diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 000000000..c282e9a1a --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,14 @@ +# Contributing + +This project welcomes contributions and suggestions. Most contributions require you to +agree to a Contributor License Agreement (CLA) declaring that you have the right to, +and actually do, grant us the rights to use your contribution. For details, visit +https://cla.microsoft.com. + +When you submit a pull request, a CLA-bot will automatically determine whether you need +to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the +instructions provided by the bot. You will only need to do this once across all repositories using our CLA. + +This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). +For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) +or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. \ No newline at end of file diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 000000000..848b154f6 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,21 @@ +Copyright (c) Microsoft Corporation. All rights reserved. + +## MIT License + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/NOTICE.md b/NOTICE.md new file mode 100644 index 000000000..f9dbffd81 --- /dev/null +++ b/NOTICE.md @@ -0,0 +1,655 @@ +# NOTICES AND INFORMATION + +``` +Do Not Translate or Localize + +This software incorporates material from third parties. Microsoft makes certain +open source code available at http://3rdpartysource.microsoft.com, or you may +send a check or money order for US $5.00, including the product name, the open +source component name, and version number, to: + +Source Code Compliance Team +Microsoft Corporation +One Microsoft Way +Redmond, WA 98052 +USA + +Notwithstanding any other terms, you may reverse engineer this software to the +extent required to debug changes to any libraries licensed under the GNU Lesser +General Public License. +``` + +## arcana.cpp + +``` +MIT License + +Copyright (c) Microsoft Corporation. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE​ +``` + +``` +THIRD PARTY SOFTWARE NOTICES AND INFORMATION + +Do Not Translate or Localize​ + +This software incorporates material from third parties. Microsoft makes certain​ +open source code available at http://3rdpartysource.microsoft.com, or you may +send a check or money order for US $5.00, including the product name, the open +source component name, and version number, to:​ + +Source Code Compliance Team​ +Microsoft Corporation​ +One Microsoft Way​ +Redmond, WA 98052​ +USA​ + +Notwithstanding any other terms, you may reverse engineer this software to the ​ +extent required to debug changes to any libraries licensed under the GNU Lesser ​ +General Public License.​ + +==========​ + +WG21-SG14/SG14​ + +Boost Software License - Version 1.0 - August 17th, 2003​ + +Permission is hereby granted, free of charge, to any person or organization​ +obtaining a copy of the software and accompanying documentation covered by​ +this license (the "Software") to use, reproduce, display, distribute,​ +execute, and transmit the Software, and to prepare derivative works of the​ +Software, and to permit third-parties to whom the Software is furnished to​ +do so, all subject to the following:​ + +The copyright notices in the Software and this entire statement, including​ +the above license grant, this restriction and the following disclaimer,​ +must be included in all copies of the Software, in whole or in part, and​ +all derivative works of the Software, unless such copies or derivative​ +works are solely in the form of machine-executable object code generated by​ +a source language processor.​ + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR​ +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,​ +FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT​ +SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE​ +FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,​ +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER​ +DEALINGS IN THE SOFTWARE. +``` + +# Babylon.js + +## Apache License 2.0 (Apache) + +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +### Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +### Grant of Copyright License. + +Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +### Grant of Patent License. + +Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +### Redistribution. + +You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + +1. You must give any other recipients of the Work or Derivative Works a copy of this License; and + +2. You must cause any modified files to carry prominent notices stating that You changed the files; and + +3. You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + +4. If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. + +You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +### Submission of Contributions. + +Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +### Trademarks. + +This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +### Disclaimer of Warranty. + +Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +### Limitation of Liability. + +In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +### Accepting Warranty or Additional Liability. + +While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +## External dependencies +- jQuery PEP: https://github.com/jquery/PEP + +# base-n + +``` +Copyright (C) 2012 Andrzej Zawadzki (azawadzki@gmail.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +``` + +# bx + +``` +Copyright 2010-2019 Branimir Karadzic + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, +INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE +OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED +OF THE POSSIBILITY OF SUCH DAMAGE. +``` + +# bimg + +``` +Copyright 2010-2019 Branimir Karadzic + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, +INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE +OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED +OF THE POSSIBILITY OF SUCH DAMAGE. +``` + +# bgfx + +``` +Copyright 2010-2019 Branimir Karadzic + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, +INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE +OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED +OF THE POSSIBILITY OF SUCH DAMAGE. +``` + +# curl + +``` +COPYRIGHT AND PERMISSION NOTICE + +Copyright (c) 1996 - 2019, Daniel Stenberg, , and many +contributors, see the THANKS file. + +All rights reserved. + +Permission to use, copy, modify, and distribute this software for any purpose +with or without fee is hereby granted, provided that the above copyright +notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN +NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE +OR OTHER DEALINGS IN THE SOFTWARE. + +Except as contained in this notice, the name of a copyright holder shall not +be used in advertising or otherwise to promote the sale, use or other dealings +in this Software without prior written authorization of the copyright holder. +``` + +# glslang + +``` +Here, glslang proper means core GLSL parsing, HLSL parsing, and SPIR-V code +generation. Glslang proper requires use of two licenses, one that covers +non-preprocessing and an additional one that covers preprocessing. + +Bison was removed long ago. You can build glslang from the source grammar, +using tools of your choice, without using bison or any bison files. + +Other parts, outside of glslang proper, include: + +- gl_types.h, only needed for OpenGL-like reflection, and can be left out of + a parse and codegen project. See it for its license. + +- update_glslang_sources.py, which is not part of the project proper and does + not need to be used. + +- the SPIR-V "remapper", which is optional, but has the same license as + glslang proper + +- Google tests and SPIR-V tools, and anything in the external subdirectory + are external and optional; see them for their respective licenses. + +-------------------------------------------------------------------------------- + +The core of glslang-proper, minus the preprocessor is licenced as follows: + +// +// Copyright (C) 2015-2018 Google, Inc. +// Copyright (C) +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// +// Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// +// Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following +// disclaimer in the documentation and/or other materials provided +// with the distribution. +// +// Neither the name of 3Dlabs Inc. Ltd. nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// + +-------------------------------------------------------------------------------- + +The preprocessor has the core license stated above, plus an additional licence: + +/****************************************************************************\ +Copyright (c) 2002, NVIDIA Corporation. + +NVIDIA Corporation("NVIDIA") supplies this software to you in +consideration of your agreement to the following terms, and your use, +installation, modification or redistribution of this NVIDIA software +constitutes acceptance of these terms. If you do not agree with these +terms, please do not use, install, modify or redistribute this NVIDIA +software. + +In consideration of your agreement to abide by the following terms, and +subject to these terms, NVIDIA grants you a personal, non-exclusive +license, under NVIDIA's copyrights in this original NVIDIA software (the +"NVIDIA Software"), to use, reproduce, modify and redistribute the +NVIDIA Software, with or without modifications, in source and/or binary +forms; provided that if you redistribute the NVIDIA Software, you must +retain the copyright notice of NVIDIA, this notice and the following +text and disclaimers in all such redistributions of the NVIDIA Software. +Neither the name, trademarks, service marks nor logos of NVIDIA +Corporation may be used to endorse or promote products derived from the +NVIDIA Software without specific prior written permission from NVIDIA. +Except as expressly stated in this notice, no other rights or licenses +express or implied, are granted by NVIDIA herein, including but not +limited to any patent rights that may be infringed by your derivative +works or by other works in which the NVIDIA Software may be +incorporated. No hardware is licensed hereunder. + +THE NVIDIA SOFTWARE IS BEING PROVIDED ON AN "AS IS" BASIS, WITHOUT +WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, +INCLUDING WITHOUT LIMITATION, WARRANTIES OR CONDITIONS OF TITLE, +NON-INFRINGEMENT, MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR +ITS USE AND OPERATION EITHER ALONE OR IN COMBINATION WITH OTHER +PRODUCTS. + +IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY SPECIAL, INDIRECT, +INCIDENTAL, EXEMPLARY, CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, LOST PROFITS; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF +USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) OR ARISING IN ANY WAY +OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE +NVIDIA SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, +TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF +NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +\\****************************************************************************/ +``` + +# SPIRV-Cross + +``` + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. +``` + +# V8 + +``` +Copyright 2006-2011, the V8 project authors. All rights reserved. +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of Google Inc. nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +``` diff --git a/README.md b/README.md index 105012a95..4c0396837 100644 --- a/README.md +++ b/README.md @@ -1 +1,62 @@ -# BabylonNative \ No newline at end of file +# Babylon Native + +Build cross-platform native applications with the power of the Babylon.js JavaScript framework. + +See [this blog entry](https://medium.com/@babylonjs/babylon-native-821f1694fffc) for more details. + +*This project is under heavy development. Not all intended platforms are currently implemented. **DO NOT** use in production code.* + +## Getting Started + +*Coming soon...* + +## Development Notes + +### glslang and SPIRV-Cross + +In order to compile the WebGL GLSL shader to the required bits for the target platform, this project utilizes [glslang](https://github.com/KhronosGroup/glslang) and [SPIRV-Cross](https://github.com/KhronosGroup/SPIRV-Cross). See [ShaderCompiler.h](./Engine/ShaderCompiler.h) and its corresponding implementation for details. + +### arcana.cpp + +This project makes substantial use of the utilities contained within the [arcana.cpp](https://github.com/microsoft/arcana.cpp) project, especially the support for asynchronous task execution and thread synchronization. + +### N-API + +This project uses a subset of [node-addon-api](https://github.com/nodejs/node-addon-api) and the JavaScript part of [N-API](https://github.com/nodejs/node/blob/master/src/js_native_api.h) to target either V8 or Chakra. See [this thread](https://github.com/nodejs/abi-stable-node/issues/354) for some context. There is also [work](https://github.com/nodejs/node-addon-api/issues/399) needed to factor out the JavaScript part of node-addon-api. + +The code is located [here](./Source/Napi). Some small modifications were made to avoid node dependencies and improve performance. The Chakra version [js_native_api_chakra.cc](./Source/Napi/js_native_api_chakra.cc) came from [node_api_jsrt.cc](https://github.com/nodejs/node-chakracore/blob/master/src/node_api_jsrt.cc) and was modified to target Chakra directly. We will work on submitting these changes to the public version. + +### bgfx + +This project uses [bgfx](https://github.com/bkaradzic/bgfx) for the cross-platform rendering abstraction. It does not use the shader abstraction of bgfx, but instead [compiles the WebGL GLSL shader at runtime](#glslang-and-SPIRV-Cross) and generates the shader header that bgfx expects. See [BgfxEngine.cpp](./Source/Engine/BgfxEngine.cpp) for implementation details. + +### base-n + +This project uses [base-n](https://github.com/azawadzki/base-n) to implement base64 decoding for parsing data URLs. + +### curl + +This project uses [curl](https://curl.haxx.se/) (or, more accurately, [libcurl](https://curl.haxx.se/libcurl/)) as the backend for the provided implementation of XMLHttpRequest. At present, only a "golden path" is supported, but additional features will be added as they are required. + +### Updating Babylon.js + +To update the Babylon.js version: + +* The Babylon.js repo exists as a submodule in the [Modules/Babylon.js](Modules/Babylon.js) directory pointing to the [native](https://github.com/BabylonJS/Babylon.js/tree/native) branch. +* If desired, merge in changes from other Babylon.js branches, including from the master branch. + * This may require making changes to `src/Engine/babylon.nativeEngine.ts` to adapt to breaking changes in `src/Engine/babylon.engine.ts`. +* Follow the [Babylon.js contribution documentation](http://doc.babylonjs.com/how_to/how_to_start) instructions to install prerequisites and do your first full build. +* Run `UpdateBabylon.cmd core loaders`. + +## Contributing + +Please read [CONTRIBUTING.md](./CONTRIBUTING.md) for details on our code of conduct, and the process for submitting pull requests. + +## Reporting Security Issues + +Security issues and bugs should be reported privately, via email, to the Microsoft Security +Response Center (MSRC) at [secure@microsoft.com](mailto:secure@microsoft.com). You should +receive a response within 24 hours. If for some reason you do not, please follow up via +email to ensure we received your original message. Further information, including the +[MSRC PGP](https://technet.microsoft.com/en-us/security/dn606155) key, can be found in +the [Security TechCenter](https://technet.microsoft.com/en-us/security/default). \ No newline at end of file diff --git a/Source/Engine/BgfxEngine.cpp b/Source/Engine/BgfxEngine.cpp new file mode 100644 index 000000000..2615378b1 --- /dev/null +++ b/Source/Engine/BgfxEngine.cpp @@ -0,0 +1,1173 @@ +#include "BgfxEngine.h" + +#include +#include +#include + +#include +#include + +// TODO: this needs to be fixed in bgfx +namespace bgfx +{ + uint16_t attribToId(Attrib::Enum _attr); +} + +#define BGFX_UNIFORM_FRAGMENTBIT UINT8_C(0x10) // Copy-pasta from bgfx_p.h +#define BGFX_UNIFORM_SAMPLERBIT UINT8_C(0x20) // Copy-pasta from bgfx_p.h + +#include +#include +#include + +#include +#include + +#include +#include + +namespace babylon +{ + namespace + { + struct UniformData final + { + uint8_t Stage{}; + bgfx::UniformHandle Uniform{}; + }; + + template + inline void AppendBytes(std::vector& bytes, const AppendageT appendage) + { + auto ptr = reinterpret_cast(&appendage); + auto stride = static_cast(sizeof(AppendageT)); + bytes.insert(bytes.end(), ptr, ptr + stride); + } + + template + inline void AppendBytes(std::vector& bytes, const std::string& string) + { + auto ptr = reinterpret_cast(string.data()); + auto stride = static_cast(string.length()); + bytes.insert(bytes.end(), ptr, ptr + stride); + } + + template + inline void AppendBytes(std::vector& bytes, const gsl::span& data) + { + auto ptr = reinterpret_cast(data.data()); + auto stride = static_cast(data.size() * sizeof(ElementT)); + bytes.insert(bytes.end(), ptr, ptr + stride); + } + + void FlipYInImageBytes(gsl::span bytes, size_t rowCount, size_t rowPitch) + { + std::vector buffer{}; + buffer.reserve(rowPitch); + + for (size_t row = 0; row < rowCount / 2; row++) + { + auto frontPtr = bytes.data() + (row * rowPitch); + auto backPtr = bytes.data() + ((rowCount - row - 1) * rowPitch); + + std::memcpy(buffer.data(), frontPtr, rowPitch); + std::memcpy(frontPtr, backPtr, rowPitch); + std::memcpy(backPtr, buffer.data(), rowPitch); + } + } + + void AppendUniformBuffer(std::vector& bytes, const spirv_cross::Compiler& compiler, const spirv_cross::Resource& uniformBuffer, bool isFragment) + { + const uint8_t fragmentBit = (isFragment ? BGFX_UNIFORM_FRAGMENTBIT : 0); + + const spirv_cross::SPIRType& type = compiler.get_type(uniformBuffer.base_type_id); + for (uint32_t index = 0; index < type.member_types.size(); ++index) + { + auto name = compiler.get_member_name(uniformBuffer.base_type_id, index); + auto offset = compiler.get_member_decoration(uniformBuffer.base_type_id, index, spv::DecorationOffset); + auto memberType = compiler.get_type(type.member_types[index]); + + bgfx::UniformType::Enum bgfxType; + uint16_t regCount; + + if (memberType.basetype != spirv_cross::SPIRType::Float) + { + throw std::exception("Not supported"); + } + + if (!memberType.array.empty()) + { + throw std::exception("Not implemented"); + } + + if (memberType.columns == 1 && 1 <= memberType.vecsize && memberType.vecsize <= 4) + { + bgfxType = bgfx::UniformType::Vec4; + regCount = 1; + } + else if (memberType.columns == 4 && memberType.vecsize == 4) + { + bgfxType = bgfx::UniformType::Mat4; + regCount = 4; + } + else + { + throw std::exception("Not supported"); + } + + AppendBytes(bytes, static_cast(name.size())); + AppendBytes(bytes, name); + AppendBytes(bytes, static_cast(bgfxType | fragmentBit)); + AppendBytes(bytes, static_cast(0)); // Value "num" not used by D3D11 pipeline. + AppendBytes(bytes, static_cast(offset)); + AppendBytes(bytes, static_cast(regCount)); + } + } + + void AppendSamplers(std::vector& bytes, const spirv_cross::Compiler& compiler, const spirv_cross::SmallVector& samplers, bool isFragment, std::map& cache) + { + const uint8_t fragmentBit = (isFragment ? BGFX_UNIFORM_FRAGMENTBIT : 0); + + for (const spirv_cross::Resource& sampler : samplers) + { + AppendBytes(bytes, static_cast(sampler.name.size())); + AppendBytes(bytes, sampler.name); + AppendBytes(bytes, static_cast(bgfx::UniformType::Sampler | BGFX_UNIFORM_SAMPLERBIT)); + + // These values (num, regIndex, regCount) are not used by D3D11 pipeline. + AppendBytes(bytes, static_cast(0)); + AppendBytes(bytes, static_cast(0)); + AppendBytes(bytes, static_cast(0)); + + cache[sampler.name].Stage = compiler.get_decoration(sampler.id, spv::DecorationBinding); + } + } + + void CacheUniformHandles(bgfx::ShaderHandle shader, std::map& cache) + { + const auto MAX_UNIFORMS = 256; + bgfx::UniformHandle uniforms[MAX_UNIFORMS]; + auto numUniforms = bgfx::getShaderUniforms(shader, uniforms, MAX_UNIFORMS); + + bgfx::UniformInfo info{}; + for (uint8_t idx = 0; idx < numUniforms; idx++) + { + bgfx::getUniformInfo(uniforms[idx], info); + cache[info.name].Uniform = uniforms[idx]; + } + } + + enum class WebGLAttribType + { + BYTE = 5120, + UNSIGNED_BYTE = 5121, + SHORT = 5122, + UNSIGNED_SHORT = 5123, + INT = 5124, + UNSIGNED_INT = 5125, + FLOAT = 5126 + }; + + bgfx::AttribType::Enum ConvertAttribType(WebGLAttribType type) + { + switch (type) + { + case WebGLAttribType::UNSIGNED_BYTE: return bgfx::AttribType::Uint8; + case WebGLAttribType::SHORT: return bgfx::AttribType::Int16; + case WebGLAttribType::FLOAT: return bgfx::AttribType::Float; + } + + throw std::exception("Unsupported attribute type"); + } + } + + class BgfxEngine::Impl final + { + public: + Impl(void* nativeWindowPtr, RuntimeImpl& runtimeImpl); + ~Impl() = default; + + void Initialize(Napi::Env& env); + void UpdateSize(float width, float height); + void UpdateRenderTarget(); + void Suspend(); + + private: + using EngineDefiner = NativeEngineDefiner; + friend EngineDefiner; + + /* + The sequence to draw the red box. + + CreateTexture() + LoadTexture() + GetTextureWidth() + GetTextureHeight() + GetTextureSampling() + CreateIndexBuffer() + RequestAnimationFrame() + CreateProgram() + GetUniforms() + GetAttributes() + SetProgram() + Clear() + GetRenderWidth() + GetRenderHeight() + GetRenderWidth() + GetRenderHeight() + SetState() + CreateVertexArray() + RecordIndexBuffer() + CreateVertexBuffer() + RecordVertexBuffer() + RecordVertexBuffer() + BindVertexArray() + SetMatrix() + SetMatrix() + SetFloat4() + SetFloat3() + SetFloat4() + SetFloat4() + SetTextureWrapMode() + SetTextureAnistrophicLevel() + SetTexture() + SetFloat4() + SetFloat3() + SetFloat4() + SetFloat3() + SetFloat4() + DrawIndexed() + RequestAnimationFrame() + Present() + */ + + struct VertexArray final + { + bgfx::IndexBufferHandle indexBuffer; + std::vector vertexBuffers; + }; + + enum BlendMode {}; // TODO DEBUG + enum class Filter {}; // TODO DEBUG + enum class AddressMode {}; // TODO DEBUG + + struct TextureData final + { + ~TextureData() + { + bgfx::destroy(Texture); + + for (auto image : Images) + { + bimg::imageFree(image); + } + } + + std::vector Images{}; + bgfx::TextureHandle Texture{}; + }; + + struct ProgramData final + { + ~ProgramData() + { + bgfx::destroy(Program); + } + + std::map AttributeLocations{}; + std::map VertexUniformNameToHandle{}; + std::map FragmentUniformNameToHandle{}; + + bgfx::ProgramHandle Program{}; + }; + + void RequestAnimationFrame(const Napi::CallbackInfo& info); + Napi::Value CreateVertexArray(const Napi::CallbackInfo& info); + void DeleteVertexArray(const Napi::CallbackInfo& info); + void BindVertexArray(const Napi::CallbackInfo& info); + Napi::Value CreateIndexBuffer(const Napi::CallbackInfo& info); + void DeleteIndexBuffer(const Napi::CallbackInfo& info); + void RecordIndexBuffer(const Napi::CallbackInfo& info); + Napi::Value CreateVertexBuffer(const Napi::CallbackInfo& info); + void DeleteVertexBuffer(const Napi::CallbackInfo& info); + void RecordVertexBuffer(const Napi::CallbackInfo& info); + Napi::Value CreateProgram(const Napi::CallbackInfo& info); + Napi::Value GetUniforms(const Napi::CallbackInfo& info); + Napi::Value GetAttributes(const Napi::CallbackInfo& info); + void SetProgram(const Napi::CallbackInfo& info); + void SetState(const Napi::CallbackInfo& info); + void SetZOffset(const Napi::CallbackInfo& info); + Napi::Value GetZOffset(const Napi::CallbackInfo& info); + void SetDepthTest(const Napi::CallbackInfo& info); + Napi::Value GetDepthWrite(const Napi::CallbackInfo& info); + void SetDepthWrite(const Napi::CallbackInfo& info); + void SetColorWrite(const Napi::CallbackInfo& info); + void SetBlendMode(const Napi::CallbackInfo& info); + void SetMatrix(const Napi::CallbackInfo& info); + void SetIntArray(const Napi::CallbackInfo& info); + void SetIntArray2(const Napi::CallbackInfo& info); + void SetIntArray3(const Napi::CallbackInfo& info); + void SetIntArray4(const Napi::CallbackInfo& info); + void SetFloatArray(const Napi::CallbackInfo& info); + void SetFloatArray2(const Napi::CallbackInfo& info); + void SetFloatArray3(const Napi::CallbackInfo& info); + void SetFloatArray4(const Napi::CallbackInfo& info); + void SetMatrices(const Napi::CallbackInfo& info); + void SetMatrix3x3(const Napi::CallbackInfo& info); + void SetMatrix2x2(const Napi::CallbackInfo& info); + void SetFloat(const Napi::CallbackInfo& info); + void SetFloat2(const Napi::CallbackInfo& info); + void SetFloat3(const Napi::CallbackInfo& info); + void SetFloat4(const Napi::CallbackInfo& info); + void SetBool(const Napi::CallbackInfo& info); + Napi::Value CreateTexture(const Napi::CallbackInfo& info); + void LoadTexture(const Napi::CallbackInfo& info); + void LoadCubeTexture(const Napi::CallbackInfo& info); + Napi::Value GetTextureWidth(const Napi::CallbackInfo& info); + Napi::Value GetTextureHeight(const Napi::CallbackInfo& info); + void SetTextureSampling(const Napi::CallbackInfo& info); + void SetTextureWrapMode(const Napi::CallbackInfo& info); + void SetTextureAnisotropicLevel(const Napi::CallbackInfo& info); + void SetTexture(const Napi::CallbackInfo& info); + void DeleteTexture(const Napi::CallbackInfo& info); + void DrawIndexed(const Napi::CallbackInfo& info); + void Draw(const Napi::CallbackInfo& info); + void Clear(const Napi::CallbackInfo& info); + Napi::Value GetRenderWidth(const Napi::CallbackInfo& info); + Napi::Value GetRenderHeight(const Napi::CallbackInfo& info); + + void DispatchAnimationFrameAsync(Napi::FunctionReference callback); + + ShaderCompiler m_shaderCompiler; + + ProgramData* m_currentProgram; + + RuntimeImpl& m_runtimeImpl; + + struct + { + uint32_t Width{}; + uint32_t Height{}; + } m_size; + + bx::DefaultAllocator m_allocator; + uint64_t m_engineState; + }; + + BgfxEngine::Impl::Impl(void* nativeWindowPtr, RuntimeImpl& runtimeImpl) + : m_runtimeImpl{ runtimeImpl } + , m_size{ 1024, 768 } + , m_engineState{ BGFX_STATE_DEFAULT } + { + bgfx::Init init{}; + init.platformData.nwh = nativeWindowPtr; + bgfx::setPlatformData(init.platformData); + + init.type = bgfx::RendererType::Direct3D11; + init.resolution.width = m_size.Width; + init.resolution.height = m_size.Height; + init.resolution.reset = BGFX_RESET_VSYNC; + bgfx::init(init); + + bgfx::setViewClear(0, BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH, /*0xBB464BFF*/0x443355FF, 1.0f, 0); + bgfx::setViewRect(0, 0, 0, m_size.Width, m_size.Height); + + // STUB: Let's get ready to RENNNDERRRRRRRRRRRR!!! + } + + void BgfxEngine::Impl::Initialize(Napi::Env& env) + { + EngineDefiner::Define(env, this); + } + + void BgfxEngine::Impl::UpdateSize(float width, float height) + { + auto w = static_cast(width); + auto h = static_cast(height); + + if (w != m_size.Width || h != m_size.Height) + { + m_size = { w, h }; + UpdateRenderTarget(); + } + } + + void BgfxEngine::Impl::UpdateRenderTarget() + { + bgfx::reset(m_size.Width, m_size.Height, BGFX_RESET_VSYNC | BGFX_RESET_MSAA_X4); + bgfx::setViewRect(0, 0, 0, m_size.Width, m_size.Height); + } + + void BgfxEngine::Impl::Suspend() + { + // TODO: Figure out what this is supposed to do. + } + + // NativeEngine definitions + + void BgfxEngine::Impl::RequestAnimationFrame(const Napi::CallbackInfo& info) + { + DispatchAnimationFrameAsync(Napi::Persistent(info[0].As())); + } + + Napi::Value BgfxEngine::Impl::CreateVertexArray(const Napi::CallbackInfo& info) + { + return Napi::External::New(info.Env(), new VertexArray{}); + } + + void BgfxEngine::Impl::DeleteVertexArray(const Napi::CallbackInfo& info) + { + delete info[0].As>().Data(); + } + + void BgfxEngine::Impl::BindVertexArray(const Napi::CallbackInfo& info) + { + const auto& vertexArray = *(info[0].As>().Data()); + + bgfx::setIndexBuffer(vertexArray.indexBuffer); + + const auto numVertexBuffers = vertexArray.vertexBuffers.size(); + for (size_t index = 0; index < numVertexBuffers; ++index) + { + const auto& vertexBuffer = vertexArray.vertexBuffers[index]; + bgfx::setVertexBuffer(static_cast(index), vertexBuffer); + } + } + + Napi::Value BgfxEngine::Impl::CreateIndexBuffer(const Napi::CallbackInfo& info) + { + const Napi::TypedArray data = info[0].As(); + const bgfx::Memory* ref = bgfx::makeRef(data.As().Data(), static_cast(data.ByteLength())); + const uint16_t flags = data.TypedArrayType() == napi_typedarray_type::napi_uint16_array ? 0 : BGFX_BUFFER_INDEX32; + const bgfx::IndexBufferHandle handle = bgfx::createIndexBuffer(ref, flags); + return Napi::Value::From(info.Env(), static_cast(handle.idx)); + } + + void BgfxEngine::Impl::DeleteIndexBuffer(const Napi::CallbackInfo& info) + { + const bgfx::IndexBufferHandle handle{ static_cast(info[0].As().Uint32Value()) }; + bgfx::destroy(handle); + } + + void BgfxEngine::Impl::RecordIndexBuffer(const Napi::CallbackInfo& info) + { + VertexArray& vertexArray = *(info[0].As>().Data()); + const bgfx::IndexBufferHandle handle{ static_cast(info[1].As().Uint32Value()) }; + vertexArray.indexBuffer = handle; + } + + Napi::Value BgfxEngine::Impl::CreateVertexBuffer(const Napi::CallbackInfo& info) + { + const Napi::Uint8Array data = info[0].As(); + const uint32_t byteStride = info[1].As().Uint32Value(); + const Napi::Array infos = info[2].As(); + + bgfx::VertexDecl decl; + decl.begin(); + const uint32_t infosLength = infos.Length(); + for (uint32_t index = 0; index < infosLength; index++) + { + const Napi::Object info = infos[index].As(); + const uint32_t location = info["location"].As().Uint32Value(); + const uint32_t numElements = info["numElements"].As().Uint32Value(); + const uint32_t type = info["type"].As().Uint32Value(); + const bool normalized = info["normalized"].As().Value(); + const uint32_t byteOffset = info["byteOffset"].As().Uint32Value(); + + const bgfx::Attrib::Enum attrib = static_cast(location); + const bgfx::AttribType::Enum attribType = ConvertAttribType(static_cast(type)); + decl.add(attrib, numElements, attribType, normalized); + decl.m_offset[attrib] = static_cast(byteOffset); + } + decl.m_stride = static_cast(byteStride); + decl.end(); + + const bgfx::Memory* ref = bgfx::copy(data.Data(), static_cast(data.ByteLength())); + const bgfx::VertexBufferHandle handle = bgfx::createVertexBuffer(ref, decl); + return Napi::Value::From(info.Env(), static_cast(handle.idx)); + } + + void BgfxEngine::Impl::DeleteVertexBuffer(const Napi::CallbackInfo& info) + { + const bgfx::VertexBufferHandle handle{ static_cast(info[0].As().Uint32Value()) }; + bgfx::destroy(handle); + } + + void BgfxEngine::Impl::RecordVertexBuffer(const Napi::CallbackInfo& info) + { + VertexArray& vertexArray = *(info[0].As>().Data()); + const bgfx::VertexBufferHandle handle{ static_cast(info[1].As().Uint32Value()) }; + vertexArray.vertexBuffers.push_back(handle); + } + + Napi::Value BgfxEngine::Impl::CreateProgram(const Napi::CallbackInfo& info) + { + auto vertexSource = info[0].As().Utf8Value(); + // TODO: This is a HACK to account for the fact that DirectX and OpenGL disagree about the vertical orientation of screen space. + // Remove this ASAP when we have a more long-term plan to account for this behavior. + const auto fragmentSource = std::regex_replace(info[1].As().Utf8Value(), std::regex("dFdy\\("), "-dFdy("); + + auto programData = new ProgramData(); + + std::vector vertexBytes{}; + std::vector fragmentBytes{}; + std::map attributeLocations; + + m_shaderCompiler.Compile(vertexSource, fragmentSource, [&](ShaderCompiler::ShaderInfo vertexShaderInfo, ShaderCompiler::ShaderInfo fragmentShaderInfo) + { + constexpr uint8_t BGFX_SHADER_BIN_VERSION = 6; + + // These hashes are generated internally by BGFX's custom shader compilation pipeline, + // which we don't have access to. Fortunately, however, they aren't used for anything + // crucial; they just have to match. + constexpr uint32_t vertexOutputsHash = 0xBAD1DEA; + constexpr uint32_t fragmentInputsHash = vertexOutputsHash; + + { + const spirv_cross::Compiler& compiler = *vertexShaderInfo.Compiler; + const spirv_cross::ShaderResources resources = compiler.get_shader_resources(); + assert(resources.uniform_buffers.size() == 1); + const spirv_cross::Resource& uniformBuffer = resources.uniform_buffers[0]; + const spirv_cross::SmallVector& samplers = resources.separate_samplers; + size_t numUniforms = compiler.get_type(uniformBuffer.base_type_id).member_types.size() + samplers.size(); + + AppendBytes(vertexBytes, BX_MAKEFOURCC('V', 'S', 'H', BGFX_SHADER_BIN_VERSION)); + AppendBytes(vertexBytes, vertexOutputsHash); + AppendBytes(vertexBytes, fragmentInputsHash); + + AppendBytes(vertexBytes, static_cast(numUniforms)); + AppendUniformBuffer(vertexBytes, compiler, uniformBuffer, false); + AppendSamplers(vertexBytes, compiler, samplers, false, programData->VertexUniformNameToHandle); + + AppendBytes(vertexBytes, static_cast(vertexShaderInfo.Bytes.size())); + AppendBytes(vertexBytes, vertexShaderInfo.Bytes); + AppendBytes(vertexBytes, static_cast(0)); + + AppendBytes(vertexBytes, static_cast(resources.stage_inputs.size())); + for (const spirv_cross::Resource& stageInput : resources.stage_inputs) + { + const uint32_t location = compiler.get_decoration(stageInput.id, spv::DecorationLocation); + AppendBytes(vertexBytes, bgfx::attribToId(static_cast(location))); + attributeLocations[stageInput.name] = location; + } + + AppendBytes(vertexBytes, static_cast(compiler.get_declared_struct_size(compiler.get_type(uniformBuffer.base_type_id)))); + } + + { + const spirv_cross::Compiler& compiler = *fragmentShaderInfo.Compiler; + const spirv_cross::ShaderResources resources = compiler.get_shader_resources(); + assert(resources.uniform_buffers.size() == 1); + const spirv_cross::Resource& uniformBuffer = resources.uniform_buffers[0]; + const spirv_cross::SmallVector& samplers = resources.separate_samplers; + size_t numUniforms = compiler.get_type(uniformBuffer.base_type_id).member_types.size() + samplers.size(); + + AppendBytes(fragmentBytes, BX_MAKEFOURCC('F', 'S', 'H', BGFX_SHADER_BIN_VERSION)); + AppendBytes(fragmentBytes, vertexOutputsHash); + AppendBytes(fragmentBytes, fragmentInputsHash); + + AppendBytes(fragmentBytes, static_cast(numUniforms)); + AppendUniformBuffer(fragmentBytes, compiler, uniformBuffer, true); + AppendSamplers(fragmentBytes, compiler, samplers, true, programData->FragmentUniformNameToHandle); + + AppendBytes(fragmentBytes, static_cast(fragmentShaderInfo.Bytes.size())); + AppendBytes(fragmentBytes, fragmentShaderInfo.Bytes); + AppendBytes(fragmentBytes, static_cast(0)); + + // Fragment shaders don't have attributes. + AppendBytes(fragmentBytes, static_cast(0)); + + AppendBytes(fragmentBytes, static_cast(compiler.get_declared_struct_size(compiler.get_type(uniformBuffer.base_type_id)))); + } + }); + + auto vertexShader = bgfx::createShader(bgfx::copy(vertexBytes.data(), static_cast(vertexBytes.size()))); + CacheUniformHandles(vertexShader, programData->VertexUniformNameToHandle); + programData->AttributeLocations = std::move(attributeLocations); + + auto fragmentShader = bgfx::createShader(bgfx::copy(fragmentBytes.data(), static_cast(fragmentBytes.size()))); + CacheUniformHandles(fragmentShader, programData->FragmentUniformNameToHandle); + + programData->Program = bgfx::createProgram(vertexShader, fragmentShader); + + auto finalizer = [](Napi::Env, ProgramData* data) + { + delete data; + }; + + return Napi::External::New(info.Env(), programData, finalizer); + } + + Napi::Value BgfxEngine::Impl::GetUniforms(const Napi::CallbackInfo& info) + { + const auto program = info[0].As>().Data(); + const auto names = info[1].As(); + + auto length = names.Length(); + auto uniforms = Napi::Array::New(info.Env(), length); + for (uint32_t index = 0; index < length; ++index) + { + const auto name = names[index].As().Utf8Value(); + + auto vertexFound = program->VertexUniformNameToHandle.find(name); + auto fragmentFound = program->FragmentUniformNameToHandle.find(name); + + if (vertexFound != program->VertexUniformNameToHandle.end()) + { + uniforms[index] = Napi::External::New(info.Env(), &vertexFound->second); + } + else if (fragmentFound != program->FragmentUniformNameToHandle.end()) + { + uniforms[index] = Napi::External::New(info.Env(), &fragmentFound->second); + } + else + { + uniforms[index] = info.Env().Null(); + } + } + + return uniforms; + } + + Napi::Value BgfxEngine::Impl::GetAttributes(const Napi::CallbackInfo& info) + { + const auto program = info[0].As>().Data(); + const auto names = info[1].As(); + + const auto& attributeLocations = program->AttributeLocations; + + auto length = names.Length(); + auto attributes = Napi::Array::New(info.Env(), length); + for (uint32_t index = 0; index < length; ++index) + { + const auto name = names[index].As().Utf8Value(); + const auto it = attributeLocations.find(name); + int location = (it == attributeLocations.end() ? -1 : gsl::narrow_cast(it->second)); + attributes[index] = Napi::Value::From(info.Env(), location); + } + + return attributes; + } + + void BgfxEngine::Impl::SetProgram(const Napi::CallbackInfo& info) + { + const auto program = info[0].As>().Data(); + m_currentProgram = program; + } + + void BgfxEngine::Impl::SetState(const Napi::CallbackInfo& info) + { + const auto culling = info[0].As().Value(); + const auto reverseSide = info[2].As().Value(); + + m_engineState &= ~BGFX_STATE_CULL_MASK; + if (reverseSide) + { + m_engineState &= ~BGFX_STATE_FRONT_CCW; + + if (culling) + { + m_engineState |= BGFX_STATE_CULL_CW; + } + } + else + { + m_engineState |= BGFX_STATE_FRONT_CCW; + + if (culling) + { + m_engineState |= BGFX_STATE_CULL_CCW; + } + } + + // TODO: zOffset + const auto zOffset = info[1].As().FloatValue(); + + bgfx::setState(m_engineState); + } + + void BgfxEngine::Impl::SetZOffset(const Napi::CallbackInfo& info) + { + const auto zOffset = info[0].As().FloatValue(); + + // STUB: Stub. + } + + Napi::Value BgfxEngine::Impl::GetZOffset(const Napi::CallbackInfo& info) + { + // STUB: Stub. + return{}; + } + + void BgfxEngine::Impl::SetDepthTest(const Napi::CallbackInfo& info) + { + const auto enable = info[0].As().Value(); + + // STUB: Stub. + } + + Napi::Value BgfxEngine::Impl::GetDepthWrite(const Napi::CallbackInfo& info) + { + // STUB: Stub. + return{}; + } + + void BgfxEngine::Impl::SetDepthWrite(const Napi::CallbackInfo& info) + { + const auto enable = info[0].As().Value(); + + // STUB: Stub. + } + + void BgfxEngine::Impl::SetColorWrite(const Napi::CallbackInfo& info) + { + const auto enable = info[0].As().Value(); + + // STUB: Stub. + } + + void BgfxEngine::Impl::SetBlendMode(const Napi::CallbackInfo& info) + { + const auto blendMode = static_cast(info[0].As().Int32Value()); + + m_engineState &= ~BGFX_STATE_BLEND_MASK; + switch (blendMode) + { + case 0: + break; + case 25: + m_engineState |= BGFX_STATE_BLEND_NORMAL; + break; + default: + throw std::exception("Unsupported blend mode"); + } + + bgfx::setState(m_engineState); + } + + void BgfxEngine::Impl::SetMatrix(const Napi::CallbackInfo& info) + { + const auto uniformData = info[0].As>().Data(); + const auto matrix = info[1].As(); + assert(matrix.ElementLength() == 16); + + bgfx::setUniform(uniformData->Uniform, matrix.Data(), 1); + } + + void BgfxEngine::Impl::SetIntArray(const Napi::CallbackInfo& info) + { + // args: ShaderProperty property, gsl::span array + + assert(false); + } + + void BgfxEngine::Impl::SetIntArray2(const Napi::CallbackInfo& info) + { + // args: ShaderProperty property, gsl::span array + + assert(false); + } + + void BgfxEngine::Impl::SetIntArray3(const Napi::CallbackInfo& info) + { + // args: ShaderProperty property, gsl::span array + + assert(false); + } + + void BgfxEngine::Impl::SetIntArray4(const Napi::CallbackInfo& info) + { + // args: ShaderProperty property, gsl::span array + + assert(false); + } + + void BgfxEngine::Impl::SetFloatArray(const Napi::CallbackInfo& info) + { + const auto slot = info[0].As().Uint32Value(); + const auto array = info[1].As(); + + bgfx::UniformHandle handle{}; + // TODO: Check if the desired uniform already exists. If so, use that. If not, create one. + + bgfx::setUniform(handle, array.Data(), static_cast(array.ElementLength())); // TODO: Padding? + } + + void BgfxEngine::Impl::SetFloatArray2(const Napi::CallbackInfo& info) + { + // args: ShaderProperty property, gsl::span array + + assert(false); + } + + void BgfxEngine::Impl::SetFloatArray3(const Napi::CallbackInfo& info) + { + // args: ShaderProperty property, gsl::span array + + assert(false); + } + + void BgfxEngine::Impl::SetFloatArray4(const Napi::CallbackInfo& info) + { + // args: ShaderProperty property, gsl::span array + + assert(false); + } + + void BgfxEngine::Impl::SetMatrices(const Napi::CallbackInfo& info) + { + const auto slot = info[0].As().Uint32Value(); + const auto matricesArray = info[1].As(); + assert(matricesArray.ElementLength() % 16 == 0); + + // STUB: Stub. + } + + void BgfxEngine::Impl::SetMatrix3x3(const Napi::CallbackInfo& info) + { + // args: ShaderProperty property, gsl::span matrix + + assert(false); + } + + void BgfxEngine::Impl::SetMatrix2x2(const Napi::CallbackInfo& info) + { + // args: ShaderProperty property, gsl::span matrix + + assert(false); + } + + void BgfxEngine::Impl::SetFloat(const Napi::CallbackInfo& info) + { + const auto uniformData = info[0].As>().Data(); + const float values[] = + { + info[1].As().FloatValue(), + 0.0f, + 0.0f, + 0.0f + }; + + bgfx::setUniform(uniformData->Uniform, values, 1); + } + + void BgfxEngine::Impl::SetFloat2(const Napi::CallbackInfo& info) + { + const auto uniformData = info[0].As>().Data(); + const float values[] = + { + info[1].As().FloatValue(), + info[2].As().FloatValue(), + 0.0f, + 0.0f + }; + + bgfx::setUniform(uniformData->Uniform, values, 1); + } + + void BgfxEngine::Impl::SetFloat3(const Napi::CallbackInfo& info) + { + const auto uniformData = info[0].As>().Data(); + const float values[] = + { + info[1].As().FloatValue(), + info[2].As().FloatValue(), + info[3].As().FloatValue(), + 0.0f + }; + + bgfx::setUniform(uniformData->Uniform, values, 1); + } + + void BgfxEngine::Impl::SetFloat4(const Napi::CallbackInfo& info) + { + const auto uniformData = info[0].As>().Data(); + const float values[] = + { + info[1].As().FloatValue(), + info[2].As().FloatValue(), + info[3].As().FloatValue(), + info[4].As().FloatValue() + }; + + bgfx::setUniform(uniformData->Uniform, values, 1); + } + + void BgfxEngine::Impl::SetBool(const Napi::CallbackInfo& info) + { + // args: ShaderProperty property, bool value + + assert(false); + } + + Napi::Value BgfxEngine::Impl::CreateTexture(const Napi::CallbackInfo& info) + { + auto textureData = new TextureData(); + + auto finalizer = [](Napi::Env, TextureData* data) + { + delete data; + }; + + return Napi::External::New(info.Env(), textureData, finalizer); + } + + void BgfxEngine::Impl::LoadTexture(const Napi::CallbackInfo& info) + { + const auto textureData = info[0].As>().Data(); + const auto buffer = info[1].As(); + const auto mipMap = info[2].As().Value(); + + textureData->Images.push_back(bimg::imageParse(&m_allocator, buffer.Data(), static_cast(buffer.ByteLength()))); + auto& image = *textureData->Images.front(); + + bgfx::TextureFormat::Enum format{}; + switch (image.m_format) + { + case bimg::TextureFormat::RGBA8: + { + format = bgfx::TextureFormat::RGBA8; + break; + } + case bimg::TextureFormat::RGB8: + { + format = bgfx::TextureFormat::RGB8; + break; + } + default: + { + throw std::exception("Unexpected texture format."); + } + } + + textureData->Texture = bgfx::createTexture2D( + image.m_width, + image.m_height, + false, // TODO: generate mipmaps when requested + 1, + format, + 0, + bgfx::makeRef(image.m_data, image.m_size)); + } + + void BgfxEngine::Impl::LoadCubeTexture(const Napi::CallbackInfo& info) + { + const auto textureData = info[0].As>().Data(); + const auto mipLevelsArray = info[1].As(); + const auto flipY = info[2].As().Value(); + + std::vector> images{}; + images.reserve(mipLevelsArray.Length()); + + uint32_t totalSize = 0; + + for (uint32_t mipLevel = 0; mipLevel < mipLevelsArray.Length(); mipLevel++) + { + const auto facesArray = mipLevelsArray[mipLevel].As(); + + images.emplace_back().reserve(facesArray.Length()); + + for (uint32_t face = 0; face < facesArray.Length(); face++) + { + const auto image = facesArray[face].As(); + auto buffer = gsl::make_span(static_cast(image.ArrayBuffer().Data()) + image.ByteOffset(), image.ByteLength()); + + textureData->Images.push_back(bimg::imageParse(&m_allocator, buffer.data(), static_cast(buffer.size()))); + images.back().push_back(textureData->Images.back()); + totalSize += static_cast(images.back().back()->m_size); + } + } + + auto allPixels = bgfx::alloc(totalSize); + + auto ptr = allPixels->data; + for (uint32_t face = 0; face < images.front().size(); face++) + { + for (uint32_t mipLevel = 0; mipLevel < images.size(); mipLevel++) + { + const auto image = images[mipLevel][face]; + + std::memcpy(ptr, image->m_data, image->m_size); + + if (flipY) + { + FlipYInImageBytes(gsl::make_span(ptr, image->m_size), image->m_height, image->m_size / image->m_height); + } + + ptr += image->m_size; + } + } + + bgfx::TextureFormat::Enum format{}; + switch (images.front().front()->m_format) + { + case bimg::TextureFormat::RGBA8: + { + format = bgfx::TextureFormat::RGBA8; + break; + } + case bimg::TextureFormat::RGB8: + { + format = bgfx::TextureFormat::RGB8; + break; + } + default: + { + throw std::exception("Unexpected texture format."); + } + } + + textureData->Texture = bgfx::createTextureCube( + images.front().front()->m_width, // Side size + true, // Has mips + 1, // Number of layers + format, // Self-explanatory + 0x0, // Flags + allPixels); // Memory + } + + Napi::Value BgfxEngine::Impl::GetTextureWidth(const Napi::CallbackInfo& info) + { + const auto textureData = info[0].As>().Data(); + assert(textureData->Images.size() > 0 && !textureData->Images.front()->m_cubeMap); + return Napi::Value::From(info.Env(), textureData->Images.front()->m_width); + } + + Napi::Value BgfxEngine::Impl::GetTextureHeight(const Napi::CallbackInfo& info) + { + const auto textureData = info[0].As>().Data(); + assert(textureData->Images.size() > 0 && !textureData->Images.front()->m_cubeMap); + return Napi::Value::From(info.Env(), textureData->Images.front()->m_width); + } + + void BgfxEngine::Impl::SetTextureSampling(const Napi::CallbackInfo& info) + { + const auto textureData = info[0].As>().Data(); + const auto filter = static_cast(info[1].As().Uint32Value()); + + // STUB: Stub. + } + + void BgfxEngine::Impl::SetTextureWrapMode(const Napi::CallbackInfo& info) + { + const auto textureData = info[0].As>().Data(); + const auto addressModeU = static_cast(info[1].As().Uint32Value()); + const auto addressModeV = static_cast(info[2].As().Uint32Value()); + const auto addressModeW = static_cast(info[3].As().Uint32Value()); + + // STUB: Stub. + } + + void BgfxEngine::Impl::SetTextureAnisotropicLevel(const Napi::CallbackInfo& info) + { + const auto textureData = info[0].As>().Data(); + const auto value = info[1].As().Uint32Value(); + + // STUB: Stub. + } + + void BgfxEngine::Impl::SetTexture(const Napi::CallbackInfo& info) + { + const auto uniformData = info[0].As>().Data(); + const auto textureData = info[1].As>().Data(); + + bgfx::setTexture(uniformData->Stage, uniformData->Uniform, textureData->Texture); + } + + void BgfxEngine::Impl::DeleteTexture(const Napi::CallbackInfo& info) + { + const auto textureData = info[0].As>().Data(); + delete textureData; + } + + void BgfxEngine::Impl::DrawIndexed(const Napi::CallbackInfo& info) + { + const auto fillMode = info[0].As().Int32Value(); + const auto elementStart = info[1].As().Int32Value(); + const auto elementCount = info[2].As().Int32Value(); + + // TODO: handle viewport + bgfx::submit(0, m_currentProgram->Program); + } + + void BgfxEngine::Impl::Draw(const Napi::CallbackInfo& info) + { + const auto fillMode = info[0].As().Int32Value(); + const auto elementStart = info[1].As().Int32Value(); + const auto elementCount = info[2].As().Int32Value(); + + // STUB: Stub. + // bgfx::submit(), right? Which means we have to preserve here the state of + // which program is being worked on. + } + + void BgfxEngine::Impl::Clear(const Napi::CallbackInfo& info) + { + auto r = info[0].As().FloatValue(); + auto g = info[1].As().FloatValue(); + auto b = info[2].As().FloatValue(); + auto a = info[3].As().FloatValue(); + auto backBuffer = info[4].As().Value(); + auto depth = info[5].As().Value(); + auto stencil = info[6].As().Value(); + + // TODO CHECK: Does this have meaning for BGFX? BGFX seems to call clear() + // on its own, depending on the settings. + } + + Napi::Value BgfxEngine::Impl::GetRenderWidth(const Napi::CallbackInfo& info) + { + // TODO CHECK: Is this not just the size? What is this? + return Napi::Value::From(info.Env(), m_size.Width); + } + + Napi::Value BgfxEngine::Impl::GetRenderHeight(const Napi::CallbackInfo& info) + { + // TODO CHECK: Is this not just the size? What is this? + return Napi::Value::From(info.Env(), m_size.Height); + } + + void BgfxEngine::Impl::DispatchAnimationFrameAsync(Napi::FunctionReference callback) + { + // The purpose of encapsulating the callbackPtr in a std::shared_ptr is because, under the hood, the lambda is + // put into a kind of function which requires a copy constructor for all of its captured variables. Because + // the Napi::FunctionReference is not copyable, this breaks when trying to capture the callback directly, so we + // wrap it in a std::shared_ptr to allow the capture to function correctly. + m_runtimeImpl.Execute([this, callbackPtr = std::make_shared(std::move(callback))](auto&) + { + //bgfx_test(static_cast(m_size.Width), static_cast(m_size.Height)); + + callbackPtr->Call({}); + bgfx::frame(); + }); + } + + // BgfxEngine exterior definitions. + + BgfxEngine::BgfxEngine(void* nativeWindowPtr, RuntimeImpl& runtimeImpl) + : m_impl{ std::make_unique(nativeWindowPtr, runtimeImpl) } + {} + + BgfxEngine::~BgfxEngine() + {} + + void BgfxEngine::Initialize(Napi::Env& env) + { + m_impl->Initialize(env); + } + + void BgfxEngine::UpdateSize(float width, float height) + { + m_impl->UpdateSize(width, height); + } + + void BgfxEngine::UpdateRenderTarget() + { + m_impl->UpdateRenderTarget(); + } + + void BgfxEngine::Suspend() + { + m_impl->Suspend(); + } +} diff --git a/Source/Engine/BgfxEngine.h b/Source/Engine/BgfxEngine.h new file mode 100644 index 000000000..5470b4602 --- /dev/null +++ b/Source/Engine/BgfxEngine.h @@ -0,0 +1,24 @@ +#include + +#include + +namespace babylon +{ + class RuntimeImpl; + + class BgfxEngine final + { + public: + BgfxEngine(void* nativeWindowPtr, RuntimeImpl&); + ~BgfxEngine(); + + void Initialize(Napi::Env& env); + void UpdateSize(float width, float height); + void UpdateRenderTarget(); + void Suspend(); + + private: + class Impl; + std::unique_ptr m_impl; + }; +} diff --git a/Source/Engine/NapiBridge.h b/Source/Engine/NapiBridge.h new file mode 100644 index 000000000..7d174961e --- /dev/null +++ b/Source/Engine/NapiBridge.h @@ -0,0 +1,142 @@ +#pragma once + +#include + +#include +#include + +namespace babylon +{ + template + struct NapiBridge final : public Napi::ObjectWrap> + { + class Definition + { + friend NapiBridge; + + public: + Definition(const Definition&) = delete; + Definition& operator=(const Definition&) = delete; + + template + Definition& AddVoidReturningMethod(const std::string& name) + { + m_propertyDescriptors.push_back(InstanceMethod(name.c_str(), &NapiBridge::InstanceMethodImpl, napi_default, m_impl)); + return *this; + } + + template + Definition& AddValueReturningMethod(const std::string& name) + { + m_propertyDescriptors.push_back(InstanceMethod(name.c_str(), &NapiBridge::InstanceMethodImpl, napi_default, m_impl)); + return *this; + } + + Napi::Function Finalize() + { + return DefineClass(m_env, m_name.c_str(), m_propertyDescriptors, m_impl); + } + + private: + Definition(const std::string& name, Napi::Env& env, ImplT* impl) + : m_name{ name } + , m_env{ env } + , m_impl{ impl } + {} + + const std::string m_name{}; + Napi::Env& m_env{}; + ImplT* m_impl{}; + std::vector>> m_propertyDescriptors{}; + }; + + static Definition Define(const std::string& name, Napi::Env& env, ImplT* impl) + { + return{ name, env, impl }; + } + + explicit NapiBridge(const Napi::CallbackInfo& info) + : Napi::ObjectWrap>{ info } + {} + + template + inline void InstanceMethodImpl(const Napi::CallbackInfo& info) + { + auto impl = reinterpret_cast(info.Data()); + (impl->*method)(info); + } + + template + inline Napi::Value InstanceMethodImpl(const Napi::CallbackInfo& info) + { + auto impl = reinterpret_cast(info.Data()); + return (impl->*method)(info); + } + }; + + template + struct NativeEngineDefiner + { + static void Define(Napi::Env& env, NativeEngineT* impl) + { + Napi::HandleScope scope{ env }; + auto func = NapiBridge::Define("NativeEngine", env, impl) + .AddVoidReturningMethod<&NativeEngineT::RequestAnimationFrame>("requestAnimationFrame") + .AddValueReturningMethod<&NativeEngineT::CreateVertexArray>("createVertexArray") + .AddVoidReturningMethod<&NativeEngineT::DeleteVertexArray>("deleteVertexArray") + .AddVoidReturningMethod<&NativeEngineT::BindVertexArray>("bindVertexArray") + .AddValueReturningMethod<&NativeEngineT::CreateIndexBuffer>("createIndexBuffer") + .AddVoidReturningMethod<&NativeEngineT::DeleteIndexBuffer>("deleteIndexBuffer") + .AddVoidReturningMethod<&NativeEngineT::RecordIndexBuffer>("recordIndexBuffer") + .AddValueReturningMethod<&NativeEngineT::CreateVertexBuffer>("createVertexBuffer") + .AddVoidReturningMethod<&NativeEngineT::DeleteVertexBuffer>("deleteVertexBuffer") + .AddVoidReturningMethod<&NativeEngineT::RecordVertexBuffer>("recordVertexBuffer") + .AddValueReturningMethod<&NativeEngineT::CreateProgram>("createProgram") + .AddValueReturningMethod<&NativeEngineT::GetUniforms>("getUniforms") + .AddValueReturningMethod<&NativeEngineT::GetAttributes>("getAttributes") + .AddVoidReturningMethod<&NativeEngineT::SetProgram>("setProgram") + .AddVoidReturningMethod<&NativeEngineT::SetState>("setState") + .AddVoidReturningMethod<&NativeEngineT::SetZOffset>("setZOffset") + .AddValueReturningMethod<&NativeEngineT::GetZOffset>("getZOffset") + .AddVoidReturningMethod<&NativeEngineT::SetDepthTest>("setDepthTest") + .AddValueReturningMethod<&NativeEngineT::GetDepthWrite>("getDepthWrite") + .AddVoidReturningMethod<&NativeEngineT::SetDepthWrite>("setDepthWrite") + .AddVoidReturningMethod<&NativeEngineT::SetColorWrite>("setColorWrite") + .AddVoidReturningMethod<&NativeEngineT::SetBlendMode>("setBlendMode") + .AddVoidReturningMethod<&NativeEngineT::SetMatrix>("setMatrix") + .AddVoidReturningMethod<&NativeEngineT::SetIntArray>("setIntArray") + .AddVoidReturningMethod<&NativeEngineT::SetIntArray2>("setIntArray2") + .AddVoidReturningMethod<&NativeEngineT::SetIntArray3>("setIntArray3") + .AddVoidReturningMethod<&NativeEngineT::SetIntArray4>("setIntArray4") + .AddVoidReturningMethod<&NativeEngineT::SetFloatArray>("setFloatArray") + .AddVoidReturningMethod<&NativeEngineT::SetFloatArray2>("setFloatArray2") + .AddVoidReturningMethod<&NativeEngineT::SetFloatArray3>("setFloatArray3") + .AddVoidReturningMethod<&NativeEngineT::SetFloatArray4>("setFloatArray4") + .AddVoidReturningMethod<&NativeEngineT::SetMatrices>("setMatrices") + .AddVoidReturningMethod<&NativeEngineT::SetMatrix3x3>("setMatrix3x3") + .AddVoidReturningMethod<&NativeEngineT::SetMatrix2x2>("setMatrix2x2") + .AddVoidReturningMethod<&NativeEngineT::SetFloat>("setFloat") + .AddVoidReturningMethod<&NativeEngineT::SetFloat2>("setFloat2") + .AddVoidReturningMethod<&NativeEngineT::SetFloat3>("setFloat3") + .AddVoidReturningMethod<&NativeEngineT::SetFloat4>("setFloat4") + .AddVoidReturningMethod<&NativeEngineT::SetBool>("setBool") + .AddValueReturningMethod<&NativeEngineT::CreateTexture>("createTexture") + .AddVoidReturningMethod<&NativeEngineT::LoadTexture>("loadTexture") + .AddVoidReturningMethod<&NativeEngineT::LoadCubeTexture>("loadCubeTexture") + .AddValueReturningMethod<&NativeEngineT::GetTextureWidth>("getTextureWidth") + .AddValueReturningMethod<&NativeEngineT::GetTextureHeight>("getTextureHeight") + .AddVoidReturningMethod<&NativeEngineT::SetTextureSampling>("setTextureSampling") + .AddVoidReturningMethod<&NativeEngineT::SetTextureWrapMode>("setTextureWrapMode") + .AddVoidReturningMethod<&NativeEngineT::SetTextureAnisotropicLevel>("setTextureAnisotropicLevel") + .AddVoidReturningMethod<&NativeEngineT::SetTexture>("setTexture") + .AddVoidReturningMethod<&NativeEngineT::DeleteTexture>("deleteTexture") + .AddVoidReturningMethod<&NativeEngineT::DrawIndexed>("drawIndexed") + .AddVoidReturningMethod<&NativeEngineT::Draw>("draw") + .AddVoidReturningMethod<&NativeEngineT::Clear>("clear") + .AddValueReturningMethod<&NativeEngineT::GetRenderWidth>("getRenderWidth") + .AddValueReturningMethod<&NativeEngineT::GetRenderHeight>("getRenderHeight") + .Finalize(); + env.Global().Set("nativeEngine", func.New({})); + } + }; +} diff --git a/Source/Engine/ShaderCompiler.h b/Source/Engine/ShaderCompiler.h new file mode 100644 index 000000000..cdb8eb013 --- /dev/null +++ b/Source/Engine/ShaderCompiler.h @@ -0,0 +1,23 @@ +#pragma once + +#include +#include +#include + +namespace babylon +{ + class ShaderCompiler + { + public: + ShaderCompiler(); + ~ShaderCompiler(); + + struct ShaderInfo + { + std::unique_ptr Compiler; + gsl::span Bytes; + }; + + void Compile(std::string_view vertexSource, std::string_view fragmentSource, std::function onCompiled); + }; +} diff --git a/Source/Engine/ShaderCompilerD3D.cpp b/Source/Engine/ShaderCompilerD3D.cpp new file mode 100644 index 000000000..6bc3632c9 --- /dev/null +++ b/Source/Engine/ShaderCompilerD3D.cpp @@ -0,0 +1,124 @@ +#include "ShaderCompiler.h" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace glslang +{ + extern const TBuiltInResource DefaultTBuiltInResource; +} + +namespace babylon +{ + namespace + { + void AddShader(glslang::TProgram& program, glslang::TShader& shader, std::string_view source) + { + const std::array sources{ source.data() }; + shader.setStrings(sources.data(), sources.size()); + shader.setEnvInput(glslang::EShSourceGlsl, shader.getStage(), glslang::EShClientVulkan, 100); + shader.setEnvClient(glslang::EShClientVulkan, glslang::EShTargetVulkan_1_0); + shader.setEnvTarget(glslang::EShTargetSpv, glslang::EShTargetSpv_1_0); + + // TODO: Do this to avoid the work around for dFdy? + //shader->setInvertY(true); + + if (!shader.parse(&glslang::DefaultTBuiltInResource, 450, false, EShMsgDefault)) + { + throw std::exception(shader.getInfoDebugLog()); + } + + program.addShader(&shader); + } + + std::unique_ptr CompileShader(glslang::TProgram& program, EShLanguage stage, gsl::span attributes, ID3DBlob** blob) + { + std::vector spirv; + glslang::GlslangToSpv(*program.getIntermediate(stage), spirv); + + spirv_cross::Parser parser{ std::move(spirv) }; + parser.parse(); + + auto compiler = std::make_unique(parser.get_parsed_ir()); + compiler->set_hlsl_options({ 40 }); + + for (const auto& attribute : attributes) + { + compiler->add_vertex_attribute_remap(attribute); + } + + std::string hlsl = compiler->compile(); + + Microsoft::WRL::ComPtr errorMsgs; + const char* target = stage == EShLangVertex ? "vs_4_0" : "ps_4_0"; + + UINT flags = 0; + +#ifdef _DEBUG + flags |= D3DCOMPILE_DEBUG; +#endif + + if (FAILED(D3DCompile(hlsl.data(), hlsl.size(), nullptr, nullptr, nullptr, "main", target, flags, 0, blob, &errorMsgs))) + { + throw new std::exception(static_cast(errorMsgs->GetBufferPointer())); + } + + return std::move(compiler); + } + } + + ShaderCompiler::ShaderCompiler() + { + glslang::InitializeProcess(); + } + + ShaderCompiler::~ShaderCompiler() + { + glslang::FinalizeProcess(); + } + + void ShaderCompiler::Compile(std::string_view vertexSource, std::string_view fragmentSource, std::function onCompiled) + { + glslang::TProgram program; + + glslang::TShader vertexShader{ EShLangVertex }; + AddShader(program, vertexShader, vertexSource); + + glslang::TShader fragmentShader{ EShLangFragment }; + AddShader(program, fragmentShader, fragmentSource); + + if (!program.link(EShMsgDefault)) + { + throw std::exception(program.getInfoDebugLog()); + } + + static const spirv_cross::HLSLVertexAttributeRemap attributes[] = + { + { bgfx::Attrib::Position, "POSITION" }, + { bgfx::Attrib::Normal, "NORMAL" }, + { bgfx::Attrib::Tangent, "TANGENT" }, + { bgfx::Attrib::TexCoord0, "TEXCOORD0" }, + { bgfx::Attrib::TexCoord1, "TEXCOORD1" }, + { bgfx::Attrib::Color0, "COLOR" }, + { bgfx::Attrib::Indices, "BLENDINDICES" }, + { bgfx::Attrib::Weight, "BLENDWEIGHT" } + }; + + Microsoft::WRL::ComPtr vertexBlob; + auto vertexCompiler = CompileShader(program, EShLangVertex, attributes, &vertexBlob); + + Microsoft::WRL::ComPtr fragmentBlob; + auto fragmentCompiler = CompileShader(program, EShLangFragment, {}, &fragmentBlob); + + onCompiled + ( + { std::move(vertexCompiler), gsl::make_span(static_cast(vertexBlob->GetBufferPointer()), vertexBlob->GetBufferSize()) }, + { std::move(fragmentCompiler), gsl::make_span(static_cast(fragmentBlob->GetBufferPointer()), fragmentBlob->GetBufferSize()) } + ); + } +} diff --git a/Source/Napi/env_chakra.cc b/Source/Napi/env_chakra.cc new file mode 100644 index 000000000..6a8b59535 --- /dev/null +++ b/Source/Napi/env_chakra.cc @@ -0,0 +1,12 @@ +#include "env_chakra.h" +#include "js_native_api_chakra.h" + +napi_env napi_create_env() +{ + return new napi_env__(); +} + +void napi_destroy_env(napi_env env) +{ + delete env; +} diff --git a/Source/Napi/env_chakra.h b/Source/Napi/env_chakra.h new file mode 100644 index 000000000..83139c81b --- /dev/null +++ b/Source/Napi/env_chakra.h @@ -0,0 +1,6 @@ +#pragma once + +#include "js_native_api_types.h" + +napi_env napi_create_env(); +void napi_destroy_env(napi_env env); diff --git a/Source/Napi/env_v8.cc b/Source/Napi/env_v8.cc new file mode 100644 index 000000000..0bbf019dc --- /dev/null +++ b/Source/Napi/env_v8.cc @@ -0,0 +1,39 @@ +#include "env_v8.h" +#include "js_native_api_v8.h" + +namespace +{ + struct napi_env_base + { + explicit napi_env_base(v8::Isolate* isolate) + : isolate_scope(isolate) + , isolate_handle_scope(isolate) + { + } + + v8::Isolate::Scope isolate_scope; + v8::HandleScope isolate_handle_scope; + }; + + struct napi_env_local : public napi_env_base, public napi_env__ + { + explicit napi_env_local(v8::Isolate* isolate) + : napi_env_base(isolate) + , napi_env__(v8::Context::New(isolate)) + , context_scope(context()) + { + } + + v8::Context::Scope context_scope; + }; +} + +napi_env napi_create_env(v8::Isolate* isolate) +{ + return new napi_env_local(isolate); +} + +void napi_destroy_env(napi_env env) +{ + delete static_cast(env); +} \ No newline at end of file diff --git a/Source/Napi/env_v8.h b/Source/Napi/env_v8.h new file mode 100644 index 000000000..0f5b50d7c --- /dev/null +++ b/Source/Napi/env_v8.h @@ -0,0 +1,7 @@ +#pragma once + +#include +#include + +napi_env napi_create_env(v8::Isolate* isolate); +void napi_destroy_env(napi_env env); diff --git a/Source/Napi/js_native_api.h b/Source/Napi/js_native_api.h new file mode 100644 index 000000000..86f961089 --- /dev/null +++ b/Source/Napi/js_native_api.h @@ -0,0 +1,486 @@ +#ifndef SRC_JS_NATIVE_API_H_ +#define SRC_JS_NATIVE_API_H_ + +#include +#include +#include "js_native_api_types.h" + +#ifndef NAPI_VERSION +#ifdef NAPI_EXPERIMENTAL +// Use INT_MAX, this should only be consumed by the pre-processor anyway. +#define NAPI_VERSION 2147483647 +#else +// The baseline version for N-API +#define NAPI_VERSION 3 +#endif +#endif + +// If you need __declspec(dllimport), either include instead, or +// define NAPI_EXTERN as __declspec(dllimport) on the compiler's command line. +#ifndef NAPI_EXTERN + #ifdef _WIN32 + #define NAPI_EXTERN __declspec(dllexport) + #else + #define NAPI_EXTERN /* nothing */ + #endif +#endif + +#define NAPI_AUTO_LENGTH SIZE_MAX + +#ifdef __cplusplus +#define EXTERN_C_START extern "C" { +#define EXTERN_C_END } +#else +#define EXTERN_C_START +#define EXTERN_C_END +#endif + +EXTERN_C_START + +NAPI_EXTERN napi_status +napi_get_last_error_info(napi_env env, + const napi_extended_error_info** result); + +// Getters for defined singletons +NAPI_EXTERN napi_status napi_get_undefined(napi_env env, napi_value* result); +NAPI_EXTERN napi_status napi_get_null(napi_env env, napi_value* result); +NAPI_EXTERN napi_status napi_get_global(napi_env env, napi_value* result); +NAPI_EXTERN napi_status napi_get_boolean(napi_env env, + bool value, + napi_value* result); + +// Methods to create Primitive types/Objects +NAPI_EXTERN napi_status napi_create_object(napi_env env, napi_value* result); +NAPI_EXTERN napi_status napi_create_array(napi_env env, napi_value* result); +NAPI_EXTERN napi_status napi_create_array_with_length(napi_env env, + size_t length, + napi_value* result); +NAPI_EXTERN napi_status napi_create_double(napi_env env, + double value, + napi_value* result); +NAPI_EXTERN napi_status napi_create_int32(napi_env env, + int32_t value, + napi_value* result); +NAPI_EXTERN napi_status napi_create_uint32(napi_env env, + uint32_t value, + napi_value* result); +NAPI_EXTERN napi_status napi_create_int64(napi_env env, + int64_t value, + napi_value* result); +NAPI_EXTERN napi_status napi_create_string_latin1(napi_env env, + const char* str, + size_t length, + napi_value* result); +NAPI_EXTERN napi_status napi_create_string_utf8(napi_env env, + const char* str, + size_t length, + napi_value* result); +NAPI_EXTERN napi_status napi_create_string_utf16(napi_env env, + const char16_t* str, + size_t length, + napi_value* result); +NAPI_EXTERN napi_status napi_create_symbol(napi_env env, + napi_value description, + napi_value* result); +NAPI_EXTERN napi_status napi_create_function(napi_env env, + const char* utf8name, + size_t length, + napi_callback cb, + void* data, + napi_value* result); +NAPI_EXTERN napi_status napi_create_error(napi_env env, + napi_value code, + napi_value msg, + napi_value* result); +NAPI_EXTERN napi_status napi_create_type_error(napi_env env, + napi_value code, + napi_value msg, + napi_value* result); +NAPI_EXTERN napi_status napi_create_range_error(napi_env env, + napi_value code, + napi_value msg, + napi_value* result); + +// Methods to get the native napi_value from Primitive type +NAPI_EXTERN napi_status napi_typeof(napi_env env, + napi_value value, + napi_valuetype* result); +NAPI_EXTERN napi_status napi_get_value_double(napi_env env, + napi_value value, + double* result); +NAPI_EXTERN napi_status napi_get_value_int32(napi_env env, + napi_value value, + int32_t* result); +NAPI_EXTERN napi_status napi_get_value_uint32(napi_env env, + napi_value value, + uint32_t* result); +NAPI_EXTERN napi_status napi_get_value_int64(napi_env env, + napi_value value, + int64_t* result); +NAPI_EXTERN napi_status napi_get_value_bool(napi_env env, + napi_value value, + bool* result); + +// Copies LATIN-1 encoded bytes from a string into a buffer. +NAPI_EXTERN napi_status napi_get_value_string_latin1(napi_env env, + napi_value value, + char* buf, + size_t bufsize, + size_t* result); + +// Copies UTF-8 encoded bytes from a string into a buffer. +NAPI_EXTERN napi_status napi_get_value_string_utf8(napi_env env, + napi_value value, + char* buf, + size_t bufsize, + size_t* result); + +// Copies UTF-16 encoded bytes from a string into a buffer. +NAPI_EXTERN napi_status napi_get_value_string_utf16(napi_env env, + napi_value value, + char16_t* buf, + size_t bufsize, + size_t* result); + +// Methods to coerce values +// These APIs may execute user scripts +NAPI_EXTERN napi_status napi_coerce_to_bool(napi_env env, + napi_value value, + napi_value* result); +NAPI_EXTERN napi_status napi_coerce_to_number(napi_env env, + napi_value value, + napi_value* result); +NAPI_EXTERN napi_status napi_coerce_to_object(napi_env env, + napi_value value, + napi_value* result); +NAPI_EXTERN napi_status napi_coerce_to_string(napi_env env, + napi_value value, + napi_value* result); + +// Methods to work with Objects +NAPI_EXTERN napi_status napi_get_prototype(napi_env env, + napi_value object, + napi_value* result); +NAPI_EXTERN napi_status napi_get_property_names(napi_env env, + napi_value object, + napi_value* result); +NAPI_EXTERN napi_status napi_set_property(napi_env env, + napi_value object, + napi_value key, + napi_value value); +NAPI_EXTERN napi_status napi_has_property(napi_env env, + napi_value object, + napi_value key, + bool* result); +NAPI_EXTERN napi_status napi_get_property(napi_env env, + napi_value object, + napi_value key, + napi_value* result); +NAPI_EXTERN napi_status napi_delete_property(napi_env env, + napi_value object, + napi_value key, + bool* result); +NAPI_EXTERN napi_status napi_has_own_property(napi_env env, + napi_value object, + napi_value key, + bool* result); +NAPI_EXTERN napi_status napi_set_named_property(napi_env env, + napi_value object, + const char* utf8name, + napi_value value); +NAPI_EXTERN napi_status napi_has_named_property(napi_env env, + napi_value object, + const char* utf8name, + bool* result); +NAPI_EXTERN napi_status napi_get_named_property(napi_env env, + napi_value object, + const char* utf8name, + napi_value* result); +NAPI_EXTERN napi_status napi_set_element(napi_env env, + napi_value object, + uint32_t index, + napi_value value); +NAPI_EXTERN napi_status napi_has_element(napi_env env, + napi_value object, + uint32_t index, + bool* result); +NAPI_EXTERN napi_status napi_get_element(napi_env env, + napi_value object, + uint32_t index, + napi_value* result); +NAPI_EXTERN napi_status napi_delete_element(napi_env env, + napi_value object, + uint32_t index, + bool* result); +NAPI_EXTERN napi_status +napi_define_properties(napi_env env, + napi_value object, + size_t property_count, + const napi_property_descriptor* properties); + +// Methods to work with Arrays +NAPI_EXTERN napi_status napi_is_array(napi_env env, + napi_value value, + bool* result); +NAPI_EXTERN napi_status napi_get_array_length(napi_env env, + napi_value value, + uint32_t* result); + +// Methods to compare values +NAPI_EXTERN napi_status napi_strict_equals(napi_env env, + napi_value lhs, + napi_value rhs, + bool* result); + +// Methods to work with Functions +NAPI_EXTERN napi_status napi_call_function(napi_env env, + napi_value recv, + napi_value func, + size_t argc, + const napi_value* argv, + napi_value* result); +NAPI_EXTERN napi_status napi_new_instance(napi_env env, + napi_value constructor, + size_t argc, + const napi_value* argv, + napi_value* result); +NAPI_EXTERN napi_status napi_instanceof(napi_env env, + napi_value object, + napi_value constructor, + bool* result); + +// Methods to work with napi_callbacks + +// Gets all callback info in a single call. (Ugly, but faster.) +NAPI_EXTERN napi_status napi_get_cb_info( + napi_env env, // [in] NAPI environment handle + napi_callback_info cbinfo, // [in] Opaque callback-info handle + size_t* argc, // [in-out] Specifies the size of the provided argv array + // and receives the actual count of args. + napi_value* argv, // [out] Array of values + napi_value* this_arg, // [out] Receives the JS 'this' arg for the call + void** data); // [out] Receives the data pointer for the callback. + +NAPI_EXTERN napi_status napi_get_new_target(napi_env env, + napi_callback_info cbinfo, + napi_value* result); +NAPI_EXTERN napi_status +napi_define_class(napi_env env, + const char* utf8name, + size_t length, + napi_callback constructor, + void* data, + size_t property_count, + const napi_property_descriptor* properties, + napi_value* result); + +// Methods to work with external data objects +NAPI_EXTERN napi_status napi_wrap(napi_env env, + napi_value js_object, + void* native_object, + napi_finalize finalize_cb, + void* finalize_hint, + napi_ref* result); +NAPI_EXTERN napi_status napi_unwrap(napi_env env, + napi_value js_object, + void** result); +NAPI_EXTERN napi_status napi_remove_wrap(napi_env env, + napi_value js_object, + void** result); +NAPI_EXTERN napi_status napi_create_external(napi_env env, + void* data, + napi_finalize finalize_cb, + void* finalize_hint, + napi_value* result); +NAPI_EXTERN napi_status napi_get_value_external(napi_env env, + napi_value value, + void** result); + +// Methods to control object lifespan + +// Set initial_refcount to 0 for a weak reference, >0 for a strong reference. +NAPI_EXTERN napi_status napi_create_reference(napi_env env, + napi_value value, + uint32_t initial_refcount, + napi_ref* result); + +// Deletes a reference. The referenced value is released, and may +// be GC'd unless there are other references to it. +NAPI_EXTERN napi_status napi_delete_reference(napi_env env, napi_ref ref); + +// Increments the reference count, optionally returning the resulting count. +// After this call the reference will be a strong reference because its +// refcount is >0, and the referenced object is effectively "pinned". +// Calling this when the refcount is 0 and the object is unavailable +// results in an error. +NAPI_EXTERN napi_status napi_reference_ref(napi_env env, + napi_ref ref, + uint32_t* result); + +// Decrements the reference count, optionally returning the resulting count. +// If the result is 0 the reference is now weak and the object may be GC'd +// at any time if there are no other references. Calling this when the +// refcount is already 0 results in an error. +NAPI_EXTERN napi_status napi_reference_unref(napi_env env, + napi_ref ref, + uint32_t* result); + +// Attempts to get a referenced value. If the reference is weak, +// the value might no longer be available, in that case the call +// is still successful but the result is NULL. +NAPI_EXTERN napi_status napi_get_reference_value(napi_env env, + napi_ref ref, + napi_value* result); + +NAPI_EXTERN napi_status napi_open_handle_scope(napi_env env, + napi_handle_scope* result); +NAPI_EXTERN napi_status napi_close_handle_scope(napi_env env, + napi_handle_scope scope); +NAPI_EXTERN napi_status +napi_open_escapable_handle_scope(napi_env env, + napi_escapable_handle_scope* result); +NAPI_EXTERN napi_status +napi_close_escapable_handle_scope(napi_env env, + napi_escapable_handle_scope scope); + +NAPI_EXTERN napi_status napi_escape_handle(napi_env env, + napi_escapable_handle_scope scope, + napi_value escapee, + napi_value* result); + +// Methods to support error handling +NAPI_EXTERN napi_status napi_throw(napi_env env, napi_value error); +NAPI_EXTERN napi_status napi_throw_error(napi_env env, + const char* code, + const char* msg); +NAPI_EXTERN napi_status napi_throw_type_error(napi_env env, + const char* code, + const char* msg); +NAPI_EXTERN napi_status napi_throw_range_error(napi_env env, + const char* code, + const char* msg); +NAPI_EXTERN napi_status napi_is_error(napi_env env, + napi_value value, + bool* result); + +// Methods to support catching exceptions +NAPI_EXTERN napi_status napi_is_exception_pending(napi_env env, bool* result); +NAPI_EXTERN napi_status napi_get_and_clear_last_exception(napi_env env, + napi_value* result); + +// Methods to work with array buffers and typed arrays +NAPI_EXTERN napi_status napi_is_arraybuffer(napi_env env, + napi_value value, + bool* result); +NAPI_EXTERN napi_status napi_create_arraybuffer(napi_env env, + size_t byte_length, + void** data, + napi_value* result); +NAPI_EXTERN napi_status +napi_create_external_arraybuffer(napi_env env, + void* external_data, + size_t byte_length, + napi_finalize finalize_cb, + void* finalize_hint, + napi_value* result); +NAPI_EXTERN napi_status napi_get_arraybuffer_info(napi_env env, + napi_value arraybuffer, + void** data, + size_t* byte_length); +NAPI_EXTERN napi_status napi_is_typedarray(napi_env env, + napi_value value, + bool* result); +NAPI_EXTERN napi_status napi_create_typedarray(napi_env env, + napi_typedarray_type type, + size_t length, + napi_value arraybuffer, + size_t byte_offset, + napi_value* result); +NAPI_EXTERN napi_status napi_get_typedarray_info(napi_env env, + napi_value typedarray, + napi_typedarray_type* type, + size_t* length, + void** data, + napi_value* arraybuffer, + size_t* byte_offset); + +NAPI_EXTERN napi_status napi_create_dataview(napi_env env, + size_t length, + napi_value arraybuffer, + size_t byte_offset, + napi_value* result); +NAPI_EXTERN napi_status napi_is_dataview(napi_env env, + napi_value value, + bool* result); +NAPI_EXTERN napi_status napi_get_dataview_info(napi_env env, + napi_value dataview, + size_t* bytelength, + void** data, + napi_value* arraybuffer, + size_t* byte_offset); + +// version management +NAPI_EXTERN napi_status napi_get_version(napi_env env, uint32_t* result); + +// Promises +NAPI_EXTERN napi_status napi_create_promise(napi_env env, + napi_deferred* deferred, + napi_value* promise); +NAPI_EXTERN napi_status napi_resolve_deferred(napi_env env, + napi_deferred deferred, + napi_value resolution); +NAPI_EXTERN napi_status napi_reject_deferred(napi_env env, + napi_deferred deferred, + napi_value rejection); +NAPI_EXTERN napi_status napi_is_promise(napi_env env, + napi_value promise, + bool* is_promise); + +// Running a script +NAPI_EXTERN napi_status napi_run_script(napi_env env, + napi_value script, + const char* sourceUrl, + napi_value* result); + +// Memory management +NAPI_EXTERN napi_status napi_adjust_external_memory(napi_env env, + int64_t change_in_bytes, + int64_t* adjusted_value); + +#ifdef NAPI_EXPERIMENTAL + +NAPI_EXTERN napi_status napi_create_bigint_int64(napi_env env, + int64_t value, + napi_value* result); +NAPI_EXTERN napi_status napi_create_bigint_uint64(napi_env env, + uint64_t value, + napi_value* result); +NAPI_EXTERN napi_status napi_create_bigint_words(napi_env env, + int sign_bit, + size_t word_count, + const uint64_t* words, + napi_value* result); +NAPI_EXTERN napi_status napi_get_value_bigint_int64(napi_env env, + napi_value value, + int64_t* result, + bool* lossless); +NAPI_EXTERN napi_status napi_get_value_bigint_uint64(napi_env env, + napi_value value, + uint64_t* result, + bool* lossless); +NAPI_EXTERN napi_status napi_get_value_bigint_words(napi_env env, + napi_value value, + int* sign_bit, + size_t* word_count, + uint64_t* words); +NAPI_EXTERN napi_status napi_add_finalizer(napi_env env, + napi_value js_object, + void* native_object, + napi_finalize finalize_cb, + void* finalize_hint, + napi_ref* result); +#endif // NAPI_EXPERIMENTAL + +EXTERN_C_END + +#endif // SRC_JS_NATIVE_API_H_ diff --git a/Source/Napi/js_native_api_chakra.cc b/Source/Napi/js_native_api_chakra.cc new file mode 100644 index 000000000..6c143d230 --- /dev/null +++ b/Source/Napi/js_native_api_chakra.cc @@ -0,0 +1,3623 @@ +/****************************************************************************** +* Experimental prototype for demonstrating VM agnostic and ABI stable API +* for native modules to use instead of using Nan and V8 APIs directly. +* +* The current status is "Experimental" and should not be used for +* production applications. The API is still subject to change +* and as an experimental feature is NOT subject to semver. +* +******************************************************************************/ + +#include +#define NAPI_EXPERIMENTAL +#include "js_native_api.h" +//#include +//#include +//#include +#include +#include +#include +#include +#include +#include +//#include "ChakraCore.h" +#include "jsrt.h" + +//#include "node_internals.h" +//#include "src/jsrtutils.h" + +// $HACK +//// Forward declare a dependency on an internal node helper +//// This is so that we don't take an additional dependency on +//// the chakrashim (v8::trycatch) and so that node doesn't +//// have to expose another public API +//namespace node { +// extern void FatalException(v8::Isolate* isolate, +// v8::Local error, +// v8::Local message); +//} + +#ifndef CALLBACK +#define CALLBACK +#endif + +#define RETURN_STATUS_IF_FALSE(condition, status) \ + do { \ + if (!(condition)) { \ + return napi_set_last_error((status)); \ + } \ + } while (0) + +#define CHECK_ENV(env) \ + if ((env) == nullptr) { \ + return napi_invalid_arg; \ + } + +#define CHECK_ARG(arg) \ + RETURN_STATUS_IF_FALSE((arg), napi_invalid_arg) + +#define CHECK_JSRT(expr) \ + do { \ + JsErrorCode err = (expr); \ + if (err != JsNoError) return napi_set_last_error(err); \ + } while (0) + +#define CHECK_JSRT_EXPECTED(expr, expected) \ + do { \ + JsErrorCode err = (expr); \ + if (err == JsErrorInvalidArgument) \ + return napi_set_last_error(expected); \ + if (err != JsNoError) return napi_set_last_error(err); \ + } while (0) + +// This does not call napi_set_last_error because the expression +// is assumed to be a NAPI function call that already did. +#define CHECK_NAPI(expr) \ + do { \ + napi_status status = (expr); \ + if (status != napi_ok) return status; \ + } while (0) + + +// utf8 multibyte codepoint start check +#define UTF8_MULTIBYTE_START(c) (((c) & 0xC0) == 0xC0) + +#define STR_AND_LENGTH(str) str, sizeof(str) - 1 + +static napi_status napi_set_last_error(napi_status error_code, + uint32_t engine_error_code = 0, + void* engine_reserved = nullptr); +static napi_status napi_set_last_error(JsErrorCode jsError, + void* engine_reserved = nullptr); +static void napi_clear_last_error(); + +// Callback Info struct as per JSRT native function. +struct CallbackInfo { + napi_value newTarget; + napi_value thisArg; + napi_value* argv; + void* data; + uint16_t argc; + bool isConstructCall; +}; + +// $HACK for ChakraCore +namespace { +std::wstring NarrowToWide(std::string_view value) +{ + int requiredSize = ::MultiByteToWideChar(CP_UTF8, 0, value.data(), static_cast(value.size()), nullptr, 0); + std::wstring wstr(requiredSize, 0); + ::MultiByteToWideChar(CP_UTF8, 0, value.data(), static_cast(value.size()), &wstr[0], requiredSize); + return std::move(wstr); +} + +STDAPI_(JsErrorCode) JsCreateString( + _In_ const char* content, + _In_ size_t length, + _Out_ JsValueRef* value) +{ + auto str = length == NAPI_AUTO_LENGTH ? NarrowToWide({ content }) : NarrowToWide({ content, length }); + return JsPointerToString(str.data(), str.size(), value); +} + +STDAPI_(JsErrorCode) JsCopyString( + _In_ JsValueRef value, + _Out_opt_ char* buffer, + _In_ size_t bufferSize, + _Out_opt_ size_t* length) +{ + const wchar_t* stringValue; + size_t stringLength; + auto errorCode = JsStringToPointer(value, &stringValue, &stringLength); + + if (length != nullptr) + { + *length = stringLength; + } + + if (buffer != nullptr) + { + ::WideCharToMultiByte(CP_UTF8, 0, stringValue, static_cast(stringLength), buffer, static_cast(bufferSize), nullptr, nullptr); + } + + return errorCode; +} + +STDAPI_(JsErrorCode) JsCreateStringUtf16( + _In_ const char16_t* content, + _In_ size_t length, + _Out_ JsValueRef* value) +{ + // $TODO: uint16_t is not wchar_t + return JsPointerToString(reinterpret_cast(content), length, value); +} + +STDAPI_(JsErrorCode) JsCopyStringUtf16( + _In_ JsValueRef value, + _Out_opt_ char16_t* buffer, + _In_ size_t bufferSize, + _Out_opt_ size_t* length) +{ + const wchar_t* stringValue; + size_t stringLength; + auto errorCode = JsStringToPointer(value, &stringValue, &stringLength); + + if (length != nullptr) + { + *length = stringLength; + } + + if (buffer != nullptr) + { + // $TODO: uint16_t is not wchar_t + memcpy_s(buffer, bufferSize, stringValue, stringLength); + } + + return errorCode; +} + +STDAPI_(JsErrorCode) JsCreatePropertyId( + _In_z_ const char *name, + _In_ size_t length, + _Out_ JsPropertyIdRef *propertyId) +{ + auto str = NarrowToWide({ name, length }); + return JsGetPropertyIdFromName(str.c_str(), propertyId); +} + +struct JsNativeFunctionInfo +{ + JsValueRef thisArg; + JsValueRef newTargetArg; + bool isConstructCall; +}; + +typedef JsValueRef(CALLBACK * JsEnhancedNativeFunction)(JsValueRef callee, JsValueRef* arguments, unsigned short argumentCount, JsNativeFunctionInfo* info, void* callbackState); + +struct JsNativeFunctionCallbackInfo +{ + JsEnhancedNativeFunction nativeFunction; + void* callbackState; + JsValueRef newTarget; +}; + +JsValueRef CALLBACK JsNativeFunctionCallback(JsValueRef callee, bool isConstructCall, JsValueRef* arguments, unsigned short argumentCount, void* callbackState) +{ + auto callbackInfo = static_cast(callbackState); + JsNativeFunctionInfo functionInfo = { arguments[0], callbackInfo->newTarget, isConstructCall }; + return callbackInfo->nativeFunction(callee, arguments, argumentCount, &functionInfo, callbackInfo->callbackState); +} + +STDAPI_(JsErrorCode) JsCreateEnhancedFunction(JsEnhancedNativeFunction nativeFunction, JsValueRef metadata, void* callbackState, JsValueRef* function) +{ + auto callbackInfo = std::make_unique(JsNativeFunctionCallbackInfo{ nativeFunction, callbackState, JS_INVALID_REFERENCE }); + auto errorCode = JsCreateNamedFunction(metadata, JsNativeFunctionCallback, callbackInfo.get(), function); + callbackInfo->newTarget = *function; + + // TODO: this is leaking memory. consolidate with code that calls this function and clean up using JsSetObjectBeforeCollectCallback + callbackInfo.release(); + + return errorCode; +} + +typedef BYTE* ChakraBytePtr; + +} // end of anonymous namespace + +namespace { + +// $HACK +//namespace v8impl { +// +////=== Conversion between V8 Isolate and napi_env ========================== +// +//class HandleScopeWrapper { +// public: +// explicit HandleScopeWrapper( +// v8::Isolate* isolate) : scope(isolate) { } +// private: +// v8::HandleScope scope; +//}; +// +//class EscapableHandleScopeWrapper { +// public: +// explicit EscapableHandleScopeWrapper( +// v8::Isolate* isolate) : scope(isolate) { } +// template +// v8::Local Escape(v8::Local handle) { +// return scope.Escape(handle); +// } +// private: +// v8::EscapableHandleScope scope; +//}; +// +////=== Conversion between V8 Handles and napi_value ======================== +// +//// This is assuming v8::Local<> will always be implemented with a single +//// pointer field so that we can pass it around as a void* (maybe we should +//// use intptr_t instead of void*) +// +//napi_value JsValueFromV8LocalValue(v8::Local local) { +// return reinterpret_cast(*local); +//} +// +//v8::Local V8LocalValueFromJsValue(napi_value v) { +// v8::Local local; +// memcpy(&local, &v, sizeof(v)); +// return local; +//} +// +//inline void TriggerFatalException( +// napi_env env, v8::Local local_err) { +// // The API requires V8 types, so use the shim until there are engine-neutral +// // core APIs. +// v8::Local local_msg = +// v8::Exception::CreateMessage(env->isolate, local_err); +// node::FatalException(env->isolate, local_err, local_msg); +//} +//} // end of namespace v8impl + +namespace jsrtimpl { + +// Adapter for JSRT external data + finalize callback. +class ExternalData { + public: + ExternalData(napi_env env, + void* data, + napi_finalize finalize_cb, + void* hint) + : _env(env), + _data(data), + _cb(finalize_cb), + _hint(hint) { + } + + void* Data() { + return _data; + } + + // JsFinalizeCallback + static void CALLBACK Finalize(void* callbackState) { + ExternalData* externalData = + reinterpret_cast(callbackState); + if (externalData != nullptr) { + if (externalData->_cb != nullptr) { + externalData->_cb( + externalData->_env, externalData->_data, externalData->_hint); + } + + delete externalData; + } + } + + // node::Buffer::FreeCallback + static void FinalizeBuffer(char* data, void* callbackState) { + Finalize(callbackState); + } + + private: + napi_env _env; + void* _data; + napi_finalize _cb; + void* _hint; +}; + +// Adapter for JSRT external callback + callback data. +class ExternalCallback { + public: + ExternalCallback(napi_env env, napi_callback cb, void* data) + : _env(env), _cb(cb), _data(data) { + } + + // JsEnhancedNativeFunction + static JsValueRef CALLBACK Callback(JsValueRef callee, + JsValueRef* arguments, + uint16_t argumentCount, + JsNativeFunctionInfo* info, + void* callbackState) { + jsrtimpl::ExternalCallback* externalCallback = + reinterpret_cast(callbackState); + + // Make sure any errors encountered last time we were in N-API are gone. + napi_clear_last_error(); + + CallbackInfo cbInfo; + cbInfo.thisArg = reinterpret_cast(info->thisArg); + cbInfo.newTarget = reinterpret_cast(info->newTargetArg); + cbInfo.isConstructCall = info->isConstructCall; + cbInfo.argc = argumentCount - 1; + cbInfo.argv = reinterpret_cast(arguments + 1); + cbInfo.data = externalCallback->_data; + + napi_value result = externalCallback->_cb( + externalCallback->_env, reinterpret_cast(&cbInfo)); + return reinterpret_cast(result); + } + + // JsObjectBeforeCollectCallback + static void CALLBACK Finalize(JsRef ref, void* callbackState) { + jsrtimpl::ExternalCallback* externalCallback = + reinterpret_cast(callbackState); + delete externalCallback; + } + + private: + napi_env _env; + napi_callback _cb; + void* _data; +}; + +class StringUtf8 { + public: + StringUtf8() : _str(nullptr), _length(0) {} + ~StringUtf8() { + if (_str != nullptr) { + free(_str); + _str = nullptr; + _length = 0; + } + } + char* operator*() { return _str; } + operator const char* () const { return _str; } + int length() const { return static_cast(_length); } + + napi_status From(JsValueRef strRef) { + //CHAKRA_ASSERT(!_str); + + size_t length = 0; + CHECK_JSRT_EXPECTED(JsCopyString(strRef, nullptr, 0, &length), + napi_string_expected); + + _str = reinterpret_cast(malloc(length + 1)); + //CHAKRA_VERIFY(_str != nullptr); + + CHECK_JSRT_EXPECTED( + JsCopyString(strRef, _str, length, nullptr), + napi_string_expected); + + _str[length] = '\0'; + _length = length; + return napi_ok; + } + + private: + // Disallow copying and assigning + StringUtf8(const StringUtf8&); + void operator=(const StringUtf8&); + + char* _str; + int _length; +}; + +inline napi_status JsPropertyIdFromKey(JsValueRef key, + JsPropertyIdRef* propertyId) { + JsValueType keyType; + CHECK_JSRT(JsGetValueType(key, &keyType)); + + if (keyType == JsString) { + StringUtf8 str; + CHECK_NAPI(str.From(key)); + + CHECK_JSRT(JsCreatePropertyId(*str, str.length(), propertyId)); + } else if (keyType == JsSymbol) { + CHECK_JSRT(JsGetPropertyIdFromSymbol(key, propertyId)); + } else { + return napi_set_last_error(napi_name_expected); + } + return napi_ok; +} + +inline napi_status +JsPropertyIdFromPropertyDescriptor(const napi_property_descriptor* p, + JsPropertyIdRef* propertyId) { + if (p->utf8name != nullptr) { + CHECK_JSRT(JsCreatePropertyId( + p->utf8name, strlen(p->utf8name), propertyId)); + return napi_ok; + } else { + return JsPropertyIdFromKey(p->name, propertyId); + } +} + +inline napi_status +JsNameValueFromPropertyDescriptor(const napi_property_descriptor* p, + napi_value* name) { + if (p->utf8name != nullptr) { + CHECK_JSRT(JsCreateString( + p->utf8name, + strlen(p->utf8name), + reinterpret_cast(name))); + } else { + *name = p->name; + } + return napi_ok; +} + +inline napi_status FindWrapper(JsValueRef obj, JsValueRef* wrapper, + JsValueRef* parent = nullptr) { + // Search the object's prototype chain for the wrapper with external data. + // Usually the wrapper would be the first in the chain, but it is OK for + // other objects to be inserted in the prototype chain. + JsValueRef candidate = obj; + JsValueRef current = JS_INVALID_REFERENCE; + bool hasExternalData = false; + + JsValueRef nullValue = JS_INVALID_REFERENCE; + CHECK_JSRT(JsGetNullValue(&nullValue)); + + do { + current = candidate; + + CHECK_JSRT(JsGetPrototype(current, &candidate)); + if (candidate == JS_INVALID_REFERENCE || candidate == nullValue) { + if (parent != nullptr) { + *parent = JS_INVALID_REFERENCE; + } + + *wrapper = JS_INVALID_REFERENCE; + return napi_ok; + } + + CHECK_JSRT(JsHasExternalData(candidate, &hasExternalData)); + } while (!hasExternalData); + + if (parent != nullptr) { + *parent = current; + } + + *wrapper = candidate; + + return napi_ok; +} + +inline napi_status Unwrap(JsValueRef obj, jsrtimpl::ExternalData** externalData, + JsValueRef* wrapper = nullptr, + JsValueRef* parent = nullptr) { + JsValueRef candidate = JS_INVALID_REFERENCE; + JsValueRef candidateParent = JS_INVALID_REFERENCE; + CHECK_NAPI(jsrtimpl::FindWrapper(obj, &candidate, &candidateParent)); + RETURN_STATUS_IF_FALSE(candidate != JS_INVALID_REFERENCE, napi_invalid_arg); + + CHECK_JSRT(JsGetExternalData(candidate, + reinterpret_cast(externalData))); + + if (wrapper != nullptr) { + *wrapper = candidate; + } + + if (parent != nullptr) { + *parent = candidateParent; + } + + return napi_ok; +} + +static napi_status SetErrorCode(JsValueRef error, + napi_value code, + const char* codeString) { + if ((code != nullptr) || (codeString != nullptr)) { + JsValueRef codeValue = reinterpret_cast(code); + if (codeValue != JS_INVALID_REFERENCE) { + JsValueType valueType = JsUndefined; + CHECK_JSRT(JsGetValueType(codeValue, &valueType)); + RETURN_STATUS_IF_FALSE(valueType == JsString, napi_string_expected); + } else { + CHECK_JSRT(JsCreateString(codeString, strlen(codeString), &codeValue)); + } + + JsPropertyIdRef codePropId = JS_INVALID_REFERENCE; + CHECK_JSRT(JsCreatePropertyId(STR_AND_LENGTH("code"), &codePropId)); + + CHECK_JSRT(JsSetProperty(error, codePropId, codeValue, true)); + + JsValueRef nameArray = JS_INVALID_REFERENCE; + CHECK_JSRT(JsCreateArray(0, &nameArray)); + + JsPropertyIdRef pushPropId = JS_INVALID_REFERENCE; + CHECK_JSRT(JsCreatePropertyId(STR_AND_LENGTH("push"), &pushPropId)); + + JsValueRef pushFunction = JS_INVALID_REFERENCE; + CHECK_JSRT(JsGetProperty(nameArray, pushPropId, &pushFunction)); + + JsPropertyIdRef namePropId = JS_INVALID_REFERENCE; + CHECK_JSRT(JsCreatePropertyId(STR_AND_LENGTH("name"), &namePropId)); + + bool hasProp = false; + CHECK_JSRT(JsHasProperty(error, namePropId, &hasProp)); + + JsValueRef nameValue = JS_INVALID_REFERENCE; + std::array args = { nameArray, JS_INVALID_REFERENCE }; + + if (hasProp) { + CHECK_JSRT(JsGetProperty(error, namePropId, &nameValue)); + + args[1] = nameValue; + CHECK_JSRT(JsCallFunction(pushFunction, + args.data(), + args.size(), + nullptr)); + } + + const char* openBracket = " ["; + JsValueRef openBracketValue = JS_INVALID_REFERENCE; + CHECK_JSRT(JsCreateString(openBracket, + strlen(openBracket), + &openBracketValue)); + + args[1] = openBracketValue; + CHECK_JSRT(JsCallFunction(pushFunction, args.data(), args.size(), nullptr)); + + args[1] = codeValue; + CHECK_JSRT(JsCallFunction(pushFunction, args.data(), args.size(), nullptr)); + + const char* closeBracket = "]"; + JsValueRef closeBracketValue = JS_INVALID_REFERENCE; + CHECK_JSRT(JsCreateString(closeBracket, + strlen(closeBracket), + &closeBracketValue)); + + args[1] = closeBracketValue; + CHECK_JSRT(JsCallFunction(pushFunction, args.data(), args.size(), nullptr)); + + JsValueRef emptyValue = JS_INVALID_REFERENCE; + CHECK_JSRT(JsCreateString("", 0, &emptyValue)); + + const char* joinPropIdName = "join"; + JsPropertyIdRef joinPropId = JS_INVALID_REFERENCE; + CHECK_JSRT(JsCreatePropertyId(joinPropIdName, + strlen(joinPropIdName), + &joinPropId)); + + JsValueRef joinFunction = JS_INVALID_REFERENCE; + CHECK_JSRT(JsGetProperty(nameArray, joinPropId, &joinFunction)); + + args[1] = emptyValue; + CHECK_JSRT(JsCallFunction(joinFunction, + args.data(), + args.size(), + &nameValue)); + + CHECK_JSRT(JsSetProperty(error, namePropId, nameValue, true)); + } + return napi_ok; +} + +napi_status ConcludeDeferred(napi_env env, + napi_deferred deferred, + const char* property, + napi_value result) { + // We do not check if property is OK, because that's not coming from outside. + CHECK_ARG(deferred); + CHECK_ARG(result); + + napi_value container, resolver, js_null; + napi_ref ref = reinterpret_cast(deferred); + + CHECK_NAPI(napi_get_reference_value(env, ref, &container)); + CHECK_NAPI(napi_get_named_property(env, container, property, &resolver)); + CHECK_NAPI(napi_get_null(env, &js_null)); + CHECK_NAPI(napi_call_function(env, js_null, resolver, 1, &result, nullptr)); + CHECK_NAPI(napi_delete_reference(env, ref)); + + return napi_ok; +} + +} // end of namespace jsrtimpl + +// $HACK +//// Intercepts the Node-V8 module registration callback. Converts parameters +//// to NAPI equivalents and then calls the registration callback specified +//// by the NAPI module. +//void napi_module_register_cb(v8::Local exports, +// v8::Local module, +// v8::Local context, +// void* priv) { +// napi_module_register_by_symbol(exports, module, context, +// static_cast(priv)->nm_register_func); +// } +} // end of anonymous namespace + +// $HACK +//void napi_module_register_by_symbol(v8::Local exports, +// v8::Local module, +// v8::Local context, +// napi_addon_register_func init) { +// if (init == nullptr) { +// node::Environment::GetCurrent(context)->ThrowError( +// "Module has no declared entry point."); +// return; +// } +// +// // Create a new napi_env for this module. Once module unloading is supported +// // we shall have to call delete on this object from there. +// v8::Isolate* isolate = context->GetIsolate(); +// napi_env env = new napi_env__(isolate, node::GetCurrentEventLoop(isolate)); +// +// napi_value _exports = init(env, v8impl::JsValueFromV8LocalValue(exports)); +// +// // If register function returned a non-null exports object different from +// // the exports object we passed it, set that as the "exports" property of +// // the module. +// if (_exports != nullptr && +// _exports != v8impl::JsValueFromV8LocalValue(exports)) { +// napi_value _module = v8impl::JsValueFromV8LocalValue(module); +// napi_set_named_property(env, _module, "exports", _exports); +// } +//} +// +//// Registers a NAPI module. +//void napi_module_register(napi_module* mod) { +// node::node_module* nm = new node::node_module { +// -1, +// mod->nm_flags, +// nullptr, +// mod->nm_filename, +// nullptr, +// napi_module_register_cb, +// mod->nm_modname, +// mod, // priv +// nullptr, +// }; +// node::node_module_register(nm); +//} +// +//napi_status napi_add_env_cleanup_hook(napi_env env, +// void (*fun)(void* arg), +// void* arg) { +// CHECK_ENV(env); +// CHECK_ARG(fun); +// +// node::AddEnvironmentCleanupHook(env->isolate, fun, arg); +// +// return napi_ok; +//} +// +//napi_status napi_remove_env_cleanup_hook(napi_env env, +// void (*fun)(void* arg), +// void* arg) { +// CHECK_ENV(env); +// CHECK_ARG(fun); +// +// node::RemoveEnvironmentCleanupHook(env->isolate, fun, arg); +// +// return napi_ok; +//} + +// Static last error returned from napi_get_last_error_info +napi_extended_error_info static_last_error; + +// Warning: Keep in-sync with napi_status enum +const char* error_messages[] = { + nullptr, + "Invalid argument", + "An object was expected", + "A string was expected", + "A string or symbol was expected", + "A function was expected", + "A number was expected", + "A boolean was expected", + "An array was expected", + "Unknown failure", + "An exception is pending", + "The async work item was cancelled", + "napi_escape_handle already called on scope", + "Invalid handle scope usage", + "Invalid callback scope usage", + "Thread-safe function queue is full", + "Thread-safe function handle is closing", + "A bigint was expected", +}; + +napi_status napi_get_last_error_info(napi_env env, + const napi_extended_error_info** result) { + CHECK_ARG(result); + + // $HACK + //static_assert( + // node::arraysize(error_messages) == napi_bigint_expected + 1, + // "Count of error messages must match count of error values"); + //assert(static_last_error.error_code <= napi_callback_scope_mismatch); + + // Wait until someone requests the last error information to fetch the error + // message string + static_last_error.error_message = + error_messages[static_last_error.error_code]; + + *result = &static_last_error; + return napi_ok; +} + +void napi_clear_last_error() { + static_last_error.error_code = napi_ok; + static_last_error.engine_error_code = 0; + static_last_error.engine_reserved = nullptr; +} + +// TODO(digitalinfinity): Does this need to be on the +// environment instead of a static error? +napi_status napi_set_last_error(napi_status error_code, + uint32_t engine_error_code, + void* engine_reserved) { + static_last_error.error_code = error_code; + static_last_error.engine_error_code = engine_error_code; + static_last_error.engine_reserved = engine_reserved; + + return error_code; +} + +napi_status napi_set_last_error(JsErrorCode jsError, void* engine_reserved) { + napi_status status; + switch (jsError) { + case JsNoError: status = napi_ok; break; + case JsErrorNullArgument: + case JsErrorInvalidArgument: status = napi_invalid_arg; break; + case JsErrorPropertyNotString: status = napi_string_expected; break; + case JsErrorArgumentNotObject: status = napi_object_expected; break; + case JsErrorScriptException: + case JsErrorInExceptionState: status = napi_pending_exception; break; + default: status = napi_generic_failure; break; + } + + static_last_error.error_code = status; + static_last_error.engine_error_code = jsError; + static_last_error.engine_reserved = engine_reserved; + return status; +} + +// $HACK +//napi_status napi_fatal_exception(napi_env env, napi_value err) { +// CHECK_ARG(err); +// +// v8::Local local_err = v8impl::V8LocalValueFromJsValue(err); +// v8impl::TriggerFatalException(env, local_err); +// +// napi_clear_last_error(); +// return napi_ok; +//} + +void napi_fatal_error(const char* location, + size_t location_len, + const char* message, + size_t message_len) { + const char* location_string = location; + const char* message_string = message; + + if (location_len != NAPI_AUTO_LENGTH) { + char* location_nullterminated = static_cast( + malloc((location_len + 1) * sizeof(char))); + strncpy(location_nullterminated, location, location_len); + location_nullterminated[location_len] = 0; + location_string = location_nullterminated; + } + + if (message_len != NAPI_AUTO_LENGTH) { + char* message_nullterminated = static_cast( + malloc((message_len + 1) * sizeof(char))); + strncpy(message_nullterminated, message, message_len); + message_nullterminated[message_len] = 0; + message_string = message_nullterminated; + } + + // $HACK + //node::FatalError(location_string, message_string); +} + +napi_status napi_create_function(napi_env env, + const char* utf8name, + size_t length, + napi_callback cb, + void* callback_data, + napi_value* result) { + CHECK_ARG(result); + + jsrtimpl::ExternalCallback* externalCallback = + new jsrtimpl::ExternalCallback(env, cb, callback_data); + if (externalCallback == nullptr) { + return napi_set_last_error(napi_generic_failure); + } + + JsValueRef function; + JsValueRef name = JS_INVALID_REFERENCE; + if (utf8name != nullptr) { + CHECK_JSRT(JsCreateString( + utf8name, + length == NAPI_AUTO_LENGTH ? strlen(utf8name) : length, + &name)); + } + + CHECK_JSRT(JsCreateEnhancedFunction( + jsrtimpl::ExternalCallback::Callback, + name, + externalCallback, + &function)); + + CHECK_JSRT(JsSetObjectBeforeCollectCallback( + function, externalCallback, jsrtimpl::ExternalCallback::Finalize)); + + *result = reinterpret_cast(function); + return napi_ok; +} + +static napi_status napi_create_property_function(napi_env env, + napi_value property_name, + napi_callback cb, + void* callback_data, + napi_value* result) { + CHECK_ARG(result); + + jsrtimpl::ExternalCallback* externalCallback = + new jsrtimpl::ExternalCallback(env, cb, callback_data); + if (externalCallback == nullptr) { + return napi_set_last_error(napi_generic_failure); + } + + napi_valuetype nameType; + CHECK_NAPI(napi_typeof(env, property_name, &nameType)); + + JsValueRef function; + JsValueRef name = JS_INVALID_REFERENCE; + if (nameType == napi_string) { + name = property_name; + } + + CHECK_JSRT(JsCreateEnhancedFunction( + jsrtimpl::ExternalCallback::Callback, + name, + externalCallback, + &function)); + + CHECK_JSRT(JsSetObjectBeforeCollectCallback( + function, externalCallback, jsrtimpl::ExternalCallback::Finalize)); + + *result = reinterpret_cast(function); + return napi_ok; +} + +napi_status napi_define_class(napi_env env, + const char* utf8name, + size_t length, + napi_callback cb, + void* data, + size_t property_count, + const napi_property_descriptor* properties, + napi_value* result) { + CHECK_ARG(result); + + napi_value namestring; + CHECK_NAPI(napi_create_string_utf8(env, utf8name, length, &namestring)); + + jsrtimpl::ExternalCallback* externalCallback = + new jsrtimpl::ExternalCallback(env, cb, data); + if (externalCallback == nullptr) { + return napi_set_last_error(napi_generic_failure); + } + + JsValueRef constructor; + CHECK_JSRT(JsCreateEnhancedFunction(jsrtimpl::ExternalCallback::Callback, + namestring, + externalCallback, + &constructor)); + + CHECK_JSRT(JsSetObjectBeforeCollectCallback( + constructor, externalCallback, jsrtimpl::ExternalCallback::Finalize)); + + JsPropertyIdRef pid = nullptr; + JsValueRef prototype = nullptr; + CHECK_JSRT(JsCreatePropertyId(STR_AND_LENGTH("prototype"), &pid)); + CHECK_JSRT(JsGetProperty(constructor, pid, &prototype)); + + CHECK_JSRT(JsCreatePropertyId(STR_AND_LENGTH("constructor"), &pid)); + CHECK_JSRT(JsSetProperty(prototype, pid, constructor, false)); + + int instancePropertyCount = 0; + int staticPropertyCount = 0; + for (size_t i = 0; i < property_count; i++) { + if ((properties[i].attributes & napi_static) != 0) { + staticPropertyCount++; + } else { + instancePropertyCount++; + } + } + + std::vector staticDescriptors; + std::vector instanceDescriptors; + staticDescriptors.reserve(staticPropertyCount); + instanceDescriptors.reserve(instancePropertyCount); + + for (size_t i = 0; i < property_count; i++) { + if ((properties[i].attributes & napi_static) != 0) { + staticDescriptors.push_back(properties[i]); + } else { + instanceDescriptors.push_back(properties[i]); + } + } + + if (staticPropertyCount > 0) { + CHECK_NAPI(napi_define_properties(env, + reinterpret_cast(constructor), + staticDescriptors.size(), + staticDescriptors.data())); + } + + if (instancePropertyCount > 0) { + CHECK_NAPI(napi_define_properties(env, + reinterpret_cast(prototype), + instanceDescriptors.size(), + instanceDescriptors.data())); + } + + *result = reinterpret_cast(constructor); + return napi_ok; +} + +napi_status napi_get_property_names(napi_env env, + napi_value object, + napi_value* result) { + CHECK_ARG(result); + JsValueRef obj = reinterpret_cast(object); + JsValueRef propertyNames; + CHECK_JSRT(JsGetOwnPropertyNames(obj, &propertyNames)); + *result = reinterpret_cast(propertyNames); + return napi_ok; +} + +napi_status napi_delete_property(napi_env env, + napi_value object, + napi_value key, + bool* result) { + CHECK_ARG(result); + *result = false; + + JsValueRef obj = reinterpret_cast(object); + JsPropertyIdRef propertyId; + JsValueRef deletePropertyResult; + CHECK_NAPI(jsrtimpl::JsPropertyIdFromKey(key, &propertyId)); + CHECK_JSRT(JsDeleteProperty(obj, propertyId, false /* isStrictMode */, + &deletePropertyResult)); + CHECK_JSRT(JsBooleanToBool(deletePropertyResult, result)); + + return napi_ok; +} + +NAPI_EXTERN napi_status napi_has_own_property(napi_env env, + napi_value object, + napi_value key, + bool* result) { + //CHECK_ARG(result); + //JsPropertyIdRef propertyId; + //CHECK_NAPI(jsrtimpl::JsPropertyIdFromKey(key, &propertyId)); + //JsValueRef obj = reinterpret_cast(object); + //CHECK_JSRT(JsHasOwnProperty(obj, propertyId, result)); + //return napi_ok; + throw new std::runtime_error("not implemented"); +} + +napi_status napi_set_named_property(napi_env env, + napi_value object, + const char* utf8name, + napi_value value) { + JsValueRef obj = reinterpret_cast(object); + JsPropertyIdRef propertyId; + CHECK_JSRT(JsCreatePropertyId(utf8name, strlen(utf8name), &propertyId)); + JsValueRef js_value = reinterpret_cast(value); + CHECK_JSRT(JsSetProperty(obj, propertyId, js_value, true)); + return napi_ok; +} + +napi_status napi_set_property(napi_env env, + napi_value object, + napi_value key, + napi_value value) { + JsValueRef obj = reinterpret_cast(object); + JsPropertyIdRef propertyId; + CHECK_NAPI(jsrtimpl::JsPropertyIdFromKey(key, &propertyId)); + JsValueRef js_value = reinterpret_cast(value); + CHECK_JSRT(JsSetProperty(obj, propertyId, js_value, true)); + return napi_ok; +} + +napi_status napi_delete_element(napi_env env, + napi_value object, + uint32_t index, + bool* result) { + CHECK_ARG(result); + JsValueRef indexValue = nullptr; + JsValueRef obj = reinterpret_cast(object); + CHECK_JSRT(JsIntToNumber(index, &indexValue)); + CHECK_JSRT(JsDeleteIndexedProperty(obj, indexValue)); + *result = true; + return napi_ok; +} + +napi_status napi_define_properties(napi_env env, + napi_value object, + size_t property_count, + const napi_property_descriptor* properties) { + JsPropertyIdRef configurableProperty; + CHECK_JSRT(JsCreatePropertyId(STR_AND_LENGTH("configurable"), + &configurableProperty)); + + JsPropertyIdRef enumerableProperty; + CHECK_JSRT(JsCreatePropertyId(STR_AND_LENGTH("enumerable"), + &enumerableProperty)); + + for (size_t i = 0; i < property_count; i++) { + const napi_property_descriptor* p = properties + i; + + JsValueRef descriptor; + CHECK_JSRT(JsCreateObject(&descriptor)); + + JsValueRef configurable; + CHECK_JSRT( + JsBoolToBoolean((p->attributes & napi_configurable), &configurable)); + CHECK_JSRT( + JsSetProperty(descriptor, configurableProperty, configurable, true)); + + JsValueRef enumerable; + CHECK_JSRT(JsBoolToBoolean((p->attributes & napi_enumerable), &enumerable)); + CHECK_JSRT(JsSetProperty(descriptor, enumerableProperty, enumerable, true)); + + if (p->getter != nullptr || p->setter != nullptr) { + napi_value property_name; + CHECK_NAPI( + jsrtimpl::JsNameValueFromPropertyDescriptor(p, &property_name)); + + if (p->getter != nullptr) { + JsPropertyIdRef getProperty; + CHECK_JSRT(JsCreatePropertyId(STR_AND_LENGTH("get"), &getProperty)); + JsValueRef getter; + CHECK_NAPI(napi_create_property_function(env, property_name, + p->getter, p->data, reinterpret_cast(&getter))); + CHECK_JSRT(JsSetProperty(descriptor, getProperty, getter, true)); + } + + if (p->setter != nullptr) { + JsPropertyIdRef setProperty; + CHECK_JSRT(JsCreatePropertyId(STR_AND_LENGTH("set"), &setProperty)); + JsValueRef setter; + CHECK_NAPI(napi_create_property_function(env, property_name, + p->setter, p->data, reinterpret_cast(&setter))); + CHECK_JSRT(JsSetProperty(descriptor, setProperty, setter, true)); + } + } else if (p->method != nullptr) { + napi_value property_name; + CHECK_NAPI( + jsrtimpl::JsNameValueFromPropertyDescriptor(p, &property_name)); + + JsPropertyIdRef valueProperty; + CHECK_JSRT(JsCreatePropertyId(STR_AND_LENGTH("value"), &valueProperty)); + JsValueRef method; + CHECK_NAPI(napi_create_property_function(env, property_name, + p->method, p->data, reinterpret_cast(&method))); + CHECK_JSRT(JsSetProperty(descriptor, valueProperty, method, true)); + } else { + RETURN_STATUS_IF_FALSE(p->value != nullptr, napi_invalid_arg); + + JsPropertyIdRef writableProperty; + CHECK_JSRT(JsCreatePropertyId(STR_AND_LENGTH("writable"), + &writableProperty)); + JsValueRef writable; + CHECK_JSRT(JsBoolToBoolean((p->attributes & napi_writable), &writable)); + CHECK_JSRT(JsSetProperty(descriptor, writableProperty, writable, true)); + + JsPropertyIdRef valueProperty; + CHECK_JSRT(JsCreatePropertyId(STR_AND_LENGTH("value"), &valueProperty)); + CHECK_JSRT(JsSetProperty(descriptor, valueProperty, + reinterpret_cast(p->value), true)); + } + + JsPropertyIdRef nameProperty; + CHECK_NAPI(jsrtimpl::JsPropertyIdFromPropertyDescriptor(p, &nameProperty)); + bool result; + CHECK_JSRT(JsDefineProperty( + reinterpret_cast(object), + reinterpret_cast(nameProperty), + reinterpret_cast(descriptor), + &result)); + } + + return napi_ok; +} + +napi_status napi_instanceof(napi_env env, + napi_value object, + napi_value c, + bool* result) { + CHECK_ARG(result); + JsValueRef obj = reinterpret_cast(object); + JsValueRef constructor = reinterpret_cast(c); + + // FIXME: Remove this type check when we switch to a version of Chakracore + // where passing an integer into JsInstanceOf as the constructor parameter + // does not cause a segfault. The need for this if-statement is removed in at + // least Chakracore 1.4.0, but maybe in an earlier version too. + napi_valuetype valuetype; + CHECK_NAPI(napi_typeof(env, c, &valuetype)); + if (valuetype != napi_function) { + napi_throw_type_error(env, + "ERR_NAPI_CONS_FUNCTION", + "constructor must be a function"); + + return napi_set_last_error(napi_invalid_arg); + } + + CHECK_JSRT(JsInstanceOf(obj, constructor, result)); + return napi_ok; +} + +napi_status napi_has_named_property(napi_env env, + napi_value object, + const char* utf8name, + bool* result) { + CHECK_ARG(result); + JsPropertyIdRef propertyId; + CHECK_JSRT(JsCreatePropertyId(utf8name, strlen(utf8name), &propertyId)); + JsValueRef obj = reinterpret_cast(object); + CHECK_JSRT(JsHasProperty(obj, propertyId, result)); + return napi_ok; +} + +napi_status napi_has_property(napi_env env, + napi_value object, + napi_value key, + bool* result) { + CHECK_ARG(result); + JsPropertyIdRef propertyId; + CHECK_NAPI(jsrtimpl::JsPropertyIdFromKey(key, &propertyId)); + JsValueRef obj = reinterpret_cast(object); + CHECK_JSRT(JsHasProperty(obj, propertyId, result)); + return napi_ok; +} + +napi_status napi_get_named_property(napi_env env, + napi_value object, + const char* utf8name, + napi_value* result) { + CHECK_ARG(result); + JsValueRef obj = reinterpret_cast(object); + JsPropertyIdRef propertyId; + CHECK_JSRT(JsCreatePropertyId(utf8name, strlen(utf8name), &propertyId)); + CHECK_JSRT( + JsGetProperty(obj, propertyId, reinterpret_cast(result))); + return napi_ok; +} + +napi_status napi_get_property(napi_env env, + napi_value object, + napi_value key, + napi_value* result) { + CHECK_ARG(result); + JsValueRef obj = reinterpret_cast(object); + JsPropertyIdRef propertyId; + CHECK_NAPI(jsrtimpl::JsPropertyIdFromKey(key, &propertyId)); + CHECK_JSRT( + JsGetProperty(obj, propertyId, reinterpret_cast(result))); + return napi_ok; +} + +napi_status napi_set_element(napi_env env, + napi_value object, + uint32_t i, + napi_value v) { + JsValueRef index = nullptr; + JsValueRef obj = reinterpret_cast(object); + JsValueRef value = reinterpret_cast(v); + CHECK_JSRT(JsIntToNumber(i, &index)); + CHECK_JSRT(JsSetIndexedProperty(obj, index, value)); + return napi_ok; +} + +napi_status napi_has_element(napi_env env, + napi_value object, + uint32_t i, + bool* result) { + CHECK_ARG(result); + JsValueRef index = nullptr; + CHECK_JSRT(JsIntToNumber(i, &index)); + JsValueRef obj = reinterpret_cast(object); + CHECK_JSRT(JsHasIndexedProperty(obj, index, result)); + return napi_ok; +} + +napi_status napi_get_element(napi_env env, + napi_value object, + uint32_t i, + napi_value* result) { + CHECK_ARG(result); + JsValueRef index = nullptr; + JsValueRef obj = reinterpret_cast(object); + CHECK_JSRT(JsIntToNumber(i, &index)); + CHECK_JSRT( + JsGetIndexedProperty(obj, index, reinterpret_cast(result))); + return napi_ok; +} + +napi_status napi_is_array(napi_env env, napi_value v, bool* result) { + CHECK_ARG(result); + JsValueRef value = reinterpret_cast(v); + JsValueType type = JsUndefined; + CHECK_JSRT(JsGetValueType(value, &type)); + *result = (type == JsArray); + return napi_ok; +} + +napi_status napi_get_array_length(napi_env env, + napi_value v, + uint32_t* result) { + CHECK_ARG(result); + JsPropertyIdRef propertyIdRef; + CHECK_JSRT(JsCreatePropertyId(STR_AND_LENGTH("length"), &propertyIdRef)); + JsValueRef lengthRef; + JsValueRef arrayRef = reinterpret_cast(v); + CHECK_JSRT(JsGetProperty(arrayRef, propertyIdRef, &lengthRef)); + double sizeInDouble; + CHECK_JSRT(JsNumberToDouble(lengthRef, &sizeInDouble)); + *result = static_cast(sizeInDouble); + return napi_ok; +} + +napi_status napi_strict_equals(napi_env env, + napi_value lhs, + napi_value rhs, + bool* result) { + CHECK_ARG(result); + JsValueRef object1 = reinterpret_cast(lhs); + JsValueRef object2 = reinterpret_cast(rhs); + CHECK_JSRT(JsStrictEquals(object1, object2, result)); + return napi_ok; +} + +napi_status napi_get_prototype(napi_env env, + napi_value object, + napi_value* result) { + CHECK_ARG(result); + JsValueRef obj = reinterpret_cast(object); + CHECK_JSRT(JsGetPrototype(obj, reinterpret_cast(result))); + return napi_ok; +} + +napi_status napi_create_object(napi_env env, napi_value* result) { + CHECK_ARG(result); + CHECK_JSRT(JsCreateObject(reinterpret_cast(result))); + return napi_ok; +} + +napi_status napi_create_array(napi_env env, napi_value* result) { + CHECK_ARG(result); + unsigned int length = 0; + CHECK_JSRT(JsCreateArray(length, reinterpret_cast(result))); + return napi_ok; +} + +napi_status napi_create_array_with_length(napi_env env, + size_t length, + napi_value* result) { + CHECK_ARG(result); + CHECK_JSRT(JsCreateArray(length, reinterpret_cast(result))); + return napi_ok; +} + +napi_status napi_create_string_latin1(napi_env env, + const char* str, + size_t length, + napi_value* result) { + // TODO(boingoing): Convert from Latin1 to UTF-8 encoding. + CHECK_ARG(result); + CHECK_JSRT(JsCreateString( + str, + length, + reinterpret_cast(result))); + return napi_ok; +} + +napi_status napi_create_string_utf8(napi_env env, + const char* str, + size_t length, + napi_value* result) { + CHECK_ARG(result); + CHECK_JSRT(JsCreateString( + str, + length, + reinterpret_cast(result))); + return napi_ok; +} + +napi_status napi_create_string_utf16(napi_env env, + const char16_t* str, + size_t length, + napi_value* result) { + CHECK_ARG(result); + CHECK_JSRT(JsCreateStringUtf16( + str, + length, + reinterpret_cast(result))); + return napi_ok; +} + +napi_status napi_create_double(napi_env env, + double value, + napi_value* result) { + CHECK_ARG(result); + CHECK_JSRT(JsDoubleToNumber(value, reinterpret_cast(result))); + return napi_ok; +} + +napi_status napi_create_int32(napi_env env, + int32_t value, + napi_value* result) { + CHECK_ARG(result); + CHECK_JSRT(JsIntToNumber(value, reinterpret_cast(result))); + return napi_ok; +} + +napi_status napi_create_uint32(napi_env env, + uint32_t value, + napi_value* result) { + CHECK_ARG(result); + CHECK_JSRT(JsDoubleToNumber(static_cast(value), + reinterpret_cast(result))); + return napi_ok; +} + +napi_status napi_create_int64(napi_env env, + int64_t value, + napi_value* result) { + CHECK_ARG(result); + CHECK_JSRT(JsDoubleToNumber(static_cast(value), + reinterpret_cast(result))); + return napi_ok; +} + +napi_status napi_create_bigint_int64(napi_env env, + int64_t value, + napi_value* result) { + // TODO(kfarnung): BigInt is not currently implemented in ChakraCore + // https://github.com/Microsoft/ChakraCore/issues/5440 + return napi_ok; +} + +napi_status napi_create_bigint_uint64(napi_env env, + uint64_t value, + napi_value* result) { + // TODO(kfarnung): BigInt is not currently implemented in ChakraCore + // https://github.com/Microsoft/ChakraCore/issues/5440 + return napi_ok; +} + +napi_status napi_create_bigint_words(napi_env env, + int sign_bit, + size_t word_count, + const uint64_t* words, + napi_value* result) { + // TODO(kfarnung): BigInt is not currently implemented in ChakraCore + // https://github.com/Microsoft/ChakraCore/issues/5440 + return napi_ok; +} + +napi_status napi_get_boolean(napi_env env, bool value, napi_value* result) { + CHECK_ARG(result); + CHECK_JSRT(JsBoolToBoolean(value, reinterpret_cast(result))); + return napi_ok; +} + +napi_status napi_create_symbol(napi_env env, + napi_value description, + napi_value* result) { + CHECK_ARG(result); + JsValueRef js_description = reinterpret_cast(description); + CHECK_JSRT( + JsCreateSymbol(js_description, reinterpret_cast(result))); + return napi_ok; +} + +napi_status napi_create_error(napi_env env, + napi_value code, + napi_value msg, + napi_value* result) { + CHECK_ARG(result); + JsValueRef message = reinterpret_cast(msg); + + JsValueRef error = JS_INVALID_REFERENCE; + CHECK_JSRT(JsCreateError(message, &error)); + CHECK_NAPI(jsrtimpl::SetErrorCode(error, code, nullptr)); + + *result = reinterpret_cast(error); + return napi_ok; +} + +napi_status napi_create_type_error(napi_env env, + napi_value code, + napi_value msg, + napi_value* result) { + CHECK_ARG(result); + JsValueRef message = reinterpret_cast(msg); + + JsValueRef error = JS_INVALID_REFERENCE; + CHECK_JSRT(JsCreateTypeError(message, &error)); + CHECK_NAPI(jsrtimpl::SetErrorCode(error, code, nullptr)); + + *result = reinterpret_cast(error); + return napi_ok; +} + +napi_status napi_create_range_error(napi_env env, + napi_value code, + napi_value msg, + napi_value* result) { + CHECK_ARG(result); + JsValueRef message = reinterpret_cast(msg); + + JsValueRef error = JS_INVALID_REFERENCE; + CHECK_JSRT( + JsCreateRangeError(message, &error)); + CHECK_NAPI(jsrtimpl::SetErrorCode(error, code, nullptr)); + + *result = reinterpret_cast(error); + return napi_ok; +} + +napi_status napi_typeof(napi_env env, napi_value vv, napi_valuetype* result) { + CHECK_ARG(result); + JsValueRef value = reinterpret_cast(vv); + JsValueType valueType = JsUndefined; + CHECK_JSRT(JsGetValueType(value, &valueType)); + + switch (valueType) { + case JsUndefined: *result = napi_undefined; break; + case JsNull: *result = napi_null; break; + case JsNumber: *result = napi_number; break; + case JsString: *result = napi_string; break; + case JsBoolean: *result = napi_boolean; break; + case JsFunction: *result = napi_function; break; + case JsSymbol: *result = napi_symbol; break; + case JsError: *result = napi_object; break; + + default: + bool hasExternalData; + if (JsHasExternalData(value, &hasExternalData) != JsNoError) { + hasExternalData = false; + } + + *result = hasExternalData ? napi_external : napi_object; + break; + } + return napi_ok; +} + +napi_status napi_get_undefined(napi_env env, napi_value* result) { + CHECK_ARG(result); + CHECK_JSRT(JsGetUndefinedValue(reinterpret_cast(result))); + return napi_ok; +} + +napi_status napi_get_null(napi_env env, napi_value* result) { + CHECK_ARG(result); + CHECK_JSRT(JsGetNullValue(reinterpret_cast(result))); + return napi_ok; +} + +napi_status napi_get_cb_info( + napi_env env, // [in] NAPI environment handle + napi_callback_info cbinfo, // [in] Opaque callback-info handle + size_t* argc, // [in-out] Specifies the size of the provided argv array + // and receives the actual count of args. + napi_value* argv, // [out] Array of values + napi_value* this_arg, // [out] Receives the JS 'this' arg for the call + void** data) { // [out] Receives the data pointer for the callback. + CHECK_ARG(cbinfo); + const CallbackInfo* info = reinterpret_cast(cbinfo); + + if (argv != nullptr) { + CHECK_ARG(argc); + + size_t i = 0; + size_t min = std::min(*argc, static_cast(info->argc)); + + for (; i < min; i++) { + argv[i] = info->argv[i]; + } + + if (i < *argc) { + napi_value undefined; + CHECK_JSRT( + JsGetUndefinedValue(reinterpret_cast(&undefined))); + for (; i < *argc; i++) { + argv[i] = undefined; + } + } + } + + if (argc != nullptr) { + *argc = info->argc; + } + + if (this_arg != nullptr) { + *this_arg = info->thisArg; + } + + if (data != nullptr) { + *data = info->data; + } + + return napi_ok; +} + +napi_status napi_get_new_target(napi_env env, + napi_callback_info cbinfo, + napi_value* result) { + CHECK_ARG(cbinfo); + CHECK_ARG(result); + + const CallbackInfo* info = reinterpret_cast(cbinfo); + if (info->isConstructCall) { + *result = info->newTarget; + } else { + *result = nullptr; + } + + return napi_ok; +} + +napi_status napi_call_function(napi_env env, + napi_value recv, + napi_value func, + size_t argc, + const napi_value* argv, + napi_value* result) { + JsValueRef object = reinterpret_cast(recv); + JsValueRef function = reinterpret_cast(func); + std::vector args(argc + 1); + args[0] = object; + for (size_t i = 0; i < argc; i++) { + args[i + 1] = reinterpret_cast(argv[i]); + } + JsValueRef returnValue; + CHECK_JSRT(JsCallFunction( + function, + args.data(), + static_cast(argc + 1), + &returnValue)); + if (result != nullptr) { + *result = reinterpret_cast(returnValue); + } + return napi_ok; +} + +napi_status napi_get_global(napi_env env, napi_value* result) { + CHECK_ARG(result); + CHECK_JSRT(JsGetGlobalObject(reinterpret_cast(result))); + return napi_ok; +} + +napi_status napi_throw(napi_env env, napi_value error) { + JsValueRef exception = reinterpret_cast(error); + CHECK_JSRT(JsSetException(exception)); + return napi_ok; +} + +napi_status napi_throw_error(napi_env env, + const char* code, + const char* msg) { + JsValueRef strRef; + JsValueRef exception; + size_t length = strlen(msg); + CHECK_JSRT(JsCreateString(msg, length, &strRef)); + CHECK_JSRT(JsCreateError(strRef, &exception)); + CHECK_NAPI(jsrtimpl::SetErrorCode(exception, nullptr, code)); + CHECK_JSRT(JsSetException(exception)); + return napi_ok; +} + +napi_status napi_throw_type_error(napi_env env, + const char* code, + const char* msg) { + JsValueRef strRef; + JsValueRef exception; + size_t length = strlen(msg); + CHECK_JSRT(JsCreateString(msg, length, &strRef)); + CHECK_JSRT(JsCreateTypeError(strRef, &exception)); + CHECK_NAPI(jsrtimpl::SetErrorCode(exception, nullptr, code)); + CHECK_JSRT(JsSetException(exception)); + return napi_ok; +} + +napi_status napi_throw_range_error(napi_env env, + const char* code, + const char* msg) { + JsValueRef strRef; + JsValueRef exception; + size_t length = strlen(msg); + CHECK_JSRT(JsCreateString(msg, length, &strRef)); + CHECK_JSRT(JsCreateRangeError(strRef, &exception)); + CHECK_NAPI(jsrtimpl::SetErrorCode(exception, nullptr, code)); + CHECK_JSRT(JsSetException(exception)); + return napi_ok; +} + +napi_status napi_is_error(napi_env env, napi_value value, bool* result) { + CHECK_ARG(result); + JsValueType valueType; + CHECK_JSRT(JsGetValueType(value, &valueType)); + *result = (valueType == JsError); + return napi_ok; +} + +napi_status napi_get_value_double(napi_env env, napi_value v, double* result) { + CHECK_ARG(result); + JsValueRef value = reinterpret_cast(v); + CHECK_JSRT_EXPECTED(JsNumberToDouble(value, result), napi_number_expected); + return napi_ok; +} + +napi_status napi_get_value_int32(napi_env env, napi_value v, int32_t* result) { + CHECK_ARG(result); + JsValueRef value = reinterpret_cast(v); + int valueInt; + CHECK_JSRT_EXPECTED(JsNumberToInt(value, &valueInt), napi_number_expected); + *result = static_cast(valueInt); + return napi_ok; +} + +napi_status napi_get_value_uint32(napi_env env, + napi_value v, + uint32_t* result) { + CHECK_ARG(result); + JsValueRef value = reinterpret_cast(v); + int valueInt; + CHECK_JSRT_EXPECTED(JsNumberToInt(value, &valueInt), napi_number_expected); + *result = static_cast(valueInt); + return napi_ok; +} + +napi_status napi_get_value_int64(napi_env env, napi_value v, int64_t* result) { + CHECK_ARG(result); + JsValueRef value = reinterpret_cast(v); + + double valueDouble; + CHECK_JSRT_EXPECTED(JsNumberToDouble(value, &valueDouble), + napi_number_expected); + + if (std::isfinite(valueDouble)) { + *result = static_cast(valueDouble); + } else { + *result = 0; + } + + return napi_ok; +} + +napi_status napi_get_value_bigint_int64(napi_env env, + napi_value value, + int64_t* result, + bool* lossless) { + // TODO(kfarnung): BigInt is not currently implemented in ChakraCore + // https://github.com/Microsoft/ChakraCore/issues/5440 + return napi_ok; +} + +napi_status napi_get_value_bigint_uint64(napi_env env, + napi_value value, + uint64_t* result, + bool* lossless) { + // TODO(kfarnung): BigInt is not currently implemented in ChakraCore + // https://github.com/Microsoft/ChakraCore/issues/5440 + return napi_ok; +} + +napi_status napi_get_value_bigint_words(napi_env env, + napi_value value, + int* sign_bit, + size_t* word_count, + uint64_t* words) { + // TODO(kfarnung): BigInt is not currently implemented in ChakraCore + // https://github.com/Microsoft/ChakraCore/issues/5440 + return napi_ok; +} + +napi_status napi_get_value_bool(napi_env env, napi_value v, bool* result) { + CHECK_ARG(result); + JsValueRef value = reinterpret_cast(v); + CHECK_JSRT_EXPECTED(JsBooleanToBool(value, result), napi_boolean_expected); + return napi_ok; +} + +// Copies a JavaScript string into a LATIN-1 string buffer. The result is the +// number of bytes (excluding the null terminator) copied into buf. +// A sufficient buffer size should be greater than the length of string, +// reserving space for null terminator. +// If bufsize is insufficient, the string will be truncated and null terminated. +// If buf is NULL, this method returns the length of the string (in bytes) +// via the result parameter. +// The result argument is optional unless buf is NULL. +napi_status napi_get_value_string_latin1(napi_env env, + napi_value value, + char* buf, + size_t bufsize, + size_t* result) { + CHECK_ARG(value); + JsValueRef js_value = reinterpret_cast(value); + + // TODO(boingoing): Convert from UTF-8 to Latin1 encoding. + if (!buf) { + CHECK_ARG(result); + + JsErrorCode err = JsCopyString(js_value, nullptr, 0, result); + if (err != JsErrorInvalidArgument) { + return napi_set_last_error(err); + } + } else { + size_t count = 0; + CHECK_JSRT_EXPECTED( + JsCopyString(js_value, nullptr, 0, &count), + napi_string_expected); + + if (bufsize <= count) { + // if bufsize == count there is no space for null terminator + // Slow path: must implement truncation here. + char* fullBuffer = static_cast(malloc(count)); + //CHAKRA_VERIFY(fullBuffer != nullptr); + + CHECK_JSRT_EXPECTED( + JsCopyString(js_value, fullBuffer, count, nullptr), + napi_string_expected); + memmove(buf, fullBuffer, sizeof(char) * bufsize); + free(fullBuffer); + + // Truncate string to the start of the last codepoint + if (bufsize > 0 && + (((buf[bufsize-1] & 0x80) == 0) + || UTF8_MULTIBYTE_START(buf[bufsize-1])) + ) { + // Last byte is a single byte codepoint or + // starts a multibyte codepoint + bufsize -= 1; + } else if (bufsize > 1 && UTF8_MULTIBYTE_START(buf[bufsize-2])) { + // Second last byte starts a multibyte codepoint, + bufsize -= 2; + } else if (bufsize > 2 && UTF8_MULTIBYTE_START(buf[bufsize-3])) { + // Third last byte starts a multibyte codepoint + bufsize -= 3; + } else if (bufsize > 3 && UTF8_MULTIBYTE_START(buf[bufsize-4])) { + // Fourth last byte starts a multibyte codepoint + bufsize -= 4; + } + + buf[bufsize] = '\0'; + + if (result) { + *result = bufsize; + } + + return napi_ok; + } + + // Fastpath, result fits in the buffer + CHECK_JSRT_EXPECTED( + JsCopyString(js_value, buf, bufsize-1, &count), + napi_string_expected); + + buf[count] = 0; + + if (result != nullptr) { + *result = count; + } + } + + return napi_ok; +} + +// Copies a JavaScript string into a UTF-8 string buffer. The result is the +// number of bytes (excluding the null terminator) copied into buf. +// A sufficient buffer size should be greater than the length of string, +// reserving space for null terminator. +// If bufsize is insufficient, the string will be truncated and null terminated. +// If buf is NULL, this method returns the length of the string (in bytes) +// via the result parameter. +// The result argument is optional unless buf is NULL. +napi_status napi_get_value_string_utf8(napi_env env, + napi_value value, + char* buf, + size_t bufsize, + size_t* result) { + CHECK_ARG(value); + JsValueRef js_value = reinterpret_cast(value); + + if (!buf) { + CHECK_ARG(result); + + JsErrorCode err = JsCopyString(js_value, nullptr, 0, result); + if (err != JsErrorInvalidArgument) { + return napi_set_last_error(err); + } + } else { + size_t count = 0; + CHECK_JSRT_EXPECTED( + JsCopyString(js_value, nullptr, 0, &count), + napi_string_expected); + + if (bufsize <= count) { + // if bufsize == count there is no space for null terminator + // Slow path: must implement truncation here. + char* fullBuffer = static_cast(malloc(count)); + //CHAKRA_VERIFY(fullBuffer != nullptr); + + CHECK_JSRT_EXPECTED( + JsCopyString(js_value, fullBuffer, count, nullptr), + napi_string_expected); + memmove(buf, fullBuffer, sizeof(char) * bufsize); + free(fullBuffer); + + // Truncate string to the start of the last codepoint + if (bufsize > 0 && + (((buf[bufsize-1] & 0x80) == 0) + || UTF8_MULTIBYTE_START(buf[bufsize-1])) + ) { + // Last byte is a single byte codepoint or + // starts a multibyte codepoint + bufsize -= 1; + } else if (bufsize > 1 && UTF8_MULTIBYTE_START(buf[bufsize-2])) { + // Second last byte starts a multibyte codepoint, + bufsize -= 2; + } else if (bufsize > 2 && UTF8_MULTIBYTE_START(buf[bufsize-3])) { + // Third last byte starts a multibyte codepoint + bufsize -= 3; + } else if (bufsize > 3 && UTF8_MULTIBYTE_START(buf[bufsize-4])) { + // Fourth last byte starts a multibyte codepoint + bufsize -= 4; + } + + buf[bufsize] = '\0'; + + if (result) { + *result = bufsize; + } + + return napi_ok; + } + + // Fastpath, result fits in the buffer + CHECK_JSRT_EXPECTED( + JsCopyString(js_value, buf, bufsize-1, &count), + napi_string_expected); + + buf[count] = 0; + + if (result != nullptr) { + *result = count; + } + } + + return napi_ok; +} + +// Copies a JavaScript string into a UTF-16 string buffer. The result is the +// number of 2-byte code units (excluding the null terminator) copied into buf. +// A sufficient buffer size should be greater than the length of string, +// reserving space for null terminator. +// If bufsize is insufficient, the string will be truncated and null terminated. +// If buf is NULL, this method returns the length of the string (in 2-byte +// code units) via the result parameter. +// The result argument is optional unless buf is NULL. +napi_status napi_get_value_string_utf16(napi_env env, + napi_value value, + char16_t* buf, + size_t bufsize, + size_t* result) { + CHECK_ARG(value); + JsValueRef js_value = reinterpret_cast(value); + + if (!buf) { + CHECK_ARG(result); + + JsErrorCode err = JsCopyStringUtf16(js_value, nullptr, 0, result); + if (err != JsErrorInvalidArgument) { + return napi_set_last_error(err); + } + } else { + size_t copied = 0; + CHECK_JSRT_EXPECTED( + JsCopyStringUtf16( + js_value, + buf, + bufsize - 1, + &copied), + napi_string_expected); + + if (copied < bufsize - 1) { + buf[copied] = 0; + } else { + buf[bufsize - 1] = 0; + } + + if (result != nullptr) { + *result = copied; + } + } + + return napi_ok; +} + +napi_status napi_coerce_to_number(napi_env env, + napi_value v, + napi_value* result) { + CHECK_ARG(result); + JsValueRef value = reinterpret_cast(v); + CHECK_JSRT( + JsConvertValueToNumber(value, reinterpret_cast(result))); + return napi_ok; +} + +napi_status napi_coerce_to_bool(napi_env env, + napi_value v, + napi_value* result) { + CHECK_ARG(result); + JsValueRef value = reinterpret_cast(v); + CHECK_JSRT( + JsConvertValueToBoolean(value, reinterpret_cast(result))); + return napi_ok; +} + +napi_status napi_coerce_to_object(napi_env env, + napi_value v, + napi_value* result) { + CHECK_ARG(result); + JsValueRef value = reinterpret_cast(v); + CHECK_JSRT( + JsConvertValueToObject(value, reinterpret_cast(result))); + return napi_ok; +} + +napi_status napi_coerce_to_string(napi_env env, + napi_value v, + napi_value* result) { + CHECK_ARG(result); + JsValueRef value = reinterpret_cast(v); + CHECK_JSRT( + JsConvertValueToString(value, reinterpret_cast(result))); + return napi_ok; +} + +napi_status napi_wrap(napi_env env, + napi_value js_object, + void* native_object, + napi_finalize finalize_cb, + void* finalize_hint, + napi_ref* result) { + JsValueRef value = reinterpret_cast(js_object); + + JsValueRef wrapper = JS_INVALID_REFERENCE; + CHECK_NAPI(jsrtimpl::FindWrapper(value, &wrapper)); + RETURN_STATUS_IF_FALSE(wrapper == JS_INVALID_REFERENCE, napi_invalid_arg); + + jsrtimpl::ExternalData* externalData = new jsrtimpl::ExternalData( + env, native_object, finalize_cb, finalize_hint); + if (externalData == nullptr) return napi_set_last_error(napi_generic_failure); + + // Create an external object that will hold the external data pointer. + JsValueRef external = JS_INVALID_REFERENCE; + CHECK_JSRT(JsCreateExternalObject( + externalData, jsrtimpl::ExternalData::Finalize, &external)); + + // Insert the external object into the value's prototype chain. + JsValueRef valuePrototype = JS_INVALID_REFERENCE; + CHECK_JSRT(JsGetPrototype(value, &valuePrototype)); + CHECK_JSRT(JsSetPrototype(external, valuePrototype)); + CHECK_JSRT(JsSetPrototype(value, external)); + + if (result != nullptr) { + CHECK_NAPI(napi_create_reference(env, js_object, 0, result)); + } + + return napi_ok; +} + +napi_status napi_unwrap(napi_env env, napi_value js_object, void** result) { + JsValueRef value = reinterpret_cast(js_object); + + jsrtimpl::ExternalData* externalData = nullptr; + CHECK_NAPI(jsrtimpl::Unwrap(value, &externalData)); + + *result = (externalData != nullptr ? externalData->Data() : nullptr); + + return napi_ok; +} + +napi_status napi_remove_wrap(napi_env env, napi_value js_object, + void** result) { + JsValueRef value = reinterpret_cast(js_object); + + jsrtimpl::ExternalData* externalData = nullptr; + JsValueRef parent = JS_INVALID_REFERENCE; + JsValueRef wrapper = JS_INVALID_REFERENCE; + CHECK_NAPI(jsrtimpl::Unwrap(value, &externalData, &wrapper, &parent)); + RETURN_STATUS_IF_FALSE(parent != JS_INVALID_REFERENCE, napi_invalid_arg); + RETURN_STATUS_IF_FALSE(wrapper != JS_INVALID_REFERENCE, napi_invalid_arg); + + // Remove the external from the prototype chain + JsValueRef wrapperProto = JS_INVALID_REFERENCE; + CHECK_JSRT(JsGetPrototype(wrapper, &wrapperProto)); + CHECK_JSRT(JsSetPrototype(parent, wrapperProto)); + + // Clear the external data from the object + CHECK_JSRT(JsSetExternalData(wrapper, nullptr)); + + if (externalData != nullptr) { + *result = externalData->Data(); + delete externalData; + } else { + *result = nullptr; + } + + return napi_ok; +} + +napi_status napi_create_external(napi_env env, + void* data, + napi_finalize finalize_cb, + void* finalize_hint, + napi_value* result) { + CHECK_ARG(result); + + jsrtimpl::ExternalData* externalData = new jsrtimpl::ExternalData( + env, data, finalize_cb, finalize_hint); + if (externalData == nullptr) return napi_set_last_error(napi_generic_failure); + + CHECK_JSRT(JsCreateExternalObject( + externalData, + jsrtimpl::ExternalData::Finalize, + reinterpret_cast(result))); + + return napi_ok; +} + +napi_status napi_get_value_external(napi_env env, napi_value v, void** result) { + CHECK_ARG(result); + + jsrtimpl::ExternalData* externalData; + CHECK_JSRT(JsGetExternalData( + reinterpret_cast(v), + reinterpret_cast(&externalData))); + + *result = (externalData != nullptr ? externalData->Data() : nullptr); + + return napi_ok; +} + +// $HACK +struct RefInfo +{ + JsValueRef value; + uint32_t count; +}; + +// Set initial_refcount to 0 for a weak reference, >0 for a strong reference. +napi_status napi_create_reference(napi_env env, + napi_value v, + uint32_t initial_refcount, + napi_ref* result) { + CHECK_ARG(result); + + auto value = reinterpret_cast(v); + auto info = new RefInfo + { + reinterpret_cast(v), + initial_refcount + }; + + if (info->count != 0) + { + CHECK_JSRT(JsAddRef(value, nullptr)); + } + + *result = reinterpret_cast(info); + return napi_ok; +} + +// Deletes a reference. The referenced value is released, and may be GC'd +// unless there are other references to it. +napi_status napi_delete_reference(napi_env env, napi_ref ref) { + auto info = reinterpret_cast(ref); + + if (info->count != 0) + { + CHECK_JSRT(JsRelease(info->value, nullptr)); + } + + delete info; + + return napi_ok; +} + +// Increments the reference count, optionally returning the resulting count. +// After this call the reference will be a strong reference because its refcount +// is >0, and the referenced object is effectively "pinned". Calling this when +// the refcount is 0 and the target is unavailable results in an error. +napi_status napi_reference_ref(napi_env env, napi_ref ref, uint32_t* result) { + auto info = reinterpret_cast(ref); + if (info->count++ == 0) + { + CHECK_JSRT(JsAddRef(info->value, nullptr)); + } + if (result != nullptr) + { + *result = info->count; + } + return napi_ok; +} + +// Decrements the reference count, optionally returning the resulting count. +// If the result is 0 the reference is now weak and the object may be GC'd at +// any time if there are no other references. Calling this when the refcount +// is already 0 results in an error. +napi_status napi_reference_unref(napi_env env, napi_ref ref, uint32_t* result) { + auto info = reinterpret_cast(ref); + if (--info->count == 0) + { + CHECK_JSRT(JsRelease(info->value, nullptr)); + } + if (result != nullptr) + { + *result = info->count; + } + return napi_ok; +} + +// Attempts to get a referenced value. If the reference is weak, the value +// might no longer be available, in that case the call is still successful but +// the result is NULL. +napi_status napi_get_reference_value(napi_env env, + napi_ref ref, + napi_value* result) { + CHECK_ARG(result); + auto info = reinterpret_cast(ref); + if (info->count == 0) + { + *result = nullptr; + } + else + { + *result = reinterpret_cast(info->value); + } + return napi_ok; +} + +/*********Stub implementation of handle scope apis' for JSRT***********/ +napi_status napi_open_handle_scope(napi_env env, napi_handle_scope* result) { + CHECK_ARG(result); + *result = nullptr; + return napi_ok; +} + +napi_status napi_close_handle_scope(napi_env env, napi_handle_scope) { + return napi_ok; +} + +napi_status napi_open_escapable_handle_scope(napi_env env, + napi_escapable_handle_scope* result) { + CHECK_ARG(result); + *result = nullptr; + return napi_ok; +} + +napi_status napi_close_escapable_handle_scope(napi_env env, + napi_escapable_handle_scope scope) { + return napi_ok; +} + +// This one will return escapee value as this is called from leveldown db. +napi_status napi_escape_handle(napi_env env, + napi_escapable_handle_scope scope, + napi_value escapee, + napi_value* result) { + CHECK_ARG(result); + *result = escapee; + return napi_ok; +} +/**************************************************************/ + +napi_status napi_new_instance(napi_env env, + napi_value constructor, + size_t argc, + const napi_value* argv, + napi_value* result) { + CHECK_ARG(result); + JsValueRef function = reinterpret_cast(constructor); + std::vector args(argc + 1); + CHECK_JSRT(JsGetUndefinedValue(&args[0])); + for (size_t i = 0; i < argc; i++) { + args[i + 1] = reinterpret_cast(argv[i]); + } + CHECK_JSRT(JsConstructObject( + function, + args.data(), + static_cast(argc + 1), + reinterpret_cast(result))); + return napi_ok; +} + +napi_status napi_make_external(napi_env env, napi_value v, napi_value* result) { + CHECK_ARG(result); + JsValueRef externalObj; + CHECK_JSRT(JsCreateExternalObject(nullptr, nullptr, &externalObj)); + CHECK_JSRT(JsSetPrototype(externalObj, reinterpret_cast(v))); + *result = reinterpret_cast(externalObj); + return napi_ok; +} + +// $HACK +//napi_status napi_async_init(napi_env env, +// napi_value async_resource, +// napi_value async_resource_name, +// napi_async_context* result) { +// CHECK_ENV(env); +// CHECK_ARG(async_resource_name); +// CHECK_ARG(result); +// +// v8::Isolate* isolate = env->isolate; +// +// v8::Local resource; +// if (async_resource != nullptr) { +// resource = +// v8impl::V8LocalValueFromJsValue(async_resource).As(); +// } else { +// resource = v8::Object::New(isolate); +// } +// +// v8::Local resource_name = +// v8impl::V8LocalValueFromJsValue(async_resource_name).As(); +// +// // TODO(jasongin): Consider avoiding allocation here by using +// // a tagged pointer with 2^31 bit fields instead. +// node::async_context* async_context = new node::async_context(); +// +// // TODO(digitalinfinty): EmitAsyncInit might be better served if it +// // tool in napi_values instead of v8 locals? +// *async_context = node::EmitAsyncInit(isolate, resource, resource_name); +// *result = reinterpret_cast(async_context); +// +// napi_clear_last_error(); +// return napi_ok; +//} +// +//napi_status napi_async_destroy(napi_env env, +// napi_async_context async_context) { +// CHECK_ENV(env); +// CHECK_ARG(async_context); +// +// v8::Isolate* isolate = env->isolate; +// node::async_context* node_async_context = +// reinterpret_cast(async_context); +// node::EmitAsyncDestroy(isolate, *node_async_context); +// +// napi_clear_last_error(); +// return napi_ok; +//} +// +//napi_status napi_open_callback_scope(napi_env env, +// napi_value resource_object, +// napi_async_context async_context_handle, +// napi_callback_scope* result) { +// node::async_context* node_async_context = +// reinterpret_cast(async_context_handle); +// +// // TODO(MSLaguana): It'd be nice if we could remove the dependency on v8::* +// // from here by changing node::CallbackScope's signature +// v8::Local resource = +// v8impl::V8LocalValueFromJsValue(resource_object).As(); +// +// *result = reinterpret_cast( +// new node::InternalCallbackScope( +// node::Environment::GetCurrent(env->isolate), +// resource, +// *node_async_context)); +// +// napi_clear_last_error(); +// return napi_ok; +//} +// +//napi_status napi_close_callback_scope(napi_env env, napi_callback_scope scope) { +// delete reinterpret_cast(scope); +// +// napi_clear_last_error(); +// return napi_ok; +//} +// +//napi_status napi_make_callback(napi_env env, +// napi_async_context async_context, +// napi_value recv, +// napi_value func, +// size_t argc, +// const napi_value* argv, +// napi_value* result) { +// v8::Isolate* isolate = env->isolate; +// v8::Local v8recv = +// v8impl::V8LocalValueFromJsValue(recv).As(); +// v8::Local v8func = +// v8impl::V8LocalValueFromJsValue(func).As(); +// v8::Local* v8argv = +// reinterpret_cast*>(const_cast(argv)); +// +// node::async_context* node_async_context = +// reinterpret_cast(async_context); +// if (node_async_context == nullptr) { +// static node::async_context empty_context = { 0, 0 }; +// node_async_context = &empty_context; +// } +// +// // TODO(jasongin): Expose JSRT or N-API version of node::MakeCallback? +// v8::MaybeLocal v8result = +// node::MakeCallback(isolate, v8recv, v8func, argc, v8argv, +// *node_async_context); +// +// bool hasException; +// CHECK_JSRT(JsHasException(&hasException)); +// if (hasException) { +// return napi_set_last_error(napi_pending_exception); +// } +// +// if (v8result.IsEmpty()) { +// return napi_set_last_error(napi_generic_failure); +// } +// +// if (result != nullptr) { +// *result = v8impl::JsValueFromV8LocalValue(v8result.ToLocalChecked()); +// } +// +// return napi_ok; +//} +// +//struct ArrayBufferFinalizeInfo { +// void* data; +// +// void Free() { +// free(data); +// delete this; +// } +//}; +// +//void CALLBACK ExternalArrayBufferFinalizeCallback(void* data) { +// static_cast(data)->Free(); +//} +// +//napi_status napi_create_buffer(napi_env env, +// size_t length, +// void** data, +// napi_value* result) { +// CHECK_ARG(result); +// // TODO(tawoll): Replace v8impl with jsrt-based version. +// +// v8::MaybeLocal maybe = +// node::Buffer::New(env->isolate, length); +// if (maybe.IsEmpty()) { +// return napi_generic_failure; +// } +// +// v8::Local buffer = maybe.ToLocalChecked(); +// if (data != nullptr) { +// *data = node::Buffer::Data(buffer); +// } +// +// *result = v8impl::JsValueFromV8LocalValue(buffer); +// return napi_ok; +//} +// +//napi_status napi_create_external_buffer(napi_env env, +// size_t length, +// void* data, +// napi_finalize finalize_cb, +// void* finalize_hint, +// napi_value* result) { +// CHECK_ARG(result); +// // TODO(tawoll): Replace v8impl with jsrt-based version. +// +// jsrtimpl::ExternalData* externalData = new jsrtimpl::ExternalData( +// env, data, finalize_cb, finalize_hint); +// v8::MaybeLocal maybe = node::Buffer::New( +// env->isolate, +// static_cast(data), +// length, +// jsrtimpl::ExternalData::FinalizeBuffer, +// externalData); +// +// if (maybe.IsEmpty()) { +// return napi_generic_failure; +// } +// +// *result = v8impl::JsValueFromV8LocalValue(maybe.ToLocalChecked()); +// return napi_ok; +//} +// +//napi_status napi_create_buffer_copy(napi_env env, +// size_t length, +// const void* data, +// void** result_data, +// napi_value* result) { +// CHECK_ARG(result); +// // TODO(tawoll): Implement node::Buffer in terms of napi to avoid using +// // chakra shim here. +// +// v8::MaybeLocal maybe = node::Buffer::Copy( +// env->isolate, static_cast(data), length); +// if (maybe.IsEmpty()) { +// return napi_generic_failure; +// } +// +// v8::Local buffer = maybe.ToLocalChecked(); +// *result = v8impl::JsValueFromV8LocalValue(buffer); +// +// if (result_data != nullptr) { +// *result_data = node::Buffer::Data(buffer); +// } +// +// return napi_ok; +//} + +napi_status napi_is_buffer(napi_env env, napi_value v, bool* result) { + CHECK_ARG(result); + JsValueRef typedArray = reinterpret_cast(v); + JsValueType objectType; + CHECK_JSRT(JsGetValueType(typedArray, &objectType)); + if (objectType != JsTypedArray) { + *result = false; + return napi_ok; + } + JsTypedArrayType arrayType; + CHECK_JSRT( + JsGetTypedArrayInfo(typedArray, &arrayType, nullptr, nullptr, nullptr)); + *result = (arrayType == JsArrayTypeUint8); + return napi_ok; +} + +napi_status napi_get_buffer_info(napi_env env, + napi_value value, + void** data, + size_t* length) { + JsValueRef typedArray = reinterpret_cast(value); + JsValueRef arrayBuffer; + unsigned int byteOffset; + ChakraBytePtr buffer; + unsigned int bufferLength; + CHECK_JSRT(JsGetTypedArrayInfo( + typedArray, nullptr, &arrayBuffer, &byteOffset, nullptr)); + CHECK_JSRT(JsGetArrayBufferStorage(arrayBuffer, &buffer, &bufferLength)); + + if (data != nullptr) { + *data = static_cast(buffer + byteOffset); + } + + if (length != nullptr) { + *length = static_cast(bufferLength); + } + + return napi_ok; +} + +napi_status napi_is_exception_pending(napi_env env, bool* result) { + CHECK_ARG(result); + CHECK_JSRT(JsHasException(result)); + return napi_ok; +} + +napi_status napi_get_and_clear_last_exception(napi_env env, + napi_value* result) { + CHECK_ARG(result); + CHECK_JSRT(JsGetAndClearException(reinterpret_cast(result))); + if (*result == nullptr) { + // Is this necessary? + CHECK_NAPI(napi_get_undefined(env, result)); + } + return napi_ok; +} + +napi_status napi_is_arraybuffer(napi_env env, napi_value value, bool* result) { + CHECK_ARG(result); + + JsValueRef jsValue = reinterpret_cast(value); + JsValueType valueType; + CHECK_JSRT(JsGetValueType(jsValue, &valueType)); + + *result = (valueType == JsArrayBuffer); + return napi_ok; +} + +napi_status napi_create_arraybuffer(napi_env env, + size_t byte_length, + void** data, + napi_value* result) { + CHECK_ARG(result); + + JsValueRef arrayBuffer; + CHECK_JSRT( + JsCreateArrayBuffer(static_cast(byte_length), &arrayBuffer)); + + if (data != nullptr) { + CHECK_JSRT(JsGetArrayBufferStorage( + arrayBuffer, + reinterpret_cast(data), + reinterpret_cast(&byte_length))); + } + + *result = reinterpret_cast(arrayBuffer); + return napi_ok; +} + +napi_status napi_create_external_arraybuffer(napi_env env, + void* external_data, + size_t byte_length, + napi_finalize finalize_cb, + void* finalize_hint, + napi_value* result) { + CHECK_ARG(result); + + jsrtimpl::ExternalData* externalData = new jsrtimpl::ExternalData( + env, external_data, finalize_cb, finalize_hint); + if (externalData == nullptr) return napi_set_last_error(napi_generic_failure); + + JsValueRef arrayBuffer; + CHECK_JSRT(JsCreateExternalArrayBuffer( + external_data, + static_cast(byte_length), + jsrtimpl::ExternalData::Finalize, + externalData, + &arrayBuffer)); + + *result = reinterpret_cast(arrayBuffer); + return napi_ok; +} + +napi_status napi_get_arraybuffer_info(napi_env env, + napi_value arraybuffer, + void** data, + size_t* byte_length) { + ChakraBytePtr storageData; + unsigned int storageLength; + CHECK_JSRT(JsGetArrayBufferStorage( + reinterpret_cast(arraybuffer), + &storageData, + &storageLength)); + + if (data != nullptr) { + *data = reinterpret_cast(storageData); + } + + if (byte_length != nullptr) { + *byte_length = static_cast(storageLength); + } + + return napi_ok; +} + +napi_status napi_is_typedarray(napi_env env, napi_value value, bool* result) { + CHECK_ARG(result); + + JsValueRef jsValue = reinterpret_cast(value); + JsValueType valueType; + CHECK_JSRT(JsGetValueType(jsValue, &valueType)); + + *result = (valueType == JsTypedArray); + return napi_ok; +} + +napi_status napi_create_typedarray(napi_env env, + napi_typedarray_type type, + size_t length, + napi_value arraybuffer, + size_t byte_offset, + napi_value* result) { + CHECK_ARG(result); + + JsTypedArrayType jsType; + switch (type) { + case napi_int8_array: + jsType = JsArrayTypeInt8; + break; + case napi_uint8_array: + jsType = JsArrayTypeUint8; + break; + case napi_uint8_clamped_array: + jsType = JsArrayTypeUint8Clamped; + break; + case napi_int16_array: + jsType = JsArrayTypeInt16; + break; + case napi_uint16_array: + jsType = JsArrayTypeUint16; + break; + case napi_int32_array: + jsType = JsArrayTypeInt32; + break; + case napi_uint32_array: + jsType = JsArrayTypeUint32; + break; + case napi_float32_array: + jsType = JsArrayTypeFloat32; + break; + case napi_float64_array: + jsType = JsArrayTypeFloat64; + break; + default: + return napi_set_last_error(napi_invalid_arg); + } + + JsValueRef jsArrayBuffer = reinterpret_cast(arraybuffer); + + CHECK_JSRT(JsCreateTypedArray( + jsType, + jsArrayBuffer, + static_cast(byte_offset), + static_cast(length), + reinterpret_cast(result))); + + return napi_ok; +} + +napi_status napi_get_typedarray_info(napi_env env, + napi_value typedarray, + napi_typedarray_type* type, + size_t* length, + void** data, + napi_value* arraybuffer, + size_t* byte_offset) { + JsTypedArrayType jsType; + JsValueRef jsArrayBuffer; + unsigned int byteOffset; + unsigned int byteLength; + ChakraBytePtr bufferData; + unsigned int bufferLength; + int elementSize; + + CHECK_JSRT(JsGetTypedArrayInfo( + reinterpret_cast(typedarray), + &jsType, + &jsArrayBuffer, + &byteOffset, + &byteLength)); + + CHECK_JSRT(JsGetTypedArrayStorage( + reinterpret_cast(typedarray), + &bufferData, + &bufferLength, + &jsType, + &elementSize)); + + if (type != nullptr) { + switch (jsType) { + case JsArrayTypeInt8: + *type = napi_int8_array; + break; + case JsArrayTypeUint8: + *type = napi_uint8_array; + break; + case JsArrayTypeUint8Clamped: + *type = napi_uint8_clamped_array; + break; + case JsArrayTypeInt16: + *type = napi_int16_array; + break; + case JsArrayTypeUint16: + *type = napi_uint16_array; + break; + case JsArrayTypeInt32: + *type = napi_int32_array; + break; + case JsArrayTypeUint32: + *type = napi_uint32_array; + break; + case JsArrayTypeFloat32: + *type = napi_float32_array; + break; + case JsArrayTypeFloat64: + *type = napi_float64_array; + break; + default: + return napi_set_last_error(napi_generic_failure); + } + } + + if (length != nullptr) { + *length = static_cast(byteLength / elementSize); + } + + if (data != nullptr) { + *data = static_cast(bufferData); + } + + if (arraybuffer != nullptr) { + *arraybuffer = reinterpret_cast(jsArrayBuffer); + } + + if (byte_offset != nullptr) { + *byte_offset = static_cast(byteOffset); + } + + return napi_ok; +} + +napi_status napi_create_dataview(napi_env env, + size_t byte_length, + napi_value arraybuffer, + size_t byte_offset, + napi_value* result) { + CHECK_ARG(result); + + JsValueRef jsArrayBuffer = reinterpret_cast(arraybuffer); + + BYTE* unused = nullptr; + unsigned int bufferLength = 0; + + CHECK_JSRT(JsGetArrayBufferStorage( + jsArrayBuffer, + &unused, + &bufferLength)); + + if (byte_length + byte_offset > bufferLength) { + napi_throw_range_error( + env, + "ERR_NAPI_INVALID_DATAVIEW_ARGS", + "byte_offset + byte_length should be less than or " + "equal to the size in bytes of the array passed in"); + return napi_set_last_error(napi_pending_exception); + } + + CHECK_JSRT(JsCreateDataView( + jsArrayBuffer, + static_cast(byte_offset), + static_cast(byte_length), + reinterpret_cast(result))); + + return napi_ok; +} + +napi_status napi_is_dataview(napi_env env, napi_value value, bool* result) { + CHECK_ARG(result); + + JsValueRef jsValue = reinterpret_cast(value); + JsValueType valueType; + CHECK_JSRT(JsGetValueType(jsValue, &valueType)); + + *result = (valueType == JsDataView); + return napi_ok; +} + +napi_status napi_get_dataview_info(napi_env env, + napi_value dataview, + size_t* byte_length, + void** data, + napi_value* arraybuffer, + size_t* byte_offset) { + //JsValueRef jsArrayBuffer = JS_INVALID_REFERENCE; + //unsigned int byteOffset = 0; + //unsigned int byteLength = 0; + //ChakraBytePtr bufferData = nullptr; + //unsigned int bufferLength = 0; + + //JsValueRef jsDataView = reinterpret_cast(dataview); + + //CHECK_JSRT(JsGetDataViewInfo( + // jsDataView, + // &jsArrayBuffer, + // &byteOffset, + // &byteLength)); + + //CHECK_JSRT(JsGetDataViewStorage( + // jsDataView, + // &bufferData, + // &bufferLength)); + + //if (byte_length != nullptr) { + // *byte_length = static_cast(byteLength); + //} + + //if (data != nullptr) { + // *data = static_cast(bufferData); + //} + + //if (arraybuffer != nullptr) { + // *arraybuffer = reinterpret_cast(jsArrayBuffer); + //} + + //if (byte_offset != nullptr) { + // *byte_offset = static_cast(byteOffset); + //} + + //return napi_ok; + throw new std::runtime_error("not implemented"); +} + +//napi_status napi_get_version(napi_env env, uint32_t* result) { +// CHECK_ARG(result); +// *result = NAPI_VERSION; +// return napi_ok; +//} +// +//napi_status napi_get_node_version(napi_env env, +// const napi_node_version** result) { +// CHECK_ARG(result); +// static const napi_node_version version = { +// NODE_MAJOR_VERSION, +// NODE_MINOR_VERSION, +// NODE_PATCH_VERSION, +// NODE_RELEASE +// }; +// *result = &version; +// return napi_ok; +//} + +napi_status napi_adjust_external_memory(napi_env env, + int64_t change_in_bytes, + int64_t* adjusted_value) { + CHECK_ARG(change_in_bytes); + CHECK_ARG(adjusted_value); + + // TODO(jackhorton): Determine if Chakra needs or is able to do anything here + // For now, we can lie and say that we always adjusted more memory + *adjusted_value = change_in_bytes; + + return napi_ok; +} + +//JsValueRef runScriptSourceUrl = JS_INVALID_REFERENCE; + +napi_status napi_run_script(napi_env env, + napi_value script, + const char* sourceUrl, + napi_value* result) { + CHECK_ARG(script); + CHECK_ARG(result); + JsValueRef scriptVar = reinterpret_cast(script); + + //if (runScriptSourceUrl == JS_INVALID_REFERENCE) { + // CHECK_JSRT(JsCreateString(STR_AND_LENGTH("NAPI run script"), + // &runScriptSourceUrl)); + //} + + //CHECK_JSRT_EXPECTED(JsRun(scriptVar, + // JS_SOURCE_CONTEXT_NONE, + // runScriptSourceUrl, + // JsParseScriptAttributeNone, + // reinterpret_cast(result)), + // napi_string_expected); + + static JsSourceContext context = JS_SOURCE_CONTEXT_NONE; + + const wchar_t* scriptStr; + size_t scriptStrLen; + CHECK_JSRT(JsStringToPointer(scriptVar, &scriptStr, &scriptStrLen)); + CHECK_JSRT_EXPECTED(JsRunScript(scriptStr, ++context, NarrowToWide(sourceUrl).data(), reinterpret_cast(result)), napi_string_expected); + + return napi_ok; +} + +// $HACK +//namespace uvimpl { +// +//napi_status ConvertUVErrorCode(int code) { +// switch (code) { +// case 0: +// return napi_ok; +// case UV_EINVAL: +// return napi_invalid_arg; +// case UV_ECANCELED: +// return napi_cancelled; +// } +// +// return napi_generic_failure; +//} +// +//// Wrapper around uv_work_t which calls user-provided callbacks. +//class Work: public node::AsyncResource { +// private: +// explicit Work(napi_env env, +// v8::Local async_resource, +// v8::Local async_resource_name, +// napi_async_execute_callback execute = nullptr, +// napi_async_complete_callback complete = nullptr, +// void* data = nullptr) +// : AsyncResource(env->isolate, async_resource, async_resource_name), +// _env(env), +// _data(data), +// _execute(execute), +// _complete(complete) { +// memset(&_request, 0, sizeof(_request)); +// _request.data = this; +// } +// +// ~Work() { } +// +// public: +// static Work* New(napi_env env, +// napi_value async_resource, +// napi_value async_resource_name, +// napi_async_execute_callback execute, +// napi_async_complete_callback complete, +// void* data) { +// v8::Local async_resource_local = +// v8impl::V8LocalValueFromJsValue(async_resource).As(); +// v8::Local async_resource_name_local = +// v8impl::V8LocalValueFromJsValue(async_resource_name).As(); +// +// return new Work(env, async_resource_local, async_resource_name_local, +// execute, complete, data); +// } +// +// static void Delete(Work* work) { +// delete work; +// } +// +// static void ExecuteCallback(uv_work_t* req) { +// Work* work = static_cast(req->data); +// work->_execute(work->_env, work->_data); +// } +// +// static void Fatal() { +// const char* message = "[napi] CompleteCallback failed " +// "but exception could not be propagated"; +// napi_fatal_error(nullptr, -1, message, strlen(message)); +// } +// +// static void CompleteCallback(uv_work_t* req, int status) { +// Work* work = static_cast(req->data); +// +// if (work->_complete != nullptr) { +// CallbackScope callback_scope(work); +// +// work->_complete(work->_env, ConvertUVErrorCode(status), work->_data); +// +// bool hasException; +// JsErrorCode errorCode = JsHasException(&hasException); +// if (errorCode != JsNoError || !hasException) { +// return; +// } +// +// JsValueRef metadata; +// if (JsGetAndClearExceptionWithMetadata(&metadata) != JsNoError) { +// Fatal(); +// return; +// } +// +// JsValueRef exception; +// JsPropertyIdRef exProp; +// +// if (JsCreatePropertyId(STR_AND_LENGTH("exception"), +// &exProp) != JsNoError) { +// Fatal(); +// return; +// } +// +// if (JsGetProperty(metadata, exProp, &exception) != JsNoError) { +// Fatal(); +// return; +// } +// +// // TODO(digitalinfinity): +// // Taking a dependency on v8::Local::New for expediency here +// // Remove this once node::FatalException is clean +// v8::Local message = +// v8::Local::New(metadata); +// v8::Local exceptionObject = +// v8impl::V8LocalValueFromJsValue( +// reinterpret_cast(exception)).As(); +// +// node::FatalException(work->_env->isolate, exceptionObject, message); +// } +// } +// +// uv_work_t* Request() { +// return &_request; +// } +// +// private: +// napi_env _env; +// void* _data; +// uv_work_t _request; +// napi_async_execute_callback _execute; +// napi_async_complete_callback _complete; +//}; +// +//} // end of namespace uvimpl +// +//#define CALL_UV(condition) \ +// do { \ +// int result = (condition); \ +// napi_status status = uvimpl::ConvertUVErrorCode(result); \ +// if (status != napi_ok) { \ +// return napi_set_last_error(status, result); \ +// } \ +// } while (0) +// +//napi_status napi_create_async_work(napi_env env, +// napi_value async_resource, +// napi_value async_resource_name, +// napi_async_execute_callback execute, +// napi_async_complete_callback complete, +// void* data, +// napi_async_work* result) { +// CHECK_ARG(execute); +// CHECK_ARG(result); +// +// napi_value resource; +// if (async_resource != nullptr) { +// CHECK_NAPI(napi_coerce_to_object(env, async_resource, &resource)); +// } else { +// CHECK_NAPI(napi_create_object(env, &resource)); +// } +// +// napi_value resource_name; +// CHECK_NAPI(napi_coerce_to_string(env, async_resource_name, &resource_name)); +// +// uvimpl::Work* work = +// uvimpl::Work::New(env, resource, resource_name, execute, complete, data); +// +// *result = reinterpret_cast(work); +// +// return napi_ok; +//} +// +//napi_status napi_delete_async_work(napi_env env, napi_async_work work) { +// CHECK_ARG(work); +// +// uvimpl::Work::Delete(reinterpret_cast(work)); +// +// return napi_ok; +//} +// +//napi_status napi_queue_async_work(napi_env env, napi_async_work work) { +// CHECK_ARG(work); +// +// // Consider: Encapsulate the uv_loop_t into an opaque pointer parameter. +// // Currently the environment event loop is the same as the UV default loop. +// // Someday (if node ever supports multiple isolates), it may be better to get +// // the loop from node::Environment::GetCurrent(env->isolate)->event_loop(); +// uv_loop_t* event_loop = uv_default_loop(); +// +// uvimpl::Work* w = reinterpret_cast(work); +// +// CALL_UV(uv_queue_work(event_loop, +// w->Request(), +// uvimpl::Work::ExecuteCallback, +// uvimpl::Work::CompleteCallback)); +// +// return napi_ok; +//} +// +//napi_status napi_cancel_async_work(napi_env env, napi_async_work work) { +// CHECK_ARG(work); +// +// uvimpl::Work* w = reinterpret_cast(work); +// +// CALL_UV(uv_cancel(reinterpret_cast(w->Request()))); +// +// return napi_ok; +//} + +NAPI_EXTERN napi_status napi_create_promise(napi_env env, + napi_deferred* deferred, + napi_value* promise) { + //CHECK_ARG(deferred); + //CHECK_ARG(promise); + + //JsValueRef js_promise, resolve, reject, container; + //napi_ref ref; + //napi_value js_deferred; + + //CHECK_JSRT(JsCreatePromise(&js_promise, &resolve, &reject)); + + //CHECK_JSRT(JsCreateObject(&container)); + //js_deferred = reinterpret_cast(container); + + //CHECK_NAPI(napi_set_named_property(env, js_deferred, "resolve", + // reinterpret_cast(resolve))); + //CHECK_NAPI(napi_set_named_property(env, js_deferred, "reject", + // reinterpret_cast(reject))); + + //CHECK_NAPI(napi_create_reference(env, js_deferred, 1, &ref)); + + //*deferred = reinterpret_cast(ref); + //*promise = reinterpret_cast(js_promise); + + //return napi_ok; + throw new std::runtime_error("not implemented"); +} + +NAPI_EXTERN napi_status napi_resolve_deferred(napi_env env, + napi_deferred deferred, + napi_value resolution) { + return jsrtimpl::ConcludeDeferred(env, deferred, "resolve", resolution); +} + +NAPI_EXTERN napi_status napi_reject_deferred(napi_env env, + napi_deferred deferred, + napi_value rejection) { + return jsrtimpl::ConcludeDeferred(env, deferred, "reject", rejection); +} + +NAPI_EXTERN napi_status napi_is_promise(napi_env env, + napi_value promise, + bool* is_promise) { + CHECK_ARG(promise); + CHECK_ARG(is_promise); + + napi_value global, promise_ctor; + + CHECK_NAPI(napi_get_global(env, &global)); + CHECK_NAPI(napi_get_named_property(env, global, "Promise", &promise_ctor)); + CHECK_NAPI(napi_instanceof(env, promise, promise_ctor, is_promise)); + + return napi_ok; +} + +// $HACK +//NAPI_EXTERN napi_status napi_get_uv_event_loop(napi_env env, uv_loop_t** loop) { +// CHECK_ENV(env); +// CHECK_ARG(loop); +// *loop = env->loop; +// +// napi_clear_last_error(); +// return napi_ok; +//} +// +//class TsFn: public node::AsyncResource { +// public: +// TsFn(v8::Local func, +// v8::Local resource, +// v8::Local name, +// size_t thread_count_, +// void* context_, +// size_t max_queue_size_, +// napi_env env_, +// void* finalize_data_, +// napi_finalize finalize_cb_, +// napi_threadsafe_function_call_js call_js_cb_): +// AsyncResource(env_->isolate, +// resource, +// *v8::String::Utf8Value(env_->isolate, name)), +// thread_count(thread_count_), +// is_closing(false), +// context(context_), +// max_queue_size(max_queue_size_), +// env(env_), +// finalize_data(finalize_data_), +// finalize_cb(finalize_cb_), +// idle_running(false), +// call_js_cb(call_js_cb_ == nullptr ? CallJs : call_js_cb_), +// handles_closing(false) { +// ref.Reset(env->isolate, func); +// node::AddEnvironmentCleanupHook(env->isolate, Cleanup, this); +// } +// +// ~TsFn() { +// node::RemoveEnvironmentCleanupHook(env->isolate, Cleanup, this); +// } +// +// // These methods can be called from any thread. +// +// napi_status Push(void* data, napi_threadsafe_function_call_mode mode) { +// node::Mutex::ScopedLock lock(this->mutex); +// +// while (queue.size() >= max_queue_size && +// max_queue_size > 0 && +// !is_closing) { +// if (mode == napi_tsfn_nonblocking) { +// return napi_queue_full; +// } +// cond->Wait(lock); +// } +// +// if (is_closing) { +// if (thread_count == 0) { +// return napi_invalid_arg; +// } else { +// thread_count--; +// return napi_closing; +// } +// } else { +// if (uv_async_send(&async) != 0) { +// return napi_generic_failure; +// } +// queue.push(data); +// return napi_ok; +// } +// } +// +// napi_status Acquire() { +// node::Mutex::ScopedLock lock(this->mutex); +// +// if (is_closing) { +// return napi_closing; +// } +// +// thread_count++; +// +// return napi_ok; +// } +// +// napi_status Release(napi_threadsafe_function_release_mode mode) { +// node::Mutex::ScopedLock lock(this->mutex); +// +// if (thread_count == 0) { +// return napi_invalid_arg; +// } +// +// thread_count--; +// +// if (thread_count == 0 || mode == napi_tsfn_abort) { +// if (!is_closing) { +// is_closing = (mode == napi_tsfn_abort); +// if (is_closing && max_queue_size > 0) { +// cond->Signal(lock); +// } +// if (uv_async_send(&async) != 0) { +// return napi_generic_failure; +// } +// } +// } +// +// return napi_ok; +// } +// +// void EmptyQueueAndDelete() { +// for (; !queue.empty() ; queue.pop()) { +// call_js_cb(nullptr, nullptr, context, queue.front()); +// } +// delete this; +// } +// +// // These methods must only be called from the loop thread. +// +// napi_status Init() { +// TsFn* ts_fn = this; +// +// if (uv_async_init(env->loop, &async, AsyncCb) == 0) { +// if (max_queue_size > 0) { +// cond.reset(new node::ConditionVariable); +// } +// if ((max_queue_size == 0 || cond.get() != nullptr) && +// uv_idle_init(env->loop, &idle) == 0) { +// return napi_ok; +// } +// +// node::Environment::GetCurrent(env->isolate)->CloseHandle( +// reinterpret_cast(&async), +// [] (uv_handle_t* handle) -> void { +// TsFn* ts_fn = +// node::ContainerOf(&TsFn::async, +// reinterpret_cast(handle)); +// delete ts_fn; +// }); +// +// // Prevent the thread-safe function from being deleted here, because +// // the callback above will delete it. +// ts_fn = nullptr; +// } +// +// delete ts_fn; +// +// return napi_generic_failure; +// } +// +// napi_status Unref() { +// uv_unref(reinterpret_cast(&async)); +// uv_unref(reinterpret_cast(&idle)); +// +// return napi_ok; +// } +// +// napi_status Ref() { +// uv_ref(reinterpret_cast(&async)); +// uv_ref(reinterpret_cast(&idle)); +// +// return napi_ok; +// } +// +// void DispatchOne() { +// void* data; +// bool popped_value = false; +// bool idle_stop_failed = false; +// +// { +// node::Mutex::ScopedLock lock(this->mutex); +// if (is_closing) { +// CloseHandlesAndMaybeDelete(); +// } else { +// size_t size = queue.size(); +// if (size > 0) { +// data = queue.front(); +// queue.pop(); +// popped_value = true; +// if (size == max_queue_size && max_queue_size > 0) { +// cond->Signal(lock); +// } +// size--; +// } +// +// if (size == 0) { +// if (thread_count == 0) { +// is_closing = true; +// if (max_queue_size > 0) { +// cond->Signal(lock); +// } +// CloseHandlesAndMaybeDelete(); +// } else { +// if (uv_idle_stop(&idle) != 0) { +// idle_stop_failed = true; +// } else { +// idle_running = false; +// } +// } +// } +// } +// } +// +// if (popped_value || idle_stop_failed) { +// v8::HandleScope scope(env->isolate); +// CallbackScope cb_scope(this); +// +// if (idle_stop_failed) { +// CHECK(napi_throw_error(env, +// "ERR_NAPI_TSFN_STOP_IDLE_LOOP", +// "Failed to stop the idle loop") == napi_ok); +// } else { +// v8::Local js_cb = +// v8::Local::New(env->isolate, ref); +// call_js_cb(env, +// v8impl::JsValueFromV8LocalValue(js_cb), +// context, +// data); +// } +// } +// } +// +// node::Environment* NodeEnv() { +// // For some reason grabbing the Node.js environment requires a handle scope. +// v8::HandleScope scope(env->isolate); +// return node::Environment::GetCurrent(env->isolate); +// } +// +// void MaybeStartIdle() { +// if (!idle_running) { +// if (uv_idle_start(&idle, IdleCb) != 0) { +// v8::HandleScope scope(env->isolate); +// CallbackScope cb_scope(this); +// CHECK(napi_throw_error(env, +// "ERR_NAPI_TSFN_START_IDLE_LOOP", +// "Failed to start the idle loop") == napi_ok); +// } +// } +// } +// +// void Finalize() { +// v8::HandleScope scope(env->isolate); +// if (finalize_cb) { +// CallbackScope cb_scope(this); +// finalize_cb(env, finalize_data, context); +// } +// EmptyQueueAndDelete(); +// } +// +// inline void* Context() { +// return context; +// } +// +// void CloseHandlesAndMaybeDelete(bool set_closing = false) { +// if (set_closing) { +// node::Mutex::ScopedLock lock(this->mutex); +// is_closing = true; +// if (max_queue_size > 0) { +// cond->Signal(lock); +// } +// } +// if (handles_closing) { +// return; +// } +// handles_closing = true; +// NodeEnv()->CloseHandle( +// reinterpret_cast(&async), +// [] (uv_handle_t* handle) -> void { +// TsFn* ts_fn = node::ContainerOf(&TsFn::async, +// reinterpret_cast(handle)); +// ts_fn->NodeEnv()->CloseHandle( +// reinterpret_cast(&ts_fn->idle), +// [] (uv_handle_t* handle) -> void { +// TsFn* ts_fn = node::ContainerOf(&TsFn::idle, +// reinterpret_cast(handle)); +// ts_fn->Finalize(); +// }); +// }); +// } +// +// // Default way of calling into JavaScript. Used when TsFn is constructed +// // without a call_js_cb_. +// static void CallJs(napi_env env, napi_value cb, void* context, void* data) { +// if (!(env == nullptr || cb == nullptr)) { +// napi_value recv; +// napi_status status; +// +// status = napi_get_undefined(env, &recv); +// if (status != napi_ok) { +// napi_throw_error(env, "ERR_NAPI_TSFN_GET_UNDEFINED", +// "Failed to retrieve undefined value"); +// return; +// } +// +// status = napi_call_function(env, recv, cb, 0, nullptr, nullptr); +// if (status != napi_ok && status != napi_pending_exception) { +// napi_throw_error(env, "ERR_NAPI_TSFN_CALL_JS", +// "Failed to call JS callback"); +// return; +// } +// } +// } +// +// static void IdleCb(uv_idle_t* idle) { +// TsFn* ts_fn = +// node::ContainerOf(&TsFn::idle, idle); +// ts_fn->DispatchOne(); +// } +// +// static void AsyncCb(uv_async_t* async) { +// TsFn* ts_fn = +// node::ContainerOf(&TsFn::async, async); +// ts_fn->MaybeStartIdle(); +// } +// +// static void Cleanup(void* data) { +// reinterpret_cast(data)->CloseHandlesAndMaybeDelete(true); +// } +// +// private: +// // These are variables protected by the mutex. +// node::Mutex mutex; +// std::unique_ptr cond; +// std::queue queue; +// uv_async_t async; +// uv_idle_t idle; +// size_t thread_count; +// bool is_closing; +// +// // These are variables set once, upon creation, and then never again, which +// // means we don't need the mutex to read them. +// void* context; +// size_t max_queue_size; +// +// // These are variables accessed only from the loop thread. +// node::Persistent ref; +// napi_env env; +// void* finalize_data; +// napi_finalize finalize_cb; +// bool idle_running; +// napi_async_context async_context; +// napi_threadsafe_function_call_js call_js_cb; +// bool handles_closing; +//}; +// +//NAPI_EXTERN napi_status +//napi_create_threadsafe_function(napi_env env, +// napi_value func, +// napi_value async_resource, +// napi_value async_resource_name, +// size_t max_queue_size, +// size_t initial_thread_count, +// void* thread_finalize_data, +// napi_finalize thread_finalize_cb, +// void* context, +// napi_threadsafe_function_call_js call_js_cb, +// napi_threadsafe_function* result) { +// CHECK_ENV(env); +// CHECK_ARG(func); +// CHECK_ARG(async_resource_name); +// RETURN_STATUS_IF_FALSE(initial_thread_count > 0, napi_invalid_arg); +// CHECK_ARG(result); +// +// napi_status status = napi_ok; +// +// v8::Local func_local = +// v8impl::V8LocalValueFromJsValue(func).As(); +// +// v8::Local v8_context = env->isolate->GetCurrentContext(); +// +// v8::Local async_resource_local; +// if (async_resource == nullptr) { +// async_resource_local = v8::Object::New(env->isolate); +// } else { +// async_resource_local = +// v8impl::V8LocalValueFromJsValue(async_resource).As(); +// } +// +// v8::Local async_resource_name_local = +// v8impl::V8LocalValueFromJsValue(async_resource_name).As(); +// +// TsFn* ts_fn = new TsFn(func_local, +// async_resource_local, +// async_resource_name_local, +// initial_thread_count, +// context, +// max_queue_size, +// env, +// thread_finalize_data, +// thread_finalize_cb, +// call_js_cb); +// +// if (ts_fn == nullptr) { +// status = napi_generic_failure; +// } else { +// // Init deletes ts_fn upon failure. +// status = ts_fn->Init(); +// if (status == napi_ok) { +// *result = reinterpret_cast(ts_fn); +// } +// } +// +// return napi_set_last_error(status); +//} +// +//NAPI_EXTERN napi_status +//napi_get_threadsafe_function_context(napi_threadsafe_function func, +// void** result) { +// CHECK(func != nullptr); +// CHECK(result != nullptr); +// +// *result = reinterpret_cast(func)->Context(); +// return napi_ok; +//} +// +//NAPI_EXTERN napi_status +//napi_call_threadsafe_function(napi_threadsafe_function func, +// void* data, +// napi_threadsafe_function_call_mode is_blocking) { +// CHECK(func != nullptr); +// return reinterpret_cast(func)->Push(data, is_blocking); +//} +// +//NAPI_EXTERN napi_status +//napi_acquire_threadsafe_function(napi_threadsafe_function func) { +// CHECK(func != nullptr); +// return reinterpret_cast(func)->Acquire(); +//} +// +//NAPI_EXTERN napi_status +//napi_release_threadsafe_function(napi_threadsafe_function func, +// napi_threadsafe_function_release_mode mode) { +// CHECK(func != nullptr); +// return reinterpret_cast(func)->Release(mode); +//} +// +//NAPI_EXTERN napi_status +//napi_unref_threadsafe_function(napi_env env, napi_threadsafe_function func) { +// CHECK(func != nullptr); +// return reinterpret_cast(func)->Unref(); +//} +// +//NAPI_EXTERN napi_status +//napi_ref_threadsafe_function(napi_env env, napi_threadsafe_function func) { +// CHECK(func != nullptr); +// return reinterpret_cast(func)->Ref(); +//} + +napi_status napi_add_finalizer(napi_env env, + napi_value js_object, + void* native_object, + napi_finalize finalize_cb, + void* finalize_hint, + napi_ref* result) { + return napi_ok; +} diff --git a/Source/Napi/js_native_api_chakra.h b/Source/Napi/js_native_api_chakra.h new file mode 100644 index 000000000..eed1596f8 --- /dev/null +++ b/Source/Napi/js_native_api_chakra.h @@ -0,0 +1,4 @@ +#pragma once + +struct napi_env__ { +}; diff --git a/Source/Napi/js_native_api_types.h b/Source/Napi/js_native_api_types.h new file mode 100644 index 000000000..a47399579 --- /dev/null +++ b/Source/Napi/js_native_api_types.h @@ -0,0 +1,108 @@ +#ifndef SRC_JS_NATIVE_API_TYPES_H_ +#define SRC_JS_NATIVE_API_TYPES_H_ + +#include +#include + +#if !defined __cplusplus || (defined(_MSC_VER) && _MSC_VER < 1900) + typedef uint16_t char16_t; +#endif + +// JSVM API types are all opaque pointers for ABI stability +// typedef undefined structs instead of void* for compile time type safety +typedef struct napi_env__* napi_env; +typedef struct napi_value__* napi_value; +typedef struct napi_ref__* napi_ref; +typedef struct napi_handle_scope__* napi_handle_scope; +typedef struct napi_escapable_handle_scope__* napi_escapable_handle_scope; +typedef struct napi_callback_info__* napi_callback_info; +typedef struct napi_deferred__* napi_deferred; + +typedef enum { + napi_default = 0, + napi_writable = 1 << 0, + napi_enumerable = 1 << 1, + napi_configurable = 1 << 2, + + // Used with napi_define_class to distinguish static properties + // from instance properties. Ignored by napi_define_properties. + napi_static = 1 << 10, +} napi_property_attributes; + +typedef enum { + // ES6 types (corresponds to typeof) + napi_undefined, + napi_null, + napi_boolean, + napi_number, + napi_string, + napi_symbol, + napi_object, + napi_function, + napi_external, + napi_bigint, +} napi_valuetype; + +typedef enum { + napi_int8_array, + napi_uint8_array, + napi_uint8_clamped_array, + napi_int16_array, + napi_uint16_array, + napi_int32_array, + napi_uint32_array, + napi_float32_array, + napi_float64_array, + napi_bigint64_array, + napi_biguint64_array, +} napi_typedarray_type; + +typedef enum { + napi_ok, + napi_invalid_arg, + napi_object_expected, + napi_string_expected, + napi_name_expected, + napi_function_expected, + napi_number_expected, + napi_boolean_expected, + napi_array_expected, + napi_generic_failure, + napi_pending_exception, + napi_cancelled, + napi_escape_called_twice, + napi_handle_scope_mismatch, + napi_callback_scope_mismatch, + napi_queue_full, + napi_closing, + napi_bigint_expected, +} napi_status; + +typedef napi_value (*napi_callback)(napi_env env, + napi_callback_info info); +typedef void (*napi_finalize)(napi_env env, + void* finalize_data, + void* finalize_hint); + +typedef struct { + // One of utf8name or name should be NULL. + const char* utf8name; + napi_value name; + + napi_callback method; + napi_callback getter; + napi_callback setter; + napi_value value; + + napi_property_attributes attributes; + void* data; +} napi_property_descriptor; + +typedef struct { + const char* error_message; + void* engine_reserved; + uint32_t engine_error_code; + napi_status error_code; +} napi_extended_error_info; + +#endif // SRC_JS_NATIVE_API_TYPES_H_ diff --git a/Source/Napi/js_native_api_v8.cc b/Source/Napi/js_native_api_v8.cc new file mode 100644 index 000000000..293442da9 --- /dev/null +++ b/Source/Napi/js_native_api_v8.cc @@ -0,0 +1,2918 @@ +#include // INT_MAX +#include +#include +#define NAPI_EXPERIMENTAL +#include "js_native_api_v8.h" +#include "js_native_api.h" + +#define CHECK_MAYBE_NOTHING(env, maybe, status) \ + RETURN_STATUS_IF_FALSE((env), !((maybe).IsNothing()), (status)) + +#define CHECK_TO_NUMBER(env, context, result, src) \ + CHECK_TO_TYPE((env), Number, (context), (result), (src), napi_number_expected) + +#define CHECK_TO_BOOL(env, context, result, src) \ + CHECK_TO_TYPE((env), Boolean, (context), (result), (src), \ + napi_boolean_expected) + +// n-api defines NAPI_AUTO_LENGHTH as the indicator that a string +// is null terminated. For V8 the equivalent is -1. The assert +// validates that our cast of NAPI_AUTO_LENGTH results in -1 as +// needed by V8. +#define CHECK_NEW_FROM_UTF8_LEN(env, result, str, len) \ + do { \ + static_assert(static_cast(NAPI_AUTO_LENGTH) == -1, \ + "Casting NAPI_AUTO_LENGTH to int must result in -1"); \ + RETURN_STATUS_IF_FALSE((env), \ + (len == NAPI_AUTO_LENGTH) || len <= INT_MAX, \ + napi_invalid_arg); \ + auto str_maybe = v8::String::NewFromUtf8( \ + (env)->isolate, (str), v8::NewStringType::kNormal, \ + static_cast(len)); \ + CHECK_MAYBE_EMPTY((env), str_maybe, napi_generic_failure); \ + (result) = str_maybe.ToLocalChecked(); \ + } while (0) + +#define CHECK_NEW_FROM_UTF8(env, result, str) \ + CHECK_NEW_FROM_UTF8_LEN((env), (result), (str), NAPI_AUTO_LENGTH) + +#define CREATE_TYPED_ARRAY( \ + env, type, size_of_element, buffer, byte_offset, length, out) \ + do { \ + if ((size_of_element) > 1) { \ + THROW_RANGE_ERROR_IF_FALSE( \ + (env), (byte_offset) % (size_of_element) == 0, \ + "ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT", \ + "start offset of "#type" should be a multiple of "#size_of_element); \ + } \ + THROW_RANGE_ERROR_IF_FALSE((env), (length) * (size_of_element) + \ + (byte_offset) <= buffer->ByteLength(), \ + "ERR_NAPI_INVALID_TYPEDARRAY_LENGTH", \ + "Invalid typed array length"); \ + (out) = v8::type::New((buffer), (byte_offset), (length)); \ + } while (0) + +namespace v8impl { + +namespace { + +inline static napi_status +V8NameFromPropertyDescriptor(napi_env env, + const napi_property_descriptor* p, + v8::Local* result) { + if (p->utf8name != nullptr) { + CHECK_NEW_FROM_UTF8(env, *result, p->utf8name); + } else { + v8::Local property_value = + v8impl::V8LocalValueFromJsValue(p->name); + + RETURN_STATUS_IF_FALSE(env, property_value->IsName(), napi_name_expected); + *result = property_value.As(); + } + + return napi_ok; +} + +// convert from n-api property attributes to v8::PropertyAttribute +inline static v8::PropertyAttribute V8PropertyAttributesFromDescriptor( + const napi_property_descriptor* descriptor) { + unsigned int attribute_flags = v8::PropertyAttribute::None; + + if (descriptor->getter != nullptr || descriptor->setter != nullptr) { + // The napi_writable attribute is ignored for accessor descriptors, but + // V8 requires the ReadOnly attribute to match nonexistence of a setter. + attribute_flags |= (descriptor->setter == nullptr ? + v8::PropertyAttribute::ReadOnly : v8::PropertyAttribute::None); + } else if ((descriptor->attributes & napi_writable) == 0) { + attribute_flags |= v8::PropertyAttribute::ReadOnly; + } + + if ((descriptor->attributes & napi_enumerable) == 0) { + attribute_flags |= v8::PropertyAttribute::DontEnum; + } + if ((descriptor->attributes & napi_configurable) == 0) { + attribute_flags |= v8::PropertyAttribute::DontDelete; + } + + return static_cast(attribute_flags); +} + +inline static napi_deferred +JsDeferredFromNodePersistent(v8impl::Persistent* local) { + return reinterpret_cast(local); +} + +inline static v8impl::Persistent* +NodePersistentFromJsDeferred(napi_deferred local) { + return reinterpret_cast*>(local); +} + +class HandleScopeWrapper { + public: + explicit HandleScopeWrapper(v8::Isolate* isolate) : scope(isolate) {} + + private: + v8::HandleScope scope; +}; + +// In node v0.10 version of v8, there is no EscapableHandleScope and the +// node v0.10 port use HandleScope::Close(Local v) to mimic the behavior +// of a EscapableHandleScope::Escape(Local v), but it is not the same +// semantics. This is an example of where the api abstraction fail to work +// across different versions. +class EscapableHandleScopeWrapper { + public: + explicit EscapableHandleScopeWrapper(v8::Isolate* isolate) + : scope(isolate), escape_called_(false) {} + bool escape_called() const { + return escape_called_; + } + template + v8::Local Escape(v8::Local handle) { + escape_called_ = true; + return scope.Escape(handle); + } + + private: + v8::EscapableHandleScope scope; + bool escape_called_; +}; + +inline static napi_handle_scope +JsHandleScopeFromV8HandleScope(HandleScopeWrapper* s) { + return reinterpret_cast(s); +} + +inline static HandleScopeWrapper* +V8HandleScopeFromJsHandleScope(napi_handle_scope s) { + return reinterpret_cast(s); +} + +inline static napi_escapable_handle_scope +JsEscapableHandleScopeFromV8EscapableHandleScope( + EscapableHandleScopeWrapper* s) { + return reinterpret_cast(s); +} + +inline static EscapableHandleScopeWrapper* +V8EscapableHandleScopeFromJsEscapableHandleScope( + napi_escapable_handle_scope s) { + return reinterpret_cast(s); +} + +inline static napi_status ConcludeDeferred(napi_env env, + napi_deferred deferred, + napi_value result, + bool is_resolved) { + NAPI_PREAMBLE(env); + CHECK_ARG(env, result); + + v8::Local context = env->isolate->GetCurrentContext(); + v8impl::Persistent* deferred_ref = + NodePersistentFromJsDeferred(deferred); + v8::Local v8_deferred = + v8::Local::New(env->isolate, *deferred_ref); + + auto v8_resolver = v8::Local::Cast(v8_deferred); + + v8::Maybe success = is_resolved ? + v8_resolver->Resolve(context, v8impl::V8LocalValueFromJsValue(result)) : + v8_resolver->Reject(context, v8impl::V8LocalValueFromJsValue(result)); + + delete deferred_ref; + + RETURN_STATUS_IF_FALSE(env, success.FromMaybe(false), napi_generic_failure); + + return GET_RETURN_STATUS(env); +} + +// Wrapper around v8impl::Persistent that implements reference counting. +class Reference : private Finalizer { + private: + Reference(napi_env env, + v8::Local value, + uint32_t initial_refcount, + bool delete_self, + napi_finalize finalize_callback, + void* finalize_data, + void* finalize_hint) + : Finalizer(env, finalize_callback, finalize_data, finalize_hint), + _persistent(env->isolate, value), + _refcount(initial_refcount), + _delete_self(delete_self) { + if (initial_refcount == 0) { + _persistent.SetWeak( + this, FinalizeCallback, v8::WeakCallbackType::kParameter); + } + } + + public: + void* Data() { + return _finalize_data; + } + + static Reference* New(napi_env env, + v8::Local value, + uint32_t initial_refcount, + bool delete_self, + napi_finalize finalize_callback = nullptr, + void* finalize_data = nullptr, + void* finalize_hint = nullptr) { + return new Reference(env, + value, + initial_refcount, + delete_self, + finalize_callback, + finalize_data, + finalize_hint); + } + + static void Delete(Reference* reference) { + delete reference; + } + + uint32_t Ref() { + if (++_refcount == 1) { + _persistent.ClearWeak(); + } + + return _refcount; + } + + uint32_t Unref() { + if (_refcount == 0) { + return 0; + } + if (--_refcount == 0) { + _persistent.SetWeak( + this, FinalizeCallback, v8::WeakCallbackType::kParameter); + } + + return _refcount; + } + + uint32_t RefCount() { + return _refcount; + } + + v8::Local Get() { + if (_persistent.IsEmpty()) { + return v8::Local(); + } else { + return v8::Local::New(_env->isolate, _persistent); + } + } + + private: + static void FinalizeCallback(const v8::WeakCallbackInfo& data) { + Reference* reference = data.GetParameter(); + reference->_persistent.Reset(); + + // Check before calling the finalize callback, because the callback might + // delete it. + bool delete_self = reference->_delete_self; + napi_env env = reference->_env; + + if (reference->_finalize_callback != nullptr) { + NAPI_CALL_INTO_MODULE_THROW(env, + reference->_finalize_callback( + reference->_env, + reference->_finalize_data, + reference->_finalize_hint)); + } + + if (delete_self) { + Delete(reference); + } + } + + v8impl::Persistent _persistent; + uint32_t _refcount; + bool _delete_self; +}; + +enum UnwrapAction { + KeepWrap, + RemoveWrap +}; + +inline static napi_status Unwrap(napi_env env, + napi_value js_object, + void** result, + UnwrapAction action) { + //NAPI_PREAMBLE(env); + CHECK_ARG(env, js_object); + if (action == KeepWrap) { + CHECK_ARG(env, result); + } + + //v8::Local context = isolate->GetCurrentContext(); + + v8::Local value = v8impl::V8LocalValueFromJsValue(js_object); + //RETURN_STATUS_IF_FALSE(env, value->IsObject(), napi_invalid_arg); + v8::Local obj = value.As(); + + auto val = obj->GetInternalField(0); + //auto val = obj->GetPrivate(context, NAPI_PRIVATE_KEY(context, wrapper)) + // .ToLocalChecked(); + //RETURN_STATUS_IF_FALSE(env, val->IsExternal(), napi_invalid_arg); + Reference* reference = + static_cast(val.As()->Value()); + + if (result) { + *result = reference->Data(); + } + + if (action == RemoveWrap) { + //CHECK(obj->DeletePrivate(context, NAPI_PRIVATE_KEY(context, wrapper)) + // .FromJust()); + obj->SetInternalField(0, v8::Undefined(env->isolate)); + Reference::Delete(reference); + } + + //return GET_RETURN_STATUS(env); + return napi_ok; +} + +//=== Function napi_callback wrapper ================================= + +// Use this data structure to associate callback data with each N-API function +// exposed to JavaScript. The structure is stored in a v8::External which gets +// passed into our callback wrapper. This reduces the performance impact of +// calling through N-API. +// Ref: benchmark/misc/function_call +// Discussion (incl. perf. data): https://github.com/nodejs/node/pull/21072 +struct CallbackBundle { + // Bind the lifecycle of `this` C++ object to a JavaScript object. + // We never delete a CallbackBundle C++ object directly. + void BindLifecycleTo(v8::Isolate* isolate, v8::Local target) { + handle.Reset(isolate, target); + handle.SetWeak(this, WeakCallback, v8::WeakCallbackType::kParameter); + } + + napi_env env; // Necessary to invoke C++ NAPI callback + void* cb_data; // The user provided callback data + napi_callback function_or_getter; + napi_callback setter; + v8impl::Persistent handle; // Die with this JavaScript object + + private: + static void WeakCallback(v8::WeakCallbackInfo const& info) { + // Use the "WeakCallback mechanism" to delete the C++ `bundle` object. + // This will be called when the v8::External containing `this` pointer + // is being GC-ed. + CallbackBundle* bundle = info.GetParameter(); + if (bundle != nullptr) { + delete bundle; + } + } +}; + +// Base class extended by classes that wrap V8 function and property callback +// info. +class CallbackWrapper { + public: + CallbackWrapper(napi_value this_arg, size_t args_length, void* data) + : _this(this_arg), _args_length(args_length), _data(data) {} + + virtual napi_value GetNewTarget() = 0; + virtual void Args(napi_value* buffer, size_t bufferlength) = 0; + virtual void SetReturnValue(napi_value value) = 0; + + napi_value This() { return _this; } + + size_t ArgsLength() { return _args_length; } + + void* Data() { return _data; } + + protected: + const napi_value _this; + const size_t _args_length; + void* _data; +}; + +template +class CallbackWrapperBase : public CallbackWrapper { + public: + CallbackWrapperBase(const Info& cbinfo, const size_t args_length) + : CallbackWrapper(JsValueFromV8LocalValue(cbinfo.This()), + args_length, + nullptr), + _cbinfo(cbinfo) { + _bundle = reinterpret_cast( + v8::Local::Cast(cbinfo.Data())->Value()); + _data = _bundle->cb_data; + } + + napi_value GetNewTarget() override { return nullptr; } + + protected: + void InvokeCallback() { + napi_callback_info cbinfo_wrapper = reinterpret_cast( + static_cast(this)); + + // All other pointers we need are stored in `_bundle` + napi_env env = _bundle->env; + napi_callback cb = _bundle->*FunctionField; + + napi_value result; + NAPI_CALL_INTO_MODULE_THROW(env, result = cb(env, cbinfo_wrapper)); + + if (result != nullptr) { + this->SetReturnValue(result); + } + } + + const Info& _cbinfo; + CallbackBundle* _bundle; +}; + +class FunctionCallbackWrapper + : public CallbackWrapperBase, + &CallbackBundle::function_or_getter> { + public: + static void Invoke(const v8::FunctionCallbackInfo& info) { + FunctionCallbackWrapper cbwrapper(info); + cbwrapper.InvokeCallback(); + } + + explicit FunctionCallbackWrapper( + const v8::FunctionCallbackInfo& cbinfo) + : CallbackWrapperBase(cbinfo, cbinfo.Length()) {} + + napi_value GetNewTarget() override { + if (_cbinfo.IsConstructCall()) { + return v8impl::JsValueFromV8LocalValue(_cbinfo.NewTarget()); + } else { + return nullptr; + } + } + + /*virtual*/ + void Args(napi_value* buffer, size_t buffer_length) override { + size_t i = 0; + size_t min = std::min(buffer_length, _args_length); + + for (; i < min; i += 1) { + buffer[i] = v8impl::JsValueFromV8LocalValue(_cbinfo[i]); + } + + if (i < buffer_length) { + napi_value undefined = + v8impl::JsValueFromV8LocalValue(v8::Undefined(_cbinfo.GetIsolate())); + for (; i < buffer_length; i += 1) { + buffer[i] = undefined; + } + } + } + + /*virtual*/ + void SetReturnValue(napi_value value) override { + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + _cbinfo.GetReturnValue().Set(val); + } +}; + +class GetterCallbackWrapper + : public CallbackWrapperBase, + &CallbackBundle::function_or_getter> { + public: + static void Invoke(v8::Local property, + const v8::PropertyCallbackInfo& info) { + GetterCallbackWrapper cbwrapper(info); + cbwrapper.InvokeCallback(); + } + + explicit GetterCallbackWrapper( + const v8::PropertyCallbackInfo& cbinfo) + : CallbackWrapperBase(cbinfo, 0) {} + + /*virtual*/ + void Args(napi_value* buffer, size_t buffer_length) override { + if (buffer_length > 0) { + napi_value undefined = + v8impl::JsValueFromV8LocalValue(v8::Undefined(_cbinfo.GetIsolate())); + for (size_t i = 0; i < buffer_length; i += 1) { + buffer[i] = undefined; + } + } + } + + /*virtual*/ + void SetReturnValue(napi_value value) override { + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + _cbinfo.GetReturnValue().Set(val); + } +}; + +class SetterCallbackWrapper + : public CallbackWrapperBase, + &CallbackBundle::setter> { + public: + static void Invoke(v8::Local property, + v8::Local value, + const v8::PropertyCallbackInfo& info) { + SetterCallbackWrapper cbwrapper(info, value); + cbwrapper.InvokeCallback(); + } + + SetterCallbackWrapper(const v8::PropertyCallbackInfo& cbinfo, + const v8::Local& value) + : CallbackWrapperBase(cbinfo, 1), _value(value) {} + + /*virtual*/ + void Args(napi_value* buffer, size_t buffer_length) override { + if (buffer_length > 0) { + buffer[0] = v8impl::JsValueFromV8LocalValue(_value); + + if (buffer_length > 1) { + napi_value undefined = v8impl::JsValueFromV8LocalValue( + v8::Undefined(_cbinfo.GetIsolate())); + for (size_t i = 1; i < buffer_length; i += 1) { + buffer[i] = undefined; + } + } + } + } + + /*virtual*/ + void SetReturnValue(napi_value value) override { + // Ignore any value returned from a setter callback. + } + + private: + const v8::Local& _value; +}; + +// Creates an object to be made available to the static function callback +// wrapper, used to retrieve the native callback function and data pointer. +static +v8::Local CreateFunctionCallbackData(napi_env env, + napi_callback cb, + void* data) { + CallbackBundle* bundle = new CallbackBundle(); + bundle->function_or_getter = cb; + bundle->cb_data = data; + bundle->env = env; + v8::Local cbdata = v8::External::New(env->isolate, bundle); + bundle->BindLifecycleTo(env->isolate, cbdata); + + return cbdata; +} + +// Creates an object to be made available to the static getter/setter +// callback wrapper, used to retrieve the native getter/setter callback +// function and data pointer. +inline v8::Local CreateAccessorCallbackData(napi_env env, + napi_callback getter, + napi_callback setter, + void* data) { + CallbackBundle* bundle = new CallbackBundle(); + bundle->function_or_getter = getter; + bundle->setter = setter; + bundle->cb_data = data; + bundle->env = env; + v8::Local cbdata = v8::External::New(env->isolate, bundle); + bundle->BindLifecycleTo(env->isolate, cbdata); + + return cbdata; +} + +enum WrapType { + retrievable, + anonymous +}; + +template +inline napi_status Wrap(napi_env env, + napi_value js_object, + void* native_object, + napi_finalize finalize_cb, + void* finalize_hint, + napi_ref* result) { + NAPI_PREAMBLE(env); + CHECK_ARG(env, js_object); + + v8::Local context = env->context(); + + v8::Local value = v8impl::V8LocalValueFromJsValue(js_object); + RETURN_STATUS_IF_FALSE(env, value->IsObject(), napi_invalid_arg); + v8::Local obj = value.As(); + + if (wrap_type == retrievable) { + // If we've already wrapped this object, we error out. + //RETURN_STATUS_IF_FALSE(env, + // !obj->HasPrivate(context, NAPI_PRIVATE_KEY(context, wrapper)) + // .FromJust(), + // napi_invalid_arg); + RETURN_STATUS_IF_FALSE(env, + obj->GetInternalField(0)->IsUndefined(), + napi_invalid_arg); + } else if (wrap_type == anonymous) { + // If no finalize callback is provided, we error out. + CHECK_ARG(env, finalize_cb); + } + + v8impl::Reference* reference = nullptr; + if (result != nullptr) { + // The returned reference should be deleted via napi_delete_reference() + // ONLY in response to the finalize callback invocation. (If it is deleted + // before then, then the finalize callback will never be invoked.) + // Therefore a finalize callback is required when returning a reference. + CHECK_ARG(env, finalize_cb); + reference = v8impl::Reference::New( + env, obj, 0, false, finalize_cb, native_object, finalize_hint); + *result = reinterpret_cast(reference); + } else { + // Create a self-deleting reference. + reference = v8impl::Reference::New(env, obj, 0, true, finalize_cb, + native_object, finalize_cb == nullptr ? nullptr : finalize_hint); + } + + if (wrap_type == retrievable) { + //CHECK(obj->SetPrivate(context, NAPI_PRIVATE_KEY(context, wrapper), + // v8::External::New(env->isolate, reference)).FromJust()); + obj->SetInternalField(0, v8::External::New(env->isolate, reference)); + } + + return GET_RETURN_STATUS(env); +} + +} // end of anonymous namespace + +} // end of namespace v8impl + +// Warning: Keep in-sync with napi_status enum +static +const char* error_messages[] = {nullptr, + "Invalid argument", + "An object was expected", + "A string was expected", + "A string or symbol was expected", + "A function was expected", + "A number was expected", + "A boolean was expected", + "An array was expected", + "Unknown failure", + "An exception is pending", + "The async work item was cancelled", + "napi_escape_handle already called on scope", + "Invalid handle scope usage", + "Invalid callback scope usage", + "Thread-safe function queue is full", + "Thread-safe function handle is closing", + "A bigint was expected", +}; + +napi_status napi_get_last_error_info(napi_env env, + const napi_extended_error_info** result) { + CHECK_ENV(env); + CHECK_ARG(env, result); + + // you must update this assert to reference the last message + // in the napi_status enum each time a new error message is added. + // We don't have a napi_status_last as this would result in an ABI + // change each time a message was added. + static_assert( + NAPI_ARRAYSIZE(error_messages) == napi_bigint_expected + 1, + "Count of error messages must match count of error values"); + CHECK_LE(env->last_error.error_code, napi_callback_scope_mismatch); + + // Wait until someone requests the last error information to fetch the error + // message string + env->last_error.error_message = + error_messages[env->last_error.error_code]; + + *result = &(env->last_error); + return napi_ok; +} + +napi_status napi_create_function(napi_env env, + const char* utf8name, + size_t length, + napi_callback cb, + void* callback_data, + napi_value* result) { + NAPI_PREAMBLE(env); + CHECK_ARG(env, result); + CHECK_ARG(env, cb); + + v8::Isolate* isolate = env->isolate; + v8::Local return_value; + v8::EscapableHandleScope scope(isolate); + v8::Local cbdata = + v8impl::CreateFunctionCallbackData(env, cb, callback_data); + + RETURN_STATUS_IF_FALSE(env, !cbdata.IsEmpty(), napi_generic_failure); + + v8::Local context = env->context(); + v8::MaybeLocal maybe_function = + v8::Function::New(context, + v8impl::FunctionCallbackWrapper::Invoke, + cbdata); + CHECK_MAYBE_EMPTY(env, maybe_function, napi_generic_failure); + + return_value = scope.Escape(maybe_function.ToLocalChecked()); + + if (utf8name != nullptr) { + v8::Local name_string; + CHECK_NEW_FROM_UTF8_LEN(env, name_string, utf8name, length); + return_value->SetName(name_string); + } + + *result = v8impl::JsValueFromV8LocalValue(return_value); + + return GET_RETURN_STATUS(env); +} + +napi_status napi_define_class(napi_env env, + const char* utf8name, + size_t length, + napi_callback constructor, + void* callback_data, + size_t property_count, + const napi_property_descriptor* properties, + napi_value* result) { + NAPI_PREAMBLE(env); + CHECK_ARG(env, result); + CHECK_ARG(env, constructor); + + v8::Isolate* isolate = env->isolate; + + v8::EscapableHandleScope scope(isolate); + v8::Local cbdata = + v8impl::CreateFunctionCallbackData(env, constructor, callback_data); + + RETURN_STATUS_IF_FALSE(env, !cbdata.IsEmpty(), napi_generic_failure); + + v8::Local tpl = v8::FunctionTemplate::New( + isolate, v8impl::FunctionCallbackWrapper::Invoke, cbdata); + + tpl->InstanceTemplate()->SetInternalFieldCount(1); + + v8::Local name_string; + CHECK_NEW_FROM_UTF8_LEN(env, name_string, utf8name, length); + tpl->SetClassName(name_string); + + size_t static_property_count = 0; + for (size_t i = 0; i < property_count; i++) { + const napi_property_descriptor* p = properties + i; + + if ((p->attributes & napi_static) != 0) { + // Static properties are handled separately below. + static_property_count++; + continue; + } + + v8::Local property_name; + napi_status status = + v8impl::V8NameFromPropertyDescriptor(env, p, &property_name); + + if (status != napi_ok) { + return napi_set_last_error(env, status); + } + + v8::PropertyAttribute attributes = + v8impl::V8PropertyAttributesFromDescriptor(p); + + // This code is similar to that in napi_define_properties(); the + // difference is it applies to a template instead of an object. + if (p->getter != nullptr || p->setter != nullptr) { + v8::Local cbdata = v8impl::CreateAccessorCallbackData( + env, p->getter, p->setter, p->data); + + tpl->PrototypeTemplate()->SetAccessor( + property_name, + p->getter ? v8impl::GetterCallbackWrapper::Invoke : nullptr, + p->setter ? v8impl::SetterCallbackWrapper::Invoke : nullptr, + cbdata, + v8::AccessControl::DEFAULT, + attributes); + } else if (p->method != nullptr) { + v8::Local cbdata = + v8impl::CreateFunctionCallbackData(env, p->method, p->data); + + RETURN_STATUS_IF_FALSE(env, !cbdata.IsEmpty(), napi_generic_failure); + + v8::Local t = + v8::FunctionTemplate::New(isolate, + v8impl::FunctionCallbackWrapper::Invoke, + cbdata, + v8::Signature::New(isolate, tpl)); + + tpl->PrototypeTemplate()->Set(property_name, t, attributes); + } else { + v8::Local value = v8impl::V8LocalValueFromJsValue(p->value); + tpl->PrototypeTemplate()->Set(property_name, value, attributes); + } + } + + v8::Local context = env->context(); + *result = v8impl::JsValueFromV8LocalValue( + scope.Escape(tpl->GetFunction(context).ToLocalChecked())); + + if (static_property_count > 0) { + std::vector static_descriptors; + static_descriptors.reserve(static_property_count); + + for (size_t i = 0; i < property_count; i++) { + const napi_property_descriptor* p = properties + i; + if ((p->attributes & napi_static) != 0) { + static_descriptors.push_back(*p); + } + } + + napi_status status = + napi_define_properties(env, + *result, + static_descriptors.size(), + static_descriptors.data()); + if (status != napi_ok) return status; + } + + return GET_RETURN_STATUS(env); +} + +napi_status napi_get_property_names(napi_env env, + napi_value object, + napi_value* result) { + NAPI_PREAMBLE(env); + CHECK_ARG(env, result); + + v8::Local context = env->context(); + v8::Local obj; + CHECK_TO_OBJECT(env, context, obj, object); + + auto maybe_propertynames = obj->GetPropertyNames(context); + + CHECK_MAYBE_EMPTY(env, maybe_propertynames, napi_generic_failure); + + *result = v8impl::JsValueFromV8LocalValue( + maybe_propertynames.ToLocalChecked()); + return GET_RETURN_STATUS(env); +} + +napi_status napi_set_property(napi_env env, + napi_value object, + napi_value key, + napi_value value) { + NAPI_PREAMBLE(env); + CHECK_ARG(env, key); + CHECK_ARG(env, value); + + v8::Local context = env->context(); + v8::Local obj; + + CHECK_TO_OBJECT(env, context, obj, object); + + v8::Local k = v8impl::V8LocalValueFromJsValue(key); + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + + v8::Maybe set_maybe = obj->Set(context, k, val); + + RETURN_STATUS_IF_FALSE(env, set_maybe.FromMaybe(false), napi_generic_failure); + return GET_RETURN_STATUS(env); +} + +napi_status napi_has_property(napi_env env, + napi_value object, + napi_value key, + bool* result) { + NAPI_PREAMBLE(env); + CHECK_ARG(env, result); + CHECK_ARG(env, key); + + v8::Local context = env->context(); + v8::Local obj; + + CHECK_TO_OBJECT(env, context, obj, object); + + v8::Local k = v8impl::V8LocalValueFromJsValue(key); + v8::Maybe has_maybe = obj->Has(context, k); + + CHECK_MAYBE_NOTHING(env, has_maybe, napi_generic_failure); + + *result = has_maybe.FromMaybe(false); + return GET_RETURN_STATUS(env); +} + +napi_status napi_get_property(napi_env env, + napi_value object, + napi_value key, + napi_value* result) { + NAPI_PREAMBLE(env); + CHECK_ARG(env, key); + CHECK_ARG(env, result); + + v8::Local context = env->context(); + v8::Local k = v8impl::V8LocalValueFromJsValue(key); + v8::Local obj; + + CHECK_TO_OBJECT(env, context, obj, object); + + auto get_maybe = obj->Get(context, k); + + CHECK_MAYBE_EMPTY(env, get_maybe, napi_generic_failure); + + v8::Local val = get_maybe.ToLocalChecked(); + *result = v8impl::JsValueFromV8LocalValue(val); + return GET_RETURN_STATUS(env); +} + +napi_status napi_delete_property(napi_env env, + napi_value object, + napi_value key, + bool* result) { + NAPI_PREAMBLE(env); + CHECK_ARG(env, key); + + v8::Local context = env->context(); + v8::Local k = v8impl::V8LocalValueFromJsValue(key); + v8::Local obj; + + CHECK_TO_OBJECT(env, context, obj, object); + v8::Maybe delete_maybe = obj->Delete(context, k); + CHECK_MAYBE_NOTHING(env, delete_maybe, napi_generic_failure); + + if (result != nullptr) + *result = delete_maybe.FromMaybe(false); + + return GET_RETURN_STATUS(env); +} + +napi_status napi_has_own_property(napi_env env, + napi_value object, + napi_value key, + bool* result) { + NAPI_PREAMBLE(env); + CHECK_ARG(env, key); + + v8::Local context = env->context(); + v8::Local obj; + + CHECK_TO_OBJECT(env, context, obj, object); + v8::Local k = v8impl::V8LocalValueFromJsValue(key); + RETURN_STATUS_IF_FALSE(env, k->IsName(), napi_name_expected); + v8::Maybe has_maybe = obj->HasOwnProperty(context, k.As()); + CHECK_MAYBE_NOTHING(env, has_maybe, napi_generic_failure); + *result = has_maybe.FromMaybe(false); + + return GET_RETURN_STATUS(env); +} + +napi_status napi_set_named_property(napi_env env, + napi_value object, + const char* utf8name, + napi_value value) { + NAPI_PREAMBLE(env); + CHECK_ARG(env, value); + + v8::Local context = env->context(); + v8::Local obj; + + CHECK_TO_OBJECT(env, context, obj, object); + + v8::Local key; + CHECK_NEW_FROM_UTF8(env, key, utf8name); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + + v8::Maybe set_maybe = obj->Set(context, key, val); + + RETURN_STATUS_IF_FALSE(env, set_maybe.FromMaybe(false), napi_generic_failure); + return GET_RETURN_STATUS(env); +} + +napi_status napi_has_named_property(napi_env env, + napi_value object, + const char* utf8name, + bool* result) { + NAPI_PREAMBLE(env); + CHECK_ARG(env, result); + + v8::Local context = env->context(); + v8::Local obj; + + CHECK_TO_OBJECT(env, context, obj, object); + + v8::Local key; + CHECK_NEW_FROM_UTF8(env, key, utf8name); + + v8::Maybe has_maybe = obj->Has(context, key); + + CHECK_MAYBE_NOTHING(env, has_maybe, napi_generic_failure); + + *result = has_maybe.FromMaybe(false); + return GET_RETURN_STATUS(env); +} + +napi_status napi_get_named_property(napi_env env, + napi_value object, + const char* utf8name, + napi_value* result) { + NAPI_PREAMBLE(env); + CHECK_ARG(env, result); + + v8::Local context = env->context(); + + v8::Local key; + CHECK_NEW_FROM_UTF8(env, key, utf8name); + + v8::Local obj; + + CHECK_TO_OBJECT(env, context, obj, object); + + auto get_maybe = obj->Get(context, key); + + CHECK_MAYBE_EMPTY(env, get_maybe, napi_generic_failure); + + v8::Local val = get_maybe.ToLocalChecked(); + *result = v8impl::JsValueFromV8LocalValue(val); + return GET_RETURN_STATUS(env); +} + +napi_status napi_set_element(napi_env env, + napi_value object, + uint32_t index, + napi_value value) { + NAPI_PREAMBLE(env); + CHECK_ARG(env, value); + + v8::Local context = env->context(); + v8::Local obj; + + CHECK_TO_OBJECT(env, context, obj, object); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + auto set_maybe = obj->Set(context, index, val); + + RETURN_STATUS_IF_FALSE(env, set_maybe.FromMaybe(false), napi_generic_failure); + + return GET_RETURN_STATUS(env); +} + +napi_status napi_has_element(napi_env env, + napi_value object, + uint32_t index, + bool* result) { + NAPI_PREAMBLE(env); + CHECK_ARG(env, result); + + v8::Local context = env->context(); + v8::Local obj; + + CHECK_TO_OBJECT(env, context, obj, object); + + v8::Maybe has_maybe = obj->Has(context, index); + + CHECK_MAYBE_NOTHING(env, has_maybe, napi_generic_failure); + + *result = has_maybe.FromMaybe(false); + return GET_RETURN_STATUS(env); +} + +napi_status napi_get_element(napi_env env, + napi_value object, + uint32_t index, + napi_value* result) { + NAPI_PREAMBLE(env); + CHECK_ARG(env, result); + + v8::Local context = env->context(); + v8::Local obj; + + CHECK_TO_OBJECT(env, context, obj, object); + + auto get_maybe = obj->Get(context, index); + + CHECK_MAYBE_EMPTY(env, get_maybe, napi_generic_failure); + + *result = v8impl::JsValueFromV8LocalValue(get_maybe.ToLocalChecked()); + return GET_RETURN_STATUS(env); +} + +napi_status napi_delete_element(napi_env env, + napi_value object, + uint32_t index, + bool* result) { + NAPI_PREAMBLE(env); + + v8::Local context = env->context(); + v8::Local obj; + + CHECK_TO_OBJECT(env, context, obj, object); + v8::Maybe delete_maybe = obj->Delete(context, index); + CHECK_MAYBE_NOTHING(env, delete_maybe, napi_generic_failure); + + if (result != nullptr) + *result = delete_maybe.FromMaybe(false); + + return GET_RETURN_STATUS(env); +} + +napi_status napi_define_properties(napi_env env, + napi_value object, + size_t property_count, + const napi_property_descriptor* properties) { + NAPI_PREAMBLE(env); + if (property_count > 0) { + CHECK_ARG(env, properties); + } + + v8::Local context = env->context(); + + v8::Local obj; + CHECK_TO_OBJECT(env, context, obj, object); + + for (size_t i = 0; i < property_count; i++) { + const napi_property_descriptor* p = &properties[i]; + + v8::Local property_name; + napi_status status = + v8impl::V8NameFromPropertyDescriptor(env, p, &property_name); + + if (status != napi_ok) { + return napi_set_last_error(env, status); + } + + v8::PropertyAttribute attributes = + v8impl::V8PropertyAttributesFromDescriptor(p); + + if (p->getter != nullptr || p->setter != nullptr) { + v8::Local cbdata = v8impl::CreateAccessorCallbackData( + env, + p->getter, + p->setter, + p->data); + + auto set_maybe = obj->SetAccessor( + context, + property_name, + p->getter ? v8impl::GetterCallbackWrapper::Invoke : nullptr, + p->setter ? v8impl::SetterCallbackWrapper::Invoke : nullptr, + cbdata, + v8::AccessControl::DEFAULT, + attributes); + + if (!set_maybe.FromMaybe(false)) { + return napi_set_last_error(env, napi_invalid_arg); + } + } else if (p->method != nullptr) { + v8::Local cbdata = + v8impl::CreateFunctionCallbackData(env, p->method, p->data); + + CHECK_MAYBE_EMPTY(env, cbdata, napi_generic_failure); + + v8::MaybeLocal maybe_fn = + v8::Function::New(context, + v8impl::FunctionCallbackWrapper::Invoke, + cbdata); + + CHECK_MAYBE_EMPTY(env, maybe_fn, napi_generic_failure); + + auto define_maybe = obj->DefineOwnProperty( + context, property_name, maybe_fn.ToLocalChecked(), attributes); + + if (!define_maybe.FromMaybe(false)) { + return napi_set_last_error(env, napi_generic_failure); + } + } else { + v8::Local value = v8impl::V8LocalValueFromJsValue(p->value); + + auto define_maybe = + obj->DefineOwnProperty(context, property_name, value, attributes); + + if (!define_maybe.FromMaybe(false)) { + return napi_set_last_error(env, napi_invalid_arg); + } + } + } + + return GET_RETURN_STATUS(env); +} + +napi_status napi_is_array(napi_env env, napi_value value, bool* result) { + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, result); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + + *result = val->IsArray(); + return napi_clear_last_error(env); +} + +napi_status napi_get_array_length(napi_env env, + napi_value value, + uint32_t* result) { + NAPI_PREAMBLE(env); + CHECK_ARG(env, value); + CHECK_ARG(env, result); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + RETURN_STATUS_IF_FALSE(env, val->IsArray(), napi_array_expected); + + v8::Local arr = val.As(); + *result = arr->Length(); + + return GET_RETURN_STATUS(env); +} + +napi_status napi_strict_equals(napi_env env, + napi_value lhs, + napi_value rhs, + bool* result) { + NAPI_PREAMBLE(env); + CHECK_ARG(env, lhs); + CHECK_ARG(env, rhs); + CHECK_ARG(env, result); + + v8::Local a = v8impl::V8LocalValueFromJsValue(lhs); + v8::Local b = v8impl::V8LocalValueFromJsValue(rhs); + + *result = a->StrictEquals(b); + return GET_RETURN_STATUS(env); +} + +napi_status napi_get_prototype(napi_env env, + napi_value object, + napi_value* result) { + NAPI_PREAMBLE(env); + CHECK_ARG(env, result); + + v8::Local context = env->context(); + + v8::Local obj; + CHECK_TO_OBJECT(env, context, obj, object); + + v8::Local val = obj->GetPrototype(); + *result = v8impl::JsValueFromV8LocalValue(val); + return GET_RETURN_STATUS(env); +} + +napi_status napi_create_object(napi_env env, napi_value* result) { + CHECK_ENV(env); + CHECK_ARG(env, result); + + *result = v8impl::JsValueFromV8LocalValue( + v8::Object::New(env->isolate)); + + return napi_clear_last_error(env); +} + +napi_status napi_create_array(napi_env env, napi_value* result) { + CHECK_ENV(env); + CHECK_ARG(env, result); + + *result = v8impl::JsValueFromV8LocalValue( + v8::Array::New(env->isolate)); + + return napi_clear_last_error(env); +} + +napi_status napi_create_array_with_length(napi_env env, + size_t length, + napi_value* result) { + CHECK_ENV(env); + CHECK_ARG(env, result); + + *result = v8impl::JsValueFromV8LocalValue( + v8::Array::New(env->isolate, length)); + + return napi_clear_last_error(env); +} + +napi_status napi_create_string_latin1(napi_env env, + const char* str, + size_t length, + napi_value* result) { + CHECK_ENV(env); + CHECK_ARG(env, result); + + auto isolate = env->isolate; + auto str_maybe = + v8::String::NewFromOneByte(isolate, + reinterpret_cast(str), + v8::NewStringType::kInternalized, + length); + CHECK_MAYBE_EMPTY(env, str_maybe, napi_generic_failure); + + *result = v8impl::JsValueFromV8LocalValue(str_maybe.ToLocalChecked()); + return napi_clear_last_error(env); +} + +napi_status napi_create_string_utf8(napi_env env, + const char* str, + size_t length, + napi_value* result) { + CHECK_ENV(env); + CHECK_ARG(env, result); + + v8::Local s; + CHECK_NEW_FROM_UTF8_LEN(env, s, str, length); + + *result = v8impl::JsValueFromV8LocalValue(s); + return napi_clear_last_error(env); +} + +napi_status napi_create_string_utf16(napi_env env, + const char16_t* str, + size_t length, + napi_value* result) { + CHECK_ENV(env); + CHECK_ARG(env, result); + + auto isolate = env->isolate; + auto str_maybe = + v8::String::NewFromTwoByte(isolate, + reinterpret_cast(str), + v8::NewStringType::kInternalized, + length); + CHECK_MAYBE_EMPTY(env, str_maybe, napi_generic_failure); + + *result = v8impl::JsValueFromV8LocalValue(str_maybe.ToLocalChecked()); + return napi_clear_last_error(env); +} + +napi_status napi_create_double(napi_env env, + double value, + napi_value* result) { + CHECK_ENV(env); + CHECK_ARG(env, result); + + *result = v8impl::JsValueFromV8LocalValue( + v8::Number::New(env->isolate, value)); + + return napi_clear_last_error(env); +} + +napi_status napi_create_int32(napi_env env, + int32_t value, + napi_value* result) { + CHECK_ENV(env); + CHECK_ARG(env, result); + + *result = v8impl::JsValueFromV8LocalValue( + v8::Integer::New(env->isolate, value)); + + return napi_clear_last_error(env); +} + +napi_status napi_create_uint32(napi_env env, + uint32_t value, + napi_value* result) { + CHECK_ENV(env); + CHECK_ARG(env, result); + + *result = v8impl::JsValueFromV8LocalValue( + v8::Integer::NewFromUnsigned(env->isolate, value)); + + return napi_clear_last_error(env); +} + +napi_status napi_create_int64(napi_env env, + int64_t value, + napi_value* result) { + CHECK_ENV(env); + CHECK_ARG(env, result); + + *result = v8impl::JsValueFromV8LocalValue( + v8::Number::New(env->isolate, static_cast(value))); + + return napi_clear_last_error(env); +} + +napi_status napi_create_bigint_int64(napi_env env, + int64_t value, + napi_value* result) { + CHECK_ENV(env); + CHECK_ARG(env, result); + + *result = v8impl::JsValueFromV8LocalValue( + v8::BigInt::New(env->isolate, value)); + + return napi_clear_last_error(env); +} + +napi_status napi_create_bigint_uint64(napi_env env, + uint64_t value, + napi_value* result) { + CHECK_ENV(env); + CHECK_ARG(env, result); + + *result = v8impl::JsValueFromV8LocalValue( + v8::BigInt::NewFromUnsigned(env->isolate, value)); + + return napi_clear_last_error(env); +} + +napi_status napi_create_bigint_words(napi_env env, + int sign_bit, + size_t word_count, + const uint64_t* words, + napi_value* result) { + NAPI_PREAMBLE(env); + CHECK_ARG(env, words); + CHECK_ARG(env, result); + + v8::Local context = env->context(); + + if (word_count > INT_MAX) { + napi_throw_range_error(env, nullptr, "Maximum BigInt size exceeded"); + return napi_set_last_error(env, napi_pending_exception); + } + + v8::MaybeLocal b = v8::BigInt::NewFromWords( + context, sign_bit, word_count, words); + + if (try_catch.HasCaught()) { + return napi_set_last_error(env, napi_pending_exception); + } else { + CHECK_MAYBE_EMPTY(env, b, napi_generic_failure); + *result = v8impl::JsValueFromV8LocalValue(b.ToLocalChecked()); + return napi_clear_last_error(env); + } +} + +napi_status napi_get_boolean(napi_env env, bool value, napi_value* result) { + CHECK_ENV(env); + CHECK_ARG(env, result); + + v8::Isolate* isolate = env->isolate; + + if (value) { + *result = v8impl::JsValueFromV8LocalValue(v8::True(isolate)); + } else { + *result = v8impl::JsValueFromV8LocalValue(v8::False(isolate)); + } + + return napi_clear_last_error(env); +} + +napi_status napi_create_symbol(napi_env env, + napi_value description, + napi_value* result) { + CHECK_ENV(env); + CHECK_ARG(env, result); + + v8::Isolate* isolate = env->isolate; + + if (description == nullptr) { + *result = v8impl::JsValueFromV8LocalValue(v8::Symbol::New(isolate)); + } else { + v8::Local desc = v8impl::V8LocalValueFromJsValue(description); + RETURN_STATUS_IF_FALSE(env, desc->IsString(), napi_string_expected); + + *result = v8impl::JsValueFromV8LocalValue( + v8::Symbol::New(isolate, desc.As())); + } + + return napi_clear_last_error(env); +} + +static inline napi_status set_error_code(napi_env env, + v8::Local error, + napi_value code, + const char* code_cstring) { + if ((code != nullptr) || (code_cstring != nullptr)) { + v8::Isolate* isolate = env->isolate; + v8::Local context = env->context(); + v8::Local err_object = error.As(); + + v8::Local code_value = v8impl::V8LocalValueFromJsValue(code); + if (code != nullptr) { + code_value = v8impl::V8LocalValueFromJsValue(code); + RETURN_STATUS_IF_FALSE(env, code_value->IsString(), napi_string_expected); + } else { + CHECK_NEW_FROM_UTF8(env, code_value, code_cstring); + } + + v8::Local code_key; + CHECK_NEW_FROM_UTF8(env, code_key, "code"); + + v8::Maybe set_maybe = err_object->Set(context, code_key, code_value); + RETURN_STATUS_IF_FALSE(env, + set_maybe.FromMaybe(false), + napi_generic_failure); + + // now update the name to be "name [code]" where name is the + // original name and code is the code associated with the Error + v8::Local name_string; + CHECK_NEW_FROM_UTF8(env, name_string, ""); + v8::Local name_key; + CHECK_NEW_FROM_UTF8(env, name_key, "name"); + + auto maybe_name = err_object->Get(context, name_key); + if (!maybe_name.IsEmpty()) { + v8::Local name = maybe_name.ToLocalChecked(); + if (name->IsString()) { + name_string = + v8::String::Concat(isolate, name_string, name.As()); + } + } + name_string = v8::String::Concat( + isolate, name_string, NAPI_FIXED_ONE_BYTE_STRING(isolate, " [")); + name_string = + v8::String::Concat(isolate, name_string, code_value.As()); + name_string = v8::String::Concat( + isolate, name_string, NAPI_FIXED_ONE_BYTE_STRING(isolate, "]")); + + set_maybe = err_object->Set(context, name_key, name_string); + RETURN_STATUS_IF_FALSE(env, + set_maybe.FromMaybe(false), + napi_generic_failure); + } + return napi_ok; +} + +napi_status napi_create_error(napi_env env, + napi_value code, + napi_value msg, + napi_value* result) { + CHECK_ENV(env); + CHECK_ARG(env, msg); + CHECK_ARG(env, result); + + v8::Local message_value = v8impl::V8LocalValueFromJsValue(msg); + RETURN_STATUS_IF_FALSE(env, message_value->IsString(), napi_string_expected); + + v8::Local error_obj = + v8::Exception::Error(message_value.As()); + napi_status status = set_error_code(env, error_obj, code, nullptr); + if (status != napi_ok) return status; + + *result = v8impl::JsValueFromV8LocalValue(error_obj); + + return napi_clear_last_error(env); +} + +napi_status napi_create_type_error(napi_env env, + napi_value code, + napi_value msg, + napi_value* result) { + CHECK_ENV(env); + CHECK_ARG(env, msg); + CHECK_ARG(env, result); + + v8::Local message_value = v8impl::V8LocalValueFromJsValue(msg); + RETURN_STATUS_IF_FALSE(env, message_value->IsString(), napi_string_expected); + + v8::Local error_obj = + v8::Exception::TypeError(message_value.As()); + napi_status status = set_error_code(env, error_obj, code, nullptr); + if (status != napi_ok) return status; + + *result = v8impl::JsValueFromV8LocalValue(error_obj); + + return napi_clear_last_error(env); +} + +napi_status napi_create_range_error(napi_env env, + napi_value code, + napi_value msg, + napi_value* result) { + CHECK_ENV(env); + CHECK_ARG(env, msg); + CHECK_ARG(env, result); + + v8::Local message_value = v8impl::V8LocalValueFromJsValue(msg); + RETURN_STATUS_IF_FALSE(env, message_value->IsString(), napi_string_expected); + + v8::Local error_obj = + v8::Exception::RangeError(message_value.As()); + napi_status status = set_error_code(env, error_obj, code, nullptr); + if (status != napi_ok) return status; + + *result = v8impl::JsValueFromV8LocalValue(error_obj); + + return napi_clear_last_error(env); +} + +napi_status napi_typeof(napi_env env, + napi_value value, + napi_valuetype* result) { + // Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw + // JS exceptions. + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, result); + + v8::Local v = v8impl::V8LocalValueFromJsValue(value); + + if (v->IsNumber()) { + *result = napi_number; + } else if (v->IsBigInt()) { + *result = napi_bigint; + } else if (v->IsString()) { + *result = napi_string; + } else if (v->IsFunction()) { + // This test has to come before IsObject because IsFunction + // implies IsObject + *result = napi_function; + } else if (v->IsExternal()) { + // This test has to come before IsObject because IsExternal + // implies IsObject + *result = napi_external; + } else if (v->IsObject()) { + *result = napi_object; + } else if (v->IsBoolean()) { + *result = napi_boolean; + } else if (v->IsUndefined()) { + *result = napi_undefined; + } else if (v->IsSymbol()) { + *result = napi_symbol; + } else if (v->IsNull()) { + *result = napi_null; + } else { + // Should not get here unless V8 has added some new kind of value. + return napi_set_last_error(env, napi_invalid_arg); + } + + return napi_clear_last_error(env); +} + +napi_status napi_get_undefined(napi_env env, napi_value* result) { + CHECK_ENV(env); + CHECK_ARG(env, result); + + *result = v8impl::JsValueFromV8LocalValue( + v8::Undefined(env->isolate)); + + return napi_clear_last_error(env); +} + +napi_status napi_get_null(napi_env env, napi_value* result) { + CHECK_ENV(env); + CHECK_ARG(env, result); + + *result = v8impl::JsValueFromV8LocalValue( + v8::Null(env->isolate)); + + return napi_clear_last_error(env); +} + +// Gets all callback info in a single call. (Ugly, but faster.) +napi_status napi_get_cb_info( + napi_env env, // [in] NAPI environment handle + napi_callback_info cbinfo, // [in] Opaque callback-info handle + size_t* argc, // [in-out] Specifies the size of the provided argv array + // and receives the actual count of args. + napi_value* argv, // [out] Array of values + napi_value* this_arg, // [out] Receives the JS 'this' arg for the call + void** data) { // [out] Receives the data pointer for the callback. + CHECK_ENV(env); + CHECK_ARG(env, cbinfo); + + v8impl::CallbackWrapper* info = + reinterpret_cast(cbinfo); + + if (argv != nullptr) { + CHECK_ARG(env, argc); + info->Args(argv, *argc); + } + if (argc != nullptr) { + *argc = info->ArgsLength(); + } + if (this_arg != nullptr) { + *this_arg = info->This(); + } + if (data != nullptr) { + *data = info->Data(); + } + + return napi_clear_last_error(env); +} + +napi_status napi_get_new_target(napi_env env, + napi_callback_info cbinfo, + napi_value* result) { + CHECK_ENV(env); + CHECK_ARG(env, cbinfo); + CHECK_ARG(env, result); + + v8impl::CallbackWrapper* info = + reinterpret_cast(cbinfo); + + *result = info->GetNewTarget(); + return napi_clear_last_error(env); +} + +napi_status napi_call_function(napi_env env, + napi_value recv, + napi_value func, + size_t argc, + const napi_value* argv, + napi_value* result) { + NAPI_PREAMBLE(env); + CHECK_ARG(env, recv); + if (argc > 0) { + CHECK_ARG(env, argv); + } + + v8::Local context = env->context(); + + v8::Local v8recv = v8impl::V8LocalValueFromJsValue(recv); + + v8::Local v8func; + CHECK_TO_FUNCTION(env, v8func, func); + + auto maybe = v8func->Call(context, v8recv, argc, + reinterpret_cast*>(const_cast(argv))); + + if (try_catch.HasCaught()) { + return napi_set_last_error(env, napi_pending_exception); + } else { + if (result != nullptr) { + CHECK_MAYBE_EMPTY(env, maybe, napi_generic_failure); + *result = v8impl::JsValueFromV8LocalValue(maybe.ToLocalChecked()); + } + return napi_clear_last_error(env); + } +} + +napi_status napi_get_global(napi_env env, napi_value* result) { + CHECK_ENV(env); + CHECK_ARG(env, result); + + *result = v8impl::JsValueFromV8LocalValue(env->context()->Global()); + + return napi_clear_last_error(env); +} + +napi_status napi_throw(napi_env env, napi_value error) { + NAPI_PREAMBLE(env); + CHECK_ARG(env, error); + + v8::Isolate* isolate = env->isolate; + + isolate->ThrowException(v8impl::V8LocalValueFromJsValue(error)); + // any VM calls after this point and before returning + // to the javascript invoker will fail + return napi_clear_last_error(env); +} + +napi_status napi_throw_error(napi_env env, + const char* code, + const char* msg) { + NAPI_PREAMBLE(env); + + v8::Isolate* isolate = env->isolate; + v8::Local str; + CHECK_NEW_FROM_UTF8(env, str, msg); + + v8::Local error_obj = v8::Exception::Error(str); + napi_status status = set_error_code(env, error_obj, nullptr, code); + if (status != napi_ok) return status; + + isolate->ThrowException(error_obj); + // any VM calls after this point and before returning + // to the javascript invoker will fail + return napi_clear_last_error(env); +} + +napi_status napi_throw_type_error(napi_env env, + const char* code, + const char* msg) { + NAPI_PREAMBLE(env); + + v8::Isolate* isolate = env->isolate; + v8::Local str; + CHECK_NEW_FROM_UTF8(env, str, msg); + + v8::Local error_obj = v8::Exception::TypeError(str); + napi_status status = set_error_code(env, error_obj, nullptr, code); + if (status != napi_ok) return status; + + isolate->ThrowException(error_obj); + // any VM calls after this point and before returning + // to the javascript invoker will fail + return napi_clear_last_error(env); +} + +napi_status napi_throw_range_error(napi_env env, + const char* code, + const char* msg) { + NAPI_PREAMBLE(env); + + v8::Isolate* isolate = env->isolate; + v8::Local str; + CHECK_NEW_FROM_UTF8(env, str, msg); + + v8::Local error_obj = v8::Exception::RangeError(str); + napi_status status = set_error_code(env, error_obj, nullptr, code); + if (status != napi_ok) return status; + + isolate->ThrowException(error_obj); + // any VM calls after this point and before returning + // to the javascript invoker will fail + return napi_clear_last_error(env); +} + +napi_status napi_is_error(napi_env env, napi_value value, bool* result) { + // Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot + // throw JS exceptions. + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, result); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + *result = val->IsNativeError(); + + return napi_clear_last_error(env); +} + +napi_status napi_get_value_double(napi_env env, + napi_value value, + double* result) { + // Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw + // JS exceptions. + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, result); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + RETURN_STATUS_IF_FALSE(env, val->IsNumber(), napi_number_expected); + + *result = val.As()->Value(); + + return napi_clear_last_error(env); +} + +napi_status napi_get_value_int32(napi_env env, + napi_value value, + int32_t* result) { + // Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw + // JS exceptions. + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, result); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + + if (val->IsInt32()) { + *result = val.As()->Value(); + } else { + RETURN_STATUS_IF_FALSE(env, val->IsNumber(), napi_number_expected); + + // Empty context: https://github.com/nodejs/node/issues/14379 + v8::Local context; + *result = val->Int32Value(context).FromJust(); + } + + return napi_clear_last_error(env); +} + +napi_status napi_get_value_uint32(napi_env env, + napi_value value, + uint32_t* result) { + // Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw + // JS exceptions. + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, result); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + + if (val->IsUint32()) { + *result = val.As()->Value(); + } else { + RETURN_STATUS_IF_FALSE(env, val->IsNumber(), napi_number_expected); + + // Empty context: https://github.com/nodejs/node/issues/14379 + v8::Local context; + *result = val->Uint32Value(context).FromJust(); + } + + return napi_clear_last_error(env); +} + +napi_status napi_get_value_int64(napi_env env, + napi_value value, + int64_t* result) { + // Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw + // JS exceptions. + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, result); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + + // This is still a fast path very likely to be taken. + if (val->IsInt32()) { + *result = val.As()->Value(); + return napi_clear_last_error(env); + } + + RETURN_STATUS_IF_FALSE(env, val->IsNumber(), napi_number_expected); + + // v8::Value::IntegerValue() converts NaN, +Inf, and -Inf to INT64_MIN, + // inconsistent with v8::Value::Int32Value() which converts those values to 0. + // Special-case all non-finite values to match that behavior. + double doubleValue = val.As()->Value(); + if (std::isfinite(doubleValue)) { + // Empty context: https://github.com/nodejs/node/issues/14379 + v8::Local context; + *result = val->IntegerValue(context).FromJust(); + } else { + *result = 0; + } + + return napi_clear_last_error(env); +} + +napi_status napi_get_value_bigint_int64(napi_env env, + napi_value value, + int64_t* result, + bool* lossless) { + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, result); + CHECK_ARG(env, lossless); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + + RETURN_STATUS_IF_FALSE(env, val->IsBigInt(), napi_bigint_expected); + + *result = val.As()->Int64Value(lossless); + + return napi_clear_last_error(env); +} + +napi_status napi_get_value_bigint_uint64(napi_env env, + napi_value value, + uint64_t* result, + bool* lossless) { + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, result); + CHECK_ARG(env, lossless); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + + RETURN_STATUS_IF_FALSE(env, val->IsBigInt(), napi_bigint_expected); + + *result = val.As()->Uint64Value(lossless); + + return napi_clear_last_error(env); +} + +napi_status napi_get_value_bigint_words(napi_env env, + napi_value value, + int* sign_bit, + size_t* word_count, + uint64_t* words) { + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, word_count); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + + RETURN_STATUS_IF_FALSE(env, val->IsBigInt(), napi_bigint_expected); + + v8::Local big = val.As(); + + int word_count_int = *word_count; + + if (sign_bit == nullptr && words == nullptr) { + word_count_int = big->WordCount(); + } else { + CHECK_ARG(env, sign_bit); + CHECK_ARG(env, words); + big->ToWordsArray(sign_bit, &word_count_int, words); + } + + *word_count = word_count_int; + + return napi_clear_last_error(env); +} + +napi_status napi_get_value_bool(napi_env env, napi_value value, bool* result) { + // Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw + // JS exceptions. + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, result); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + RETURN_STATUS_IF_FALSE(env, val->IsBoolean(), napi_boolean_expected); + + *result = val.As()->Value(); + + return napi_clear_last_error(env); +} + +// Copies a JavaScript string into a LATIN-1 string buffer. The result is the +// number of bytes (excluding the null terminator) copied into buf. +// A sufficient buffer size should be greater than the length of string, +// reserving space for null terminator. +// If bufsize is insufficient, the string will be truncated and null terminated. +// If buf is NULL, this method returns the length of the string (in bytes) +// via the result parameter. +// The result argument is optional unless buf is NULL. +napi_status napi_get_value_string_latin1(napi_env env, + napi_value value, + char* buf, + size_t bufsize, + size_t* result) { + CHECK_ENV(env); + CHECK_ARG(env, value); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + RETURN_STATUS_IF_FALSE(env, val->IsString(), napi_string_expected); + + if (!buf) { + CHECK_ARG(env, result); + *result = val.As()->Length(); + } else { + int copied = + val.As()->WriteOneByte(env->isolate, + reinterpret_cast(buf), + 0, + bufsize - 1, + v8::String::NO_NULL_TERMINATION); + + buf[copied] = '\0'; + if (result != nullptr) { + *result = copied; + } + } + + return napi_clear_last_error(env); +} + +// Copies a JavaScript string into a UTF-8 string buffer. The result is the +// number of bytes (excluding the null terminator) copied into buf. +// A sufficient buffer size should be greater than the length of string, +// reserving space for null terminator. +// If bufsize is insufficient, the string will be truncated and null terminated. +// If buf is NULL, this method returns the length of the string (in bytes) +// via the result parameter. +// The result argument is optional unless buf is NULL. +napi_status napi_get_value_string_utf8(napi_env env, + napi_value value, + char* buf, + size_t bufsize, + size_t* result) { + CHECK_ENV(env); + CHECK_ARG(env, value); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + RETURN_STATUS_IF_FALSE(env, val->IsString(), napi_string_expected); + + if (!buf) { + CHECK_ARG(env, result); + *result = val.As()->Utf8Length(env->isolate); + } else { + int copied = val.As()->WriteUtf8( + env->isolate, + buf, + bufsize - 1, + nullptr, + v8::String::REPLACE_INVALID_UTF8 | v8::String::NO_NULL_TERMINATION); + + buf[copied] = '\0'; + if (result != nullptr) { + *result = copied; + } + } + + return napi_clear_last_error(env); +} + +// Copies a JavaScript string into a UTF-16 string buffer. The result is the +// number of 2-byte code units (excluding the null terminator) copied into buf. +// A sufficient buffer size should be greater than the length of string, +// reserving space for null terminator. +// If bufsize is insufficient, the string will be truncated and null terminated. +// If buf is NULL, this method returns the length of the string (in 2-byte +// code units) via the result parameter. +// The result argument is optional unless buf is NULL. +napi_status napi_get_value_string_utf16(napi_env env, + napi_value value, + char16_t* buf, + size_t bufsize, + size_t* result) { + CHECK_ENV(env); + CHECK_ARG(env, value); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + RETURN_STATUS_IF_FALSE(env, val->IsString(), napi_string_expected); + + if (!buf) { + CHECK_ARG(env, result); + // V8 assumes UTF-16 length is the same as the number of characters. + *result = val.As()->Length(); + } else { + int copied = val.As()->Write(env->isolate, + reinterpret_cast(buf), + 0, + bufsize - 1, + v8::String::NO_NULL_TERMINATION); + + buf[copied] = '\0'; + if (result != nullptr) { + *result = copied; + } + } + + return napi_clear_last_error(env); +} + +napi_status napi_coerce_to_object(napi_env env, + napi_value value, + napi_value* result) { + NAPI_PREAMBLE(env); + CHECK_ARG(env, value); + CHECK_ARG(env, result); + + v8::Local context = env->context(); + v8::Local obj; + CHECK_TO_OBJECT(env, context, obj, value); + + *result = v8impl::JsValueFromV8LocalValue(obj); + return GET_RETURN_STATUS(env); +} + +napi_status napi_coerce_to_bool(napi_env env, + napi_value value, + napi_value* result) { + NAPI_PREAMBLE(env); + CHECK_ARG(env, value); + CHECK_ARG(env, result); + + v8::Local context = env->context(); + v8::Local b; + + CHECK_TO_BOOL(env, context, b, value); + + *result = v8impl::JsValueFromV8LocalValue(b); + return GET_RETURN_STATUS(env); +} + +napi_status napi_coerce_to_number(napi_env env, + napi_value value, + napi_value* result) { + NAPI_PREAMBLE(env); + CHECK_ARG(env, value); + CHECK_ARG(env, result); + + v8::Local context = env->context(); + v8::Local num; + + CHECK_TO_NUMBER(env, context, num, value); + + *result = v8impl::JsValueFromV8LocalValue(num); + return GET_RETURN_STATUS(env); +} + +napi_status napi_coerce_to_string(napi_env env, + napi_value value, + napi_value* result) { + NAPI_PREAMBLE(env); + CHECK_ARG(env, value); + CHECK_ARG(env, result); + + v8::Local context = env->context(); + v8::Local str; + + CHECK_TO_STRING(env, context, str, value); + + *result = v8impl::JsValueFromV8LocalValue(str); + return GET_RETURN_STATUS(env); +} + +napi_status napi_wrap(napi_env env, + napi_value js_object, + void* native_object, + napi_finalize finalize_cb, + void* finalize_hint, + napi_ref* result) { + return v8impl::Wrap(env, + js_object, + native_object, + finalize_cb, + finalize_hint, + result); +} + +napi_status napi_unwrap(napi_env env, napi_value obj, void** result) { + return v8impl::Unwrap(env, obj, result, v8impl::KeepWrap); +} + +napi_status napi_remove_wrap(napi_env env, napi_value obj, void** result) { + return v8impl::Unwrap(env, obj, result, v8impl::RemoveWrap); +} + +napi_status napi_create_external(napi_env env, + void* data, + napi_finalize finalize_cb, + void* finalize_hint, + napi_value* result) { + NAPI_PREAMBLE(env); + CHECK_ARG(env, result); + + v8::Isolate* isolate = env->isolate; + + v8::Local external_value = v8::External::New(isolate, data); + + // The Reference object will delete itself after invoking the finalizer + // callback. + v8impl::Reference::New(env, + external_value, + 0, + true, + finalize_cb, + data, + finalize_hint); + + *result = v8impl::JsValueFromV8LocalValue(external_value); + + return napi_clear_last_error(env); +} + +napi_status napi_get_value_external(napi_env env, + napi_value value, + void** result) { + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, result); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + RETURN_STATUS_IF_FALSE(env, val->IsExternal(), napi_invalid_arg); + + v8::Local external_value = val.As(); + *result = external_value->Value(); + + return napi_clear_last_error(env); +} + +// Set initial_refcount to 0 for a weak reference, >0 for a strong reference. +napi_status napi_create_reference(napi_env env, + napi_value value, + uint32_t initial_refcount, + napi_ref* result) { + // Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw + // JS exceptions. + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, result); + + v8::Local v8_value = v8impl::V8LocalValueFromJsValue(value); + + if (!(v8_value->IsObject() || v8_value->IsFunction())) { + return napi_set_last_error(env, napi_object_expected); + } + + v8impl::Reference* reference = + v8impl::Reference::New(env, v8_value, initial_refcount, false); + + *result = reinterpret_cast(reference); + return napi_clear_last_error(env); +} + +// Deletes a reference. The referenced value is released, and may be GC'd unless +// there are other references to it. +napi_status napi_delete_reference(napi_env env, napi_ref ref) { + // Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw + // JS exceptions. + CHECK_ENV(env); + CHECK_ARG(env, ref); + + v8impl::Reference::Delete(reinterpret_cast(ref)); + + return napi_clear_last_error(env); +} + +// Increments the reference count, optionally returning the resulting count. +// After this call the reference will be a strong reference because its +// refcount is >0, and the referenced object is effectively "pinned". +// Calling this when the refcount is 0 and the object is unavailable +// results in an error. +napi_status napi_reference_ref(napi_env env, napi_ref ref, uint32_t* result) { + // Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw + // JS exceptions. + CHECK_ENV(env); + CHECK_ARG(env, ref); + + v8impl::Reference* reference = reinterpret_cast(ref); + uint32_t count = reference->Ref(); + + if (result != nullptr) { + *result = count; + } + + return napi_clear_last_error(env); +} + +// Decrements the reference count, optionally returning the resulting count. If +// the result is 0 the reference is now weak and the object may be GC'd at any +// time if there are no other references. Calling this when the refcount is +// already 0 results in an error. +napi_status napi_reference_unref(napi_env env, napi_ref ref, uint32_t* result) { + // Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw + // JS exceptions. + CHECK_ENV(env); + CHECK_ARG(env, ref); + + v8impl::Reference* reference = reinterpret_cast(ref); + + if (reference->RefCount() == 0) { + return napi_set_last_error(env, napi_generic_failure); + } + + uint32_t count = reference->Unref(); + + if (result != nullptr) { + *result = count; + } + + return napi_clear_last_error(env); +} + +// Attempts to get a referenced value. If the reference is weak, the value might +// no longer be available, in that case the call is still successful but the +// result is NULL. +napi_status napi_get_reference_value(napi_env env, + napi_ref ref, + napi_value* result) { + // Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw + // JS exceptions. + CHECK_ENV(env); + CHECK_ARG(env, ref); + CHECK_ARG(env, result); + + v8impl::Reference* reference = reinterpret_cast(ref); + *result = v8impl::JsValueFromV8LocalValue(reference->Get()); + + return napi_clear_last_error(env); +} + +napi_status napi_open_handle_scope(napi_env env, napi_handle_scope* result) { + // Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw + // JS exceptions. + CHECK_ENV(env); + CHECK_ARG(env, result); + + *result = v8impl::JsHandleScopeFromV8HandleScope( + new v8impl::HandleScopeWrapper(env->isolate)); + env->open_handle_scopes++; + return napi_clear_last_error(env); +} + +napi_status napi_close_handle_scope(napi_env env, napi_handle_scope scope) { + // Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw + // JS exceptions. + CHECK_ENV(env); + CHECK_ARG(env, scope); + if (env->open_handle_scopes == 0) { + return napi_handle_scope_mismatch; + } + + env->open_handle_scopes--; + delete v8impl::V8HandleScopeFromJsHandleScope(scope); + return napi_clear_last_error(env); +} + +napi_status napi_open_escapable_handle_scope( + napi_env env, + napi_escapable_handle_scope* result) { + // Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw + // JS exceptions. + CHECK_ENV(env); + CHECK_ARG(env, result); + + *result = v8impl::JsEscapableHandleScopeFromV8EscapableHandleScope( + new v8impl::EscapableHandleScopeWrapper(env->isolate)); + env->open_handle_scopes++; + return napi_clear_last_error(env); +} + +napi_status napi_close_escapable_handle_scope( + napi_env env, + napi_escapable_handle_scope scope) { + // Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw + // JS exceptions. + CHECK_ENV(env); + CHECK_ARG(env, scope); + if (env->open_handle_scopes == 0) { + return napi_handle_scope_mismatch; + } + + delete v8impl::V8EscapableHandleScopeFromJsEscapableHandleScope(scope); + env->open_handle_scopes--; + return napi_clear_last_error(env); +} + +napi_status napi_escape_handle(napi_env env, + napi_escapable_handle_scope scope, + napi_value escapee, + napi_value* result) { + // Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw + // JS exceptions. + CHECK_ENV(env); + CHECK_ARG(env, scope); + CHECK_ARG(env, escapee); + CHECK_ARG(env, result); + + v8impl::EscapableHandleScopeWrapper* s = + v8impl::V8EscapableHandleScopeFromJsEscapableHandleScope(scope); + if (!s->escape_called()) { + *result = v8impl::JsValueFromV8LocalValue( + s->Escape(v8impl::V8LocalValueFromJsValue(escapee))); + return napi_clear_last_error(env); + } + return napi_set_last_error(env, napi_escape_called_twice); +} + +napi_status napi_new_instance(napi_env env, + napi_value constructor, + size_t argc, + const napi_value* argv, + napi_value* result) { + NAPI_PREAMBLE(env); + CHECK_ARG(env, constructor); + if (argc > 0) { + CHECK_ARG(env, argv); + } + CHECK_ARG(env, result); + + v8::Local context = env->context(); + + v8::Local ctor; + CHECK_TO_FUNCTION(env, ctor, constructor); + + auto maybe = ctor->NewInstance(context, argc, + reinterpret_cast*>(const_cast(argv))); + + CHECK_MAYBE_EMPTY(env, maybe, napi_generic_failure); + + *result = v8impl::JsValueFromV8LocalValue(maybe.ToLocalChecked()); + return GET_RETURN_STATUS(env); +} + +napi_status napi_instanceof(napi_env env, + napi_value object, + napi_value constructor, + bool* result) { + NAPI_PREAMBLE(env); + CHECK_ARG(env, object); + CHECK_ARG(env, result); + + *result = false; + + v8::Local ctor; + v8::Local context = env->context(); + + CHECK_TO_OBJECT(env, context, ctor, constructor); + + if (!ctor->IsFunction()) { + napi_throw_type_error(env, + "ERR_NAPI_CONS_FUNCTION", + "Constructor must be a function"); + + return napi_set_last_error(env, napi_function_expected); + } + + napi_status status = napi_generic_failure; + + v8::Local val = v8impl::V8LocalValueFromJsValue(object); + auto maybe_result = val->InstanceOf(context, ctor); + CHECK_MAYBE_NOTHING(env, maybe_result, status); + *result = maybe_result.FromJust(); + return GET_RETURN_STATUS(env); +} + +// Methods to support catching exceptions +napi_status napi_is_exception_pending(napi_env env, bool* result) { + // NAPI_PREAMBLE is not used here: this function must execute when there is a + // pending exception. + CHECK_ENV(env); + CHECK_ARG(env, result); + + *result = !env->last_exception.IsEmpty(); + return napi_clear_last_error(env); +} + +napi_status napi_get_and_clear_last_exception(napi_env env, + napi_value* result) { + // NAPI_PREAMBLE is not used here: this function must execute when there is a + // pending exception. + CHECK_ENV(env); + CHECK_ARG(env, result); + + if (env->last_exception.IsEmpty()) { + return napi_get_undefined(env, result); + } else { + *result = v8impl::JsValueFromV8LocalValue( + v8::Local::New(env->isolate, env->last_exception)); + env->last_exception.Reset(); + } + + return napi_clear_last_error(env); +} + +napi_status napi_is_arraybuffer(napi_env env, napi_value value, bool* result) { + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, result); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + *result = val->IsArrayBuffer(); + + return napi_clear_last_error(env); +} + +napi_status napi_create_arraybuffer(napi_env env, + size_t byte_length, + void** data, + napi_value* result) { + NAPI_PREAMBLE(env); + CHECK_ARG(env, result); + + v8::Isolate* isolate = env->isolate; + v8::Local buffer = + v8::ArrayBuffer::New(isolate, byte_length); + + // Optionally return a pointer to the buffer's data, to avoid another call to + // retrieve it. + if (data != nullptr) { + *data = buffer->GetContents().Data(); + } + + *result = v8impl::JsValueFromV8LocalValue(buffer); + return GET_RETURN_STATUS(env); +} + +napi_status napi_create_external_arraybuffer(napi_env env, + void* external_data, + size_t byte_length, + napi_finalize finalize_cb, + void* finalize_hint, + napi_value* result) { + NAPI_PREAMBLE(env); + CHECK_ARG(env, result); + + v8::Isolate* isolate = env->isolate; + v8::Local buffer = + v8::ArrayBuffer::New(isolate, external_data, byte_length); + + if (finalize_cb != nullptr) { + // Create a self-deleting weak reference that invokes the finalizer + // callback. + v8impl::Reference::New(env, + buffer, + 0, + true, + finalize_cb, + external_data, + finalize_hint); + } + + *result = v8impl::JsValueFromV8LocalValue(buffer); + return GET_RETURN_STATUS(env); +} + +napi_status napi_get_arraybuffer_info(napi_env env, + napi_value arraybuffer, + void** data, + size_t* byte_length) { + CHECK_ENV(env); + CHECK_ARG(env, arraybuffer); + + v8::Local value = v8impl::V8LocalValueFromJsValue(arraybuffer); + RETURN_STATUS_IF_FALSE(env, value->IsArrayBuffer(), napi_invalid_arg); + + v8::ArrayBuffer::Contents contents = + value.As()->GetContents(); + + if (data != nullptr) { + *data = contents.Data(); + } + + if (byte_length != nullptr) { + *byte_length = contents.ByteLength(); + } + + return napi_clear_last_error(env); +} + +napi_status napi_is_typedarray(napi_env env, napi_value value, bool* result) { + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, result); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + *result = val->IsTypedArray(); + + return napi_clear_last_error(env); +} + +napi_status napi_create_typedarray(napi_env env, + napi_typedarray_type type, + size_t length, + napi_value arraybuffer, + size_t byte_offset, + napi_value* result) { + NAPI_PREAMBLE(env); + CHECK_ARG(env, arraybuffer); + CHECK_ARG(env, result); + + v8::Local value = v8impl::V8LocalValueFromJsValue(arraybuffer); + RETURN_STATUS_IF_FALSE(env, value->IsArrayBuffer(), napi_invalid_arg); + + v8::Local buffer = value.As(); + v8::Local typedArray; + + switch (type) { + case napi_int8_array: + CREATE_TYPED_ARRAY( + env, Int8Array, 1, buffer, byte_offset, length, typedArray); + break; + case napi_uint8_array: + CREATE_TYPED_ARRAY( + env, Uint8Array, 1, buffer, byte_offset, length, typedArray); + break; + case napi_uint8_clamped_array: + CREATE_TYPED_ARRAY( + env, Uint8ClampedArray, 1, buffer, byte_offset, length, typedArray); + break; + case napi_int16_array: + CREATE_TYPED_ARRAY( + env, Int16Array, 2, buffer, byte_offset, length, typedArray); + break; + case napi_uint16_array: + CREATE_TYPED_ARRAY( + env, Uint16Array, 2, buffer, byte_offset, length, typedArray); + break; + case napi_int32_array: + CREATE_TYPED_ARRAY( + env, Int32Array, 4, buffer, byte_offset, length, typedArray); + break; + case napi_uint32_array: + CREATE_TYPED_ARRAY( + env, Uint32Array, 4, buffer, byte_offset, length, typedArray); + break; + case napi_float32_array: + CREATE_TYPED_ARRAY( + env, Float32Array, 4, buffer, byte_offset, length, typedArray); + break; + case napi_float64_array: + CREATE_TYPED_ARRAY( + env, Float64Array, 8, buffer, byte_offset, length, typedArray); + break; + case napi_bigint64_array: + CREATE_TYPED_ARRAY( + env, BigInt64Array, 8, buffer, byte_offset, length, typedArray); + break; + case napi_biguint64_array: + CREATE_TYPED_ARRAY( + env, BigUint64Array, 8, buffer, byte_offset, length, typedArray); + break; + default: + return napi_set_last_error(env, napi_invalid_arg); + } + + *result = v8impl::JsValueFromV8LocalValue(typedArray); + return GET_RETURN_STATUS(env); +} + +napi_status napi_get_typedarray_info(napi_env env, + napi_value typedarray, + napi_typedarray_type* type, + size_t* length, + void** data, + napi_value* arraybuffer, + size_t* byte_offset) { + CHECK_ENV(env); + CHECK_ARG(env, typedarray); + + v8::Local value = v8impl::V8LocalValueFromJsValue(typedarray); + RETURN_STATUS_IF_FALSE(env, value->IsTypedArray(), napi_invalid_arg); + + v8::Local array = value.As(); + + if (type != nullptr) { + if (value->IsInt8Array()) { + *type = napi_int8_array; + } else if (value->IsUint8Array()) { + *type = napi_uint8_array; + } else if (value->IsUint8ClampedArray()) { + *type = napi_uint8_clamped_array; + } else if (value->IsInt16Array()) { + *type = napi_int16_array; + } else if (value->IsUint16Array()) { + *type = napi_uint16_array; + } else if (value->IsInt32Array()) { + *type = napi_int32_array; + } else if (value->IsUint32Array()) { + *type = napi_uint32_array; + } else if (value->IsFloat32Array()) { + *type = napi_float32_array; + } else if (value->IsFloat64Array()) { + *type = napi_float64_array; + } else if (value->IsBigInt64Array()) { + *type = napi_bigint64_array; + } else if (value->IsBigUint64Array()) { + *type = napi_biguint64_array; + } + } + + if (length != nullptr) { + *length = array->Length(); + } + + v8::Local buffer = array->Buffer(); + if (data != nullptr) { + *data = static_cast(buffer->GetContents().Data()) + + array->ByteOffset(); + } + + if (arraybuffer != nullptr) { + *arraybuffer = v8impl::JsValueFromV8LocalValue(buffer); + } + + if (byte_offset != nullptr) { + *byte_offset = array->ByteOffset(); + } + + return napi_clear_last_error(env); +} + +napi_status napi_create_dataview(napi_env env, + size_t byte_length, + napi_value arraybuffer, + size_t byte_offset, + napi_value* result) { + NAPI_PREAMBLE(env); + CHECK_ARG(env, arraybuffer); + CHECK_ARG(env, result); + + v8::Local value = v8impl::V8LocalValueFromJsValue(arraybuffer); + RETURN_STATUS_IF_FALSE(env, value->IsArrayBuffer(), napi_invalid_arg); + + v8::Local buffer = value.As(); + if (byte_length + byte_offset > buffer->ByteLength()) { + napi_throw_range_error( + env, + "ERR_NAPI_INVALID_DATAVIEW_ARGS", + "byte_offset + byte_length should be less than or " + "equal to the size in bytes of the array passed in"); + return napi_set_last_error(env, napi_pending_exception); + } + v8::Local DataView = v8::DataView::New(buffer, byte_offset, + byte_length); + + *result = v8impl::JsValueFromV8LocalValue(DataView); + return GET_RETURN_STATUS(env); +} + +napi_status napi_is_dataview(napi_env env, napi_value value, bool* result) { + CHECK_ENV(env); + CHECK_ARG(env, value); + CHECK_ARG(env, result); + + v8::Local val = v8impl::V8LocalValueFromJsValue(value); + *result = val->IsDataView(); + + return napi_clear_last_error(env); +} + +napi_status napi_get_dataview_info(napi_env env, + napi_value dataview, + size_t* byte_length, + void** data, + napi_value* arraybuffer, + size_t* byte_offset) { + CHECK_ENV(env); + CHECK_ARG(env, dataview); + + v8::Local value = v8impl::V8LocalValueFromJsValue(dataview); + RETURN_STATUS_IF_FALSE(env, value->IsDataView(), napi_invalid_arg); + + v8::Local array = value.As(); + + if (byte_length != nullptr) { + *byte_length = array->ByteLength(); + } + + v8::Local buffer = array->Buffer(); + if (data != nullptr) { + *data = static_cast(buffer->GetContents().Data()) + + array->ByteOffset(); + } + + if (arraybuffer != nullptr) { + *arraybuffer = v8impl::JsValueFromV8LocalValue(buffer); + } + + if (byte_offset != nullptr) { + *byte_offset = array->ByteOffset(); + } + + return napi_clear_last_error(env); +} + +napi_status napi_get_version(napi_env env, uint32_t* result) { + CHECK_ENV(env); + CHECK_ARG(env, result); + *result = NAPI_VERSION; + return napi_clear_last_error(env); +} + +napi_status napi_create_promise(napi_env env, + napi_deferred* deferred, + napi_value* promise) { + NAPI_PREAMBLE(env); + CHECK_ARG(env, deferred); + CHECK_ARG(env, promise); + + auto maybe = v8::Promise::Resolver::New(env->context()); + CHECK_MAYBE_EMPTY(env, maybe, napi_generic_failure); + + auto v8_resolver = maybe.ToLocalChecked(); + auto v8_deferred = new v8impl::Persistent(); + v8_deferred->Reset(env->isolate, v8_resolver); + + *deferred = v8impl::JsDeferredFromNodePersistent(v8_deferred); + *promise = v8impl::JsValueFromV8LocalValue(v8_resolver->GetPromise()); + return GET_RETURN_STATUS(env); +} + +napi_status napi_resolve_deferred(napi_env env, + napi_deferred deferred, + napi_value resolution) { + return v8impl::ConcludeDeferred(env, deferred, resolution, true); +} + +napi_status napi_reject_deferred(napi_env env, + napi_deferred deferred, + napi_value resolution) { + return v8impl::ConcludeDeferred(env, deferred, resolution, false); +} + +napi_status napi_is_promise(napi_env env, + napi_value promise, + bool* is_promise) { + CHECK_ENV(env); + CHECK_ARG(env, promise); + CHECK_ARG(env, is_promise); + + *is_promise = v8impl::V8LocalValueFromJsValue(promise)->IsPromise(); + + return napi_clear_last_error(env); +} + +napi_status napi_run_script(napi_env env, + napi_value script, + const char* sourceUrl, + napi_value* result) { + NAPI_PREAMBLE(env); + CHECK_ARG(env, script); + CHECK_ARG(env, result); + + v8::Local v8_script = v8impl::V8LocalValueFromJsValue(script); + + if (!v8_script->IsString()) { + return napi_set_last_error(env, napi_string_expected); + } + + v8::Local context = env->context(); + + // $TODO: pass in sourceUrl + auto maybe_script = v8::Script::Compile(context, + v8::Local::Cast(v8_script)); + CHECK_MAYBE_EMPTY(env, maybe_script, napi_generic_failure); + + auto script_result = + maybe_script.ToLocalChecked()->Run(context); + CHECK_MAYBE_EMPTY(env, script_result, napi_generic_failure); + + *result = v8impl::JsValueFromV8LocalValue(script_result.ToLocalChecked()); + return GET_RETURN_STATUS(env); +} + +napi_status napi_add_finalizer(napi_env env, + napi_value js_object, + void* native_object, + napi_finalize finalize_cb, + void* finalize_hint, + napi_ref* result) { + return v8impl::Wrap(env, + js_object, + native_object, + finalize_cb, + finalize_hint, + result); +} + +napi_status napi_adjust_external_memory(napi_env env, + int64_t change_in_bytes, + int64_t* adjusted_value) { + CHECK_ENV(env); + CHECK_ARG(env, adjusted_value); + + *adjusted_value = env->isolate->AdjustAmountOfExternalAllocatedMemory( + change_in_bytes); + + return napi_clear_last_error(env); +} diff --git a/Source/Napi/js_native_api_v8.h b/Source/Napi/js_native_api_v8.h new file mode 100644 index 000000000..d5402845d --- /dev/null +++ b/Source/Napi/js_native_api_v8.h @@ -0,0 +1,202 @@ +#ifndef SRC_JS_NATIVE_API_V8_H_ +#define SRC_JS_NATIVE_API_V8_H_ + +#include +#include "js_native_api_types.h" +#include "js_native_api_v8_internals.h" + +struct napi_env__ { + explicit napi_env__(v8::Local context) + : isolate(context->GetIsolate()), + context_persistent(isolate, context) { + CHECK_EQ(isolate, context->GetIsolate()); + } + v8::Isolate* const isolate; // Shortcut for context()->GetIsolate() + v8impl::Persistent context_persistent; + + inline v8::Local context() const { + return v8impl::PersistentToLocal::Strong(context_persistent); + } + + inline void Ref() { refs++; } + inline void Unref() { if ( --refs == 0) delete this; } + + v8impl::Persistent last_exception; + napi_extended_error_info last_error; + int open_handle_scopes = 0; + int open_callback_scopes = 0; + int refs = 1; +}; + +static inline napi_status napi_clear_last_error(napi_env env) { + env->last_error.error_code = napi_ok; + + // TODO(boingoing): Should this be a callback? + env->last_error.engine_error_code = 0; + env->last_error.engine_reserved = nullptr; + return napi_ok; +} + +static inline +napi_status napi_set_last_error(napi_env env, napi_status error_code, + uint32_t engine_error_code = 0, + void* engine_reserved = nullptr) { + env->last_error.error_code = error_code; + env->last_error.engine_error_code = engine_error_code; + env->last_error.engine_reserved = engine_reserved; + return error_code; +} + +#define RETURN_STATUS_IF_FALSE(env, condition, status) \ + do { \ + if (!(condition)) { \ + return napi_set_last_error((env), (status)); \ + } \ + } while (0) + +#define CHECK_ENV(env) \ + do { \ + if ((env) == nullptr) { \ + return napi_invalid_arg; \ + } \ + } while (0) + +#define CHECK_ARG(env, arg) \ + RETURN_STATUS_IF_FALSE((env), ((arg) != nullptr), napi_invalid_arg) + +#define CHECK_MAYBE_EMPTY(env, maybe, status) \ + RETURN_STATUS_IF_FALSE((env), !((maybe).IsEmpty()), (status)) + +// NAPI_PREAMBLE is not wrapped in do..while: try_catch must have function scope +#define NAPI_PREAMBLE(env) \ + CHECK_ENV((env)); \ + RETURN_STATUS_IF_FALSE((env), (env)->last_exception.IsEmpty(), \ + napi_pending_exception); \ + napi_clear_last_error((env)); \ + v8impl::TryCatch try_catch((env)) + +#define CHECK_TO_TYPE(env, type, context, result, src, status) \ + do { \ + CHECK_ARG((env), (src)); \ + auto maybe = v8impl::V8LocalValueFromJsValue((src))->To##type((context)); \ + CHECK_MAYBE_EMPTY((env), maybe, (status)); \ + (result) = maybe.ToLocalChecked(); \ + } while (0) + +#define CHECK_TO_FUNCTION(env, result, src) \ + do { \ + CHECK_ARG((env), (src)); \ + v8::Local v8value = v8impl::V8LocalValueFromJsValue((src)); \ + RETURN_STATUS_IF_FALSE((env), v8value->IsFunction(), napi_invalid_arg); \ + (result) = v8value.As(); \ + } while (0) + +#define CHECK_TO_OBJECT(env, context, result, src) \ + CHECK_TO_TYPE((env), Object, (context), (result), (src), napi_object_expected) + +#define CHECK_TO_STRING(env, context, result, src) \ + CHECK_TO_TYPE((env), String, (context), (result), (src), napi_string_expected) + +#define GET_RETURN_STATUS(env) \ + (!try_catch.HasCaught() ? napi_ok \ + : napi_set_last_error((env), napi_pending_exception)) + +#define THROW_RANGE_ERROR_IF_FALSE(env, condition, error, message) \ + do { \ + if (!(condition)) { \ + napi_throw_range_error((env), (error), (message)); \ + return napi_set_last_error((env), napi_generic_failure); \ + } \ + } while (0) + +#define NAPI_CALL_INTO_MODULE(env, call, handle_exception) \ + do { \ + int open_handle_scopes = (env)->open_handle_scopes; \ + int open_callback_scopes = (env)->open_callback_scopes; \ + napi_clear_last_error((env)); \ + call; \ + CHECK_EQ((env)->open_handle_scopes, open_handle_scopes); \ + CHECK_EQ((env)->open_callback_scopes, open_callback_scopes); \ + if (!(env)->last_exception.IsEmpty()) { \ + handle_exception( \ + v8::Local::New((env)->isolate, (env)->last_exception)); \ + (env)->last_exception.Reset(); \ + } \ + } while (0) + +#define NAPI_CALL_INTO_MODULE_THROW(env, call) \ + NAPI_CALL_INTO_MODULE((env), call, (env)->isolate->ThrowException) + +namespace v8impl { + +//=== Conversion between V8 Handles and napi_value ======================== + +// This asserts v8::Local<> will always be implemented with a single +// pointer field so that we can pass it around as a void*. +static_assert(sizeof(v8::Local) == sizeof(napi_value), + "Cannot convert between v8::Local and napi_value"); + +inline napi_value JsValueFromV8LocalValue(v8::Local local) { + return reinterpret_cast(*local); +} + +inline v8::Local V8LocalValueFromJsValue(napi_value v) { + v8::Local local; + memcpy(&local, &v, sizeof(v)); + return local; +} + +// Adapter for napi_finalize callbacks. +class Finalizer { + protected: + Finalizer(napi_env env, + napi_finalize finalize_callback, + void* finalize_data, + void* finalize_hint) + : _env(env), + _finalize_callback(finalize_callback), + _finalize_data(finalize_data), + _finalize_hint(finalize_hint) { + } + + ~Finalizer() { + } + + public: + static Finalizer* New(napi_env env, + napi_finalize finalize_callback = nullptr, + void* finalize_data = nullptr, + void* finalize_hint = nullptr) { + return new Finalizer( + env, finalize_callback, finalize_data, finalize_hint); + } + + static void Delete(Finalizer* finalizer) { + delete finalizer; + } + + protected: + napi_env _env; + napi_finalize _finalize_callback; + void* _finalize_data; + void* _finalize_hint; +}; + +class TryCatch : public v8::TryCatch { + public: + explicit TryCatch(napi_env env) + : v8::TryCatch(env->isolate), _env(env) {} + + ~TryCatch() { + if (HasCaught()) { + _env->last_exception.Reset(_env->isolate, Exception()); + } + } + + private: + napi_env _env; +}; + +} // end of namespace v8impl + +#endif // SRC_JS_NATIVE_API_V8_H_ diff --git a/Source/Napi/js_native_api_v8_internals.h b/Source/Napi/js_native_api_v8_internals.h new file mode 100644 index 000000000..cf985ff59 --- /dev/null +++ b/Source/Napi/js_native_api_v8_internals.h @@ -0,0 +1,49 @@ +#ifndef SRC_JS_NATIVE_API_V8_INTERNALS_H_ +#define SRC_JS_NATIVE_API_V8_INTERNALS_H_ + +#include +#include + +#define NAPI_ARRAYSIZE(array) \ + (sizeof(array) / sizeof(array[0])) + +inline v8::Local OneByteString(v8::Isolate* isolate, + const char* data, + int length) { + return v8::String::NewFromOneByte(isolate, + reinterpret_cast(data), + v8::NewStringType::kNormal, + length).ToLocalChecked(); +} + +#define NAPI_FIXED_ONE_BYTE_STRING(isolate, string) \ + OneByteString((isolate), (string), sizeof(string) - 1) + +namespace v8impl { +template +using Persistent = v8::Persistent; + +class PersistentToLocal { +public: + template + static inline v8::Local Strong( + const Persistent& persistent) { + return *reinterpret_cast*>( + const_cast*>(&persistent)); + } +}; +} // end of namespace v8impl + +#ifndef CHECK +#define CHECK(expr) assert(expr) +#endif + +#ifndef CHECK_EQ +#define CHECK_EQ(a, b) CHECK((a) == (b)) +#endif + +#ifndef CHECK_LE +#define CHECK_LE(a, b) CHECK((a) <= (b)) +#endif + +#endif // SRC_JS_NATIVE_API_V8_INTERNALS_H_ diff --git a/Source/Napi/napi-inl.h b/Source/Napi/napi-inl.h new file mode 100644 index 000000000..6e510442a --- /dev/null +++ b/Source/Napi/napi-inl.h @@ -0,0 +1,3642 @@ +#ifndef SRC_NAPI_INL_H_ +#define SRC_NAPI_INL_H_ + +//////////////////////////////////////////////////////////////////////////////// +// N-API C++ Wrapper Classes +// +// Inline header-only implementations for "N-API" ABI-stable C APIs for Node.js. +//////////////////////////////////////////////////////////////////////////////// + +// Note: Do not include this file directly! Include "napi.h" instead. + +#include +#include + +namespace Napi { + +// Helpers to handle functions exposed from C++. +namespace details { + +#ifdef NAPI_CPP_EXCEPTIONS + +#define NAPI_THROW(e) throw e + +// When C++ exceptions are enabled, Errors are thrown directly. There is no need +// to return anything after the throw statement. The variadic parameter is an +// optional return value that is ignored. +#define NAPI_THROW_IF_FAILED(env, status, ...) \ + if ((status) != napi_ok) throw Error::New(env); + +#define NAPI_THROW_IF_FAILED_VOID(env, status) \ + if ((status) != napi_ok) throw Error::New(env); + +#else // NAPI_CPP_EXCEPTIONS + +#define NAPI_THROW(e) (e).ThrowAsJavaScriptException(); + +// When C++ exceptions are disabled, Errors are thrown as JavaScript exceptions, +// which are pending until the callback returns to JS. The variadic parameter +// is an optional return value; usually it is an empty result. +#define NAPI_THROW_IF_FAILED(env, status, ...) \ + if ((status) != napi_ok) { \ + Error::New(env).ThrowAsJavaScriptException(); \ + return __VA_ARGS__; \ + } + +// We need a _VOID version of this macro to avoid warnings resulting from +// leaving the NAPI_THROW_IF_FAILED `...` argument empty. +#define NAPI_THROW_IF_FAILED_VOID(env, status) \ + if ((status) != napi_ok) { \ + Error::New(env).ThrowAsJavaScriptException(); \ + return; \ + } + +#endif // NAPI_CPP_EXCEPTIONS + +#define NAPI_FATAL_IF_FAILED(status, location, message) \ + do { \ + if ((status) != napi_ok) { \ + Error::Fatal((location), (message)); \ + } \ + } while (0) + +// Attach a data item to an object and delete it when the object gets +// garbage-collected. +// TODO: Replace this code with `napi_add_finalizer()` whenever it becomes +// available on all supported versions of Node.js. +template +static inline napi_status AttachData(napi_env env, + napi_value obj, + FreeType* data) { + napi_value symbol, external; + napi_status status = napi_create_symbol(env, nullptr, &symbol); + if (status == napi_ok) { + status = napi_create_external(env, + data, + [](napi_env /*env*/, void* data, void* /*hint*/) { + delete static_cast(data); + }, + nullptr, + &external); + if (status == napi_ok) { + napi_property_descriptor desc = { + nullptr, + symbol, + nullptr, + nullptr, + nullptr, + external, + napi_default, + nullptr + }; + status = napi_define_properties(env, obj, 1, &desc); + } + } + return status; +} + +// For use in JS to C++ callback wrappers to catch any Napi::Error exceptions +// and rethrow them as JavaScript exceptions before returning from the callback. +template +inline napi_value WrapCallback(Callable callback) { +#ifdef NAPI_CPP_EXCEPTIONS + try { + return callback(); + } catch (const Error& e) { + e.ThrowAsJavaScriptException(); + return nullptr; + } +#else // NAPI_CPP_EXCEPTIONS + // When C++ exceptions are disabled, errors are immediately thrown as JS + // exceptions, so there is no need to catch and rethrow them here. + return callback(); +#endif // NAPI_CPP_EXCEPTIONS +} + +template +struct CallbackData { + static inline + napi_value Wrapper(napi_env env, napi_callback_info info) { + return details::WrapCallback([&] { + CallbackInfo callbackInfo(env, info); + CallbackData* callbackData = + static_cast(callbackInfo.Data()); + callbackInfo.SetData(callbackData->data); + return callbackData->callback(callbackInfo); + }); + } + + Callable callback; + void* data; +}; + +template +struct CallbackData { + static inline + napi_value Wrapper(napi_env env, napi_callback_info info) { + return details::WrapCallback([&] { + CallbackInfo callbackInfo(env, info); + CallbackData* callbackData = + static_cast(callbackInfo.Data()); + callbackInfo.SetData(callbackData->data); + callbackData->callback(callbackInfo); + return nullptr; + }); + } + + Callable callback; + void* data; +}; + +template +struct FinalizeData { + static inline + void Wrapper(napi_env env, void* data, void* finalizeHint) { + FinalizeData* finalizeData = static_cast(finalizeHint); + finalizeData->callback(Env(env), static_cast(data)); + delete finalizeData; + } + + static inline + void WrapperWithHint(napi_env env, void* data, void* finalizeHint) { + FinalizeData* finalizeData = static_cast(finalizeHint); + finalizeData->callback(Env(env), static_cast(data), finalizeData->hint); + delete finalizeData; + } + + Finalizer callback; + Hint* hint; +}; + +template +struct AccessorCallbackData { + static inline + napi_value GetterWrapper(napi_env env, napi_callback_info info) { + return details::WrapCallback([&] { + CallbackInfo callbackInfo(env, info); + AccessorCallbackData* callbackData = + static_cast(callbackInfo.Data()); + return callbackData->getterCallback(callbackInfo); + }); + } + + static inline + napi_value SetterWrapper(napi_env env, napi_callback_info info) { + return details::WrapCallback([&] { + CallbackInfo callbackInfo(env, info); + AccessorCallbackData* callbackData = + static_cast(callbackInfo.Data()); + callbackData->setterCallback(callbackInfo); + return nullptr; + }); + } + + Getter getterCallback; + Setter setterCallback; +}; + +} // namespace details + +#ifndef NODE_ADDON_API_DISABLE_DEPRECATED +# include "napi-inl.deprecated.h" +#endif // !NODE_ADDON_API_DISABLE_DEPRECATED + +//////////////////////////////////////////////////////////////////////////////// +// Module registration +//////////////////////////////////////////////////////////////////////////////// + +#define NODE_API_MODULE(modname, regfunc) \ + napi_value __napi_ ## regfunc(napi_env env, \ + napi_value exports) { \ + return Napi::RegisterModule(env, exports, regfunc); \ + } \ + NAPI_MODULE(modname, __napi_ ## regfunc) + +// Adapt the NAPI_MODULE registration function: +// - Wrap the arguments in NAPI wrappers. +// - Catch any NAPI errors and rethrow as JS exceptions. +inline napi_value RegisterModule(napi_env env, + napi_value exports, + ModuleRegisterCallback registerCallback) { + return details::WrapCallback([&] { + return napi_value(registerCallback(Napi::Env(env), + Napi::Object(env, exports))); + }); +} + +//////////////////////////////////////////////////////////////////////////////// +// Env class +//////////////////////////////////////////////////////////////////////////////// + +inline Env::Env(napi_env env) : _env(env) { +} + +inline Env::operator napi_env() const { + return _env; +} + +inline Object Env::Global() const { + napi_value value; + napi_status status = napi_get_global(*this, &value); + NAPI_THROW_IF_FAILED(*this, status, Object()); + return Object(*this, value); +} + +inline Value Env::Undefined() const { + napi_value value; + napi_status status = napi_get_undefined(*this, &value); + NAPI_THROW_IF_FAILED(*this, status, Value()); + return Value(*this, value); +} + +inline Value Env::Null() const { + napi_value value; + napi_status status = napi_get_null(*this, &value); + NAPI_THROW_IF_FAILED(*this, status, Value()); + return Value(*this, value); +} + +inline bool Env::IsExceptionPending() const { + bool result; + napi_status status = napi_is_exception_pending(_env, &result); + if (status != napi_ok) result = false; // Checking for a pending exception shouldn't throw. + return result; +} + +inline Error Env::GetAndClearPendingException() { + napi_value value; + napi_status status = napi_get_and_clear_last_exception(_env, &value); + if (status != napi_ok) { + // Don't throw another exception when failing to get the exception! + return Error(); + } + return Error(_env, value); +} + +//////////////////////////////////////////////////////////////////////////////// +// Value class +//////////////////////////////////////////////////////////////////////////////// + +inline Value::Value() : _env(nullptr), _value(nullptr) { +} + +inline Value::Value(napi_env env, napi_value value) : _env(env), _value(value) { +} + +inline Value::operator napi_value() const { + return _value; +} + +inline bool Value::operator ==(const Value& other) const { + return StrictEquals(other); +} + +inline bool Value::operator !=(const Value& other) const { + return !this->operator ==(other); +} + +inline bool Value::StrictEquals(const Value& other) const { + bool result; + napi_status status = napi_strict_equals(_env, *this, other, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +inline Napi::Env Value::Env() const { + return Napi::Env(_env); +} + +inline bool Value::IsEmpty() const { + return _value == nullptr; +} + +inline napi_valuetype Value::Type() const { + if (_value == nullptr) { + return napi_undefined; + } + + napi_valuetype type; + napi_status status = napi_typeof(_env, _value, &type); + NAPI_THROW_IF_FAILED(_env, status, napi_undefined); + return type; +} + +inline bool Value::IsUndefined() const { + return Type() == napi_undefined; +} + +inline bool Value::IsNull() const { + return Type() == napi_null; +} + +inline bool Value::IsBoolean() const { + return Type() == napi_boolean; +} + +inline bool Value::IsNumber() const { + return Type() == napi_number; +} + +// currently experimental guard with version of NAPI_VERSION that it is +// released in once it is no longer experimental +#if (NAPI_VERSION > 2147483646) +inline bool Value::IsBigInt() const { + return Type() == napi_bigint; +} +#endif // NAPI_EXPERIMENTAL + +inline bool Value::IsString() const { + return Type() == napi_string; +} + +inline bool Value::IsSymbol() const { + return Type() == napi_symbol; +} + +inline bool Value::IsArray() const { + if (_value == nullptr) { + return false; + } + + bool result; + napi_status status = napi_is_array(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +inline bool Value::IsArrayBuffer() const { + if (_value == nullptr) { + return false; + } + + bool result; + napi_status status = napi_is_arraybuffer(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +inline bool Value::IsTypedArray() const { + if (_value == nullptr) { + return false; + } + + bool result; + napi_status status = napi_is_typedarray(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +inline bool Value::IsObject() const { + return Type() == napi_object || IsFunction(); +} + +inline bool Value::IsFunction() const { + return Type() == napi_function; +} + +inline bool Value::IsPromise() const { + if (_value == nullptr) { + return false; + } + + bool result; + napi_status status = napi_is_promise(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +inline bool Value::IsDataView() const { + if (_value == nullptr) { + return false; + } + + bool result; + napi_status status = napi_is_dataview(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +//inline bool Value::IsBuffer() const { +// if (_value == nullptr) { +// return false; +// } +// +// bool result; +// napi_status status = napi_is_buffer(_env, _value, &result); +// NAPI_THROW_IF_FAILED(_env, status, false); +// return result; +//} + +inline bool Value::IsExternal() const { + return Type() == napi_external; +} + +template +inline T Value::As() const { + return T(_env, _value); +} + +inline Boolean Value::ToBoolean() const { + napi_value result; + napi_status status = napi_coerce_to_bool(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, Boolean()); + return Boolean(_env, result); +} + +inline Number Value::ToNumber() const { + napi_value result; + napi_status status = napi_coerce_to_number(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, Number()); + return Number(_env, result); +} + +inline String Value::ToString() const { + napi_value result; + napi_status status = napi_coerce_to_string(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, String()); + return String(_env, result); +} + +inline Object Value::ToObject() const { + napi_value result; + napi_status status = napi_coerce_to_object(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, Object()); + return Object(_env, result); +} + +//////////////////////////////////////////////////////////////////////////////// +// Boolean class +//////////////////////////////////////////////////////////////////////////////// + +inline Boolean Boolean::New(napi_env env, bool val) { + napi_value value; + napi_status status = napi_get_boolean(env, val, &value); + NAPI_THROW_IF_FAILED(env, status, Boolean()); + return Boolean(env, value); +} + +inline Boolean::Boolean() : Napi::Value() { +} + +inline Boolean::Boolean(napi_env env, napi_value value) : Napi::Value(env, value) { +} + +inline Boolean::operator bool() const { + return Value(); +} + +inline bool Boolean::Value() const { + bool result; + napi_status status = napi_get_value_bool(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +//////////////////////////////////////////////////////////////////////////////// +// Number class +//////////////////////////////////////////////////////////////////////////////// + +inline Number Number::New(napi_env env, double val) { + napi_value value; + napi_status status = napi_create_double(env, val, &value); + NAPI_THROW_IF_FAILED(env, status, Number()); + return Number(env, value); +} + +inline Number::Number() : Value() { +} + +inline Number::Number(napi_env env, napi_value value) : Value(env, value) { +} + +inline Number::operator int32_t() const { + return Int32Value(); +} + +inline Number::operator uint32_t() const { + return Uint32Value(); +} + +inline Number::operator int64_t() const { + return Int64Value(); +} + +inline Number::operator float() const { + return FloatValue(); +} + +inline Number::operator double() const { + return DoubleValue(); +} + +inline int32_t Number::Int32Value() const { + int32_t result; + napi_status status = napi_get_value_int32(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, 0); + return result; +} + +inline uint32_t Number::Uint32Value() const { + uint32_t result; + napi_status status = napi_get_value_uint32(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, 0); + return result; +} + +inline int64_t Number::Int64Value() const { + int64_t result; + napi_status status = napi_get_value_int64(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, 0); + return result; +} + +inline float Number::FloatValue() const { + return static_cast(DoubleValue()); +} + +inline double Number::DoubleValue() const { + double result; + napi_status status = napi_get_value_double(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, 0); + return result; +} + +// currently experimental guard with version of NAPI_VERSION that it is +// released in once it is no longer experimental +#if (NAPI_VERSION > 2147483646) +//////////////////////////////////////////////////////////////////////////////// +// BigInt Class +//////////////////////////////////////////////////////////////////////////////// + +inline BigInt BigInt::New(napi_env env, int64_t val) { + napi_value value; + napi_status status = napi_create_bigint_int64(env, val, &value); + NAPI_THROW_IF_FAILED(env, status, BigInt()); + return BigInt(env, value); +} + +inline BigInt BigInt::New(napi_env env, uint64_t val) { + napi_value value; + napi_status status = napi_create_bigint_uint64(env, val, &value); + NAPI_THROW_IF_FAILED(env, status, BigInt()); + return BigInt(env, value); +} + +inline BigInt BigInt::New(napi_env env, int sign_bit, size_t word_count, const uint64_t* words) { + napi_value value; + napi_status status = napi_create_bigint_words(env, sign_bit, word_count, words, &value); + NAPI_THROW_IF_FAILED(env, status, BigInt()); + return BigInt(env, value); +} + +inline BigInt::BigInt() : Value() { +} + +inline BigInt::BigInt(napi_env env, napi_value value) : Value(env, value) { +} + +inline int64_t BigInt::Int64Value(bool* lossless) const { + int64_t result; + napi_status status = napi_get_value_bigint_int64( + _env, _value, &result, lossless); + NAPI_THROW_IF_FAILED(_env, status, 0); + return result; +} + +inline uint64_t BigInt::Uint64Value(bool* lossless) const { + uint64_t result; + napi_status status = napi_get_value_bigint_uint64( + _env, _value, &result, lossless); + NAPI_THROW_IF_FAILED(_env, status, 0); + return result; +} + +inline size_t BigInt::WordCount() const { + size_t word_count; + napi_status status = napi_get_value_bigint_words( + _env, _value, nullptr, &word_count, nullptr); + NAPI_THROW_IF_FAILED(_env, status, 0); + return word_count; +} + +inline void BigInt::ToWords(int* sign_bit, size_t* word_count, uint64_t* words) { + napi_status status = napi_get_value_bigint_words( + _env, _value, sign_bit, word_count, words); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} +#endif // NAPI_EXPERIMENTAL + +//////////////////////////////////////////////////////////////////////////////// +// Name class +//////////////////////////////////////////////////////////////////////////////// + +inline Name::Name() : Value() { +} + +inline Name::Name(napi_env env, napi_value value) : Value(env, value) { +} + +//////////////////////////////////////////////////////////////////////////////// +// String class +//////////////////////////////////////////////////////////////////////////////// + +inline String String::New(napi_env env, const std::string& val) { + return String::New(env, val.c_str(), val.size()); +} + +inline String String::New(napi_env env, const std::u16string& val) { + return String::New(env, val.c_str(), val.size()); +} + +inline String String::New(napi_env env, const char* val) { + napi_value value; + napi_status status = napi_create_string_utf8(env, val, std::strlen(val), &value); + NAPI_THROW_IF_FAILED(env, status, String()); + return String(env, value); +} + +inline String String::New(napi_env env, const char16_t* val) { + napi_value value; + napi_status status = napi_create_string_utf16(env, val, std::u16string(val).size(), &value); + NAPI_THROW_IF_FAILED(env, status, String()); + return String(env, value); +} + +inline String String::New(napi_env env, const char* val, size_t length) { + napi_value value; + napi_status status = napi_create_string_utf8(env, val, length, &value); + NAPI_THROW_IF_FAILED(env, status, String()); + return String(env, value); +} + +inline String String::New(napi_env env, const char16_t* val, size_t length) { + napi_value value; + napi_status status = napi_create_string_utf16(env, val, length, &value); + NAPI_THROW_IF_FAILED(env, status, String()); + return String(env, value); +} + +inline String::String() : Name() { +} + +inline String::String(napi_env env, napi_value value) : Name(env, value) { +} + +inline String::operator std::string() const { + return Utf8Value(); +} + +inline String::operator std::u16string() const { + return Utf16Value(); +} + +inline std::string String::Utf8Value() const { + size_t length; + napi_status status = napi_get_value_string_utf8(_env, _value, nullptr, 0, &length); + NAPI_THROW_IF_FAILED(_env, status, ""); + + std::string value; + value.reserve(length + 1); + value.resize(length); + status = napi_get_value_string_utf8(_env, _value, &value[0], value.capacity(), nullptr); + NAPI_THROW_IF_FAILED(_env, status, ""); + return value; +} + +inline std::u16string String::Utf16Value() const { + size_t length; + napi_status status = napi_get_value_string_utf16(_env, _value, nullptr, 0, &length); + NAPI_THROW_IF_FAILED(_env, status, NAPI_WIDE_TEXT("")); + + std::u16string value; + value.reserve(length + 1); + value.resize(length); + status = napi_get_value_string_utf16(_env, _value, &value[0], value.capacity(), nullptr); + NAPI_THROW_IF_FAILED(_env, status, NAPI_WIDE_TEXT("")); + return value; +} + +//////////////////////////////////////////////////////////////////////////////// +// Symbol class +//////////////////////////////////////////////////////////////////////////////// + +inline Symbol Symbol::New(napi_env env, const char* description) { + napi_value descriptionValue = description != nullptr ? + String::New(env, description) : static_cast(nullptr); + return Symbol::New(env, descriptionValue); +} + +inline Symbol Symbol::New(napi_env env, const std::string& description) { + napi_value descriptionValue = String::New(env, description); + return Symbol::New(env, descriptionValue); +} + +inline Symbol Symbol::New(napi_env env, String description) { + napi_value descriptionValue = description; + return Symbol::New(env, descriptionValue); +} + +inline Symbol Symbol::New(napi_env env, napi_value description) { + napi_value value; + napi_status status = napi_create_symbol(env, description, &value); + NAPI_THROW_IF_FAILED(env, status, Symbol()); + return Symbol(env, value); +} + +inline Symbol Symbol::WellKnown(napi_env env, const std::string& name) { + return Napi::Env(env).Global().Get("Symbol").As().Get(name).As(); +} + +inline Symbol::Symbol() : Name() { +} + +inline Symbol::Symbol(napi_env env, napi_value value) : Name(env, value) { +} + +//////////////////////////////////////////////////////////////////////////////// +// Automagic value creation +//////////////////////////////////////////////////////////////////////////////// + +namespace details { +template +struct vf_number { + static Number From(napi_env env, T value) { + return Number::New(env, static_cast(value)); + } +}; + +template<> +struct vf_number { + static Boolean From(napi_env env, bool value) { + return Boolean::New(env, value); + } +}; + +struct vf_utf8_charp { + static String From(napi_env env, const char* value) { + return String::New(env, value); + } +}; + +struct vf_utf16_charp { + static String From(napi_env env, const char16_t* value) { + return String::New(env, value); + } +}; +struct vf_utf8_string { + static String From(napi_env env, const std::string& value) { + return String::New(env, value); + } +}; + +struct vf_utf16_string { + static String From(napi_env env, const std::u16string& value) { + return String::New(env, value); + } +}; + +template +struct vf_fallback { + static Value From(napi_env env, const T& value) { + return Value(env, value); + } +}; + +template struct disjunction : std::false_type {}; +template struct disjunction : B {}; +template +struct disjunction + : std::conditional>::type {}; + +template +struct can_make_string + : disjunction::type, + typename std::is_convertible::type, + typename std::is_convertible::type, + typename std::is_convertible::type> {}; +} + +template +Value Value::From(napi_env env, const T& value) { + using Helper = typename std::conditional< + std::is_integral::value || std::is_floating_point::value, + details::vf_number, + typename std::conditional< + details::can_make_string::value, + String, + details::vf_fallback + >::type + >::type; + return Helper::From(env, value); +} + +template +String String::From(napi_env env, const T& value) { + struct Dummy {}; + using Helper = typename std::conditional< + std::is_convertible::value, + details::vf_utf8_charp, + typename std::conditional< + std::is_convertible::value, + details::vf_utf16_charp, + typename std::conditional< + std::is_convertible::value, + details::vf_utf8_string, + typename std::conditional< + std::is_convertible::value, + details::vf_utf16_string, + Dummy + >::type + >::type + >::type + >::type; + return Helper::From(env, value); +} + +//////////////////////////////////////////////////////////////////////////////// +// Object class +//////////////////////////////////////////////////////////////////////////////// + +template +inline Object::PropertyLValue::operator Value() const { + return Object(_env, _object).Get(_key); +} + +template template +inline Object::PropertyLValue& Object::PropertyLValue::operator =(ValueType value) { + Object(_env, _object).Set(_key, value); + return *this; +} + +template +inline Object::PropertyLValue::PropertyLValue(Object object, Key key) + : _env(object.Env()), _object(object), _key(key) {} + +inline Object Object::New(napi_env env) { + napi_value value; + napi_status status = napi_create_object(env, &value); + NAPI_THROW_IF_FAILED(env, status, Object()); + return Object(env, value); +} + +inline Object::Object() : Value() { +} + +inline Object::Object(napi_env env, napi_value value) : Value(env, value) { +} + +inline Object::PropertyLValue Object::operator [](const char* utf8name) { + return PropertyLValue(*this, utf8name); +} + +inline Object::PropertyLValue Object::operator [](const std::string& utf8name) { + return PropertyLValue(*this, utf8name); +} + +inline Object::PropertyLValue Object::operator [](uint32_t index) { + return PropertyLValue(*this, index); +} + +inline Value Object::operator [](const char* utf8name) const { + return Get(utf8name); +} + +inline Value Object::operator [](const std::string& utf8name) const { + return Get(utf8name); +} + +inline Value Object::operator [](uint32_t index) const { + return Get(index); +} + +inline bool Object::Has(napi_value key) const { + bool result; + napi_status status = napi_has_property(_env, _value, key, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +inline bool Object::Has(Value key) const { + bool result; + napi_status status = napi_has_property(_env, _value, key, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +inline bool Object::Has(const char* utf8name) const { + bool result; + napi_status status = napi_has_named_property(_env, _value, utf8name, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +inline bool Object::Has(const std::string& utf8name) const { + return Has(utf8name.c_str()); +} + +inline bool Object::HasOwnProperty(napi_value key) const { + bool result; + napi_status status = napi_has_own_property(_env, _value, key, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +inline bool Object::HasOwnProperty(Value key) const { + bool result; + napi_status status = napi_has_own_property(_env, _value, key, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +inline bool Object::HasOwnProperty(const char* utf8name) const { + napi_value key; + napi_status status = napi_create_string_utf8(_env, utf8name, std::strlen(utf8name), &key); + NAPI_THROW_IF_FAILED(_env, status, false); + return HasOwnProperty(key); +} + +inline bool Object::HasOwnProperty(const std::string& utf8name) const { + return HasOwnProperty(utf8name.c_str()); +} + +inline Value Object::Get(napi_value key) const { + napi_value result; + napi_status status = napi_get_property(_env, _value, key, &result); + NAPI_THROW_IF_FAILED(_env, status, Value()); + return Value(_env, result); +} + +inline Value Object::Get(Value key) const { + napi_value result; + napi_status status = napi_get_property(_env, _value, key, &result); + NAPI_THROW_IF_FAILED(_env, status, Value()); + return Value(_env, result); +} + +inline Value Object::Get(const char* utf8name) const { + napi_value result; + napi_status status = napi_get_named_property(_env, _value, utf8name, &result); + NAPI_THROW_IF_FAILED(_env, status, Value()); + return Value(_env, result); +} + +inline Value Object::Get(const std::string& utf8name) const { + return Get(utf8name.c_str()); +} + +template +inline void Object::Set(napi_value key, const ValueType& value) { + napi_status status = + napi_set_property(_env, _value, key, Value::From(_env, value)); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +template +inline void Object::Set(Value key, const ValueType& value) { + napi_status status = + napi_set_property(_env, _value, key, Value::From(_env, value)); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +template +inline void Object::Set(const char* utf8name, const ValueType& value) { + napi_status status = + napi_set_named_property(_env, _value, utf8name, Value::From(_env, value)); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +template +inline void Object::Set(const std::string& utf8name, const ValueType& value) { + Set(utf8name.c_str(), value); +} + +inline bool Object::Delete(napi_value key) { + bool result; + napi_status status = napi_delete_property(_env, _value, key, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +inline bool Object::Delete(Value key) { + bool result; + napi_status status = napi_delete_property(_env, _value, key, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +inline bool Object::Delete(const char* utf8name) { + return Delete(String::New(_env, utf8name)); +} + +inline bool Object::Delete(const std::string& utf8name) { + return Delete(String::New(_env, utf8name)); +} + +inline bool Object::Has(uint32_t index) const { + bool result; + napi_status status = napi_has_element(_env, _value, index, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +inline Value Object::Get(uint32_t index) const { + napi_value value; + napi_status status = napi_get_element(_env, _value, index, &value); + NAPI_THROW_IF_FAILED(_env, status, Value()); + return Value(_env, value); +} + +template +inline void Object::Set(uint32_t index, const ValueType& value) { + napi_status status = + napi_set_element(_env, _value, index, Value::From(_env, value)); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline bool Object::Delete(uint32_t index) { + bool result; + napi_status status = napi_delete_element(_env, _value, index, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +inline Array Object::GetPropertyNames() { + napi_value result; + napi_status status = napi_get_property_names(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, Array()); + return Array(_env, result); +} + +inline void Object::DefineProperty(const PropertyDescriptor& property) { + napi_status status = napi_define_properties(_env, _value, 1, + reinterpret_cast(&property)); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline void Object::DefineProperties(const std::initializer_list& properties) { + napi_status status = napi_define_properties(_env, _value, properties.size(), + reinterpret_cast(properties.begin())); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline void Object::DefineProperties(const std::vector& properties) { + napi_status status = napi_define_properties(_env, _value, properties.size(), + reinterpret_cast(properties.data())); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline bool Object::InstanceOf(const Function& constructor) const { + bool result; + napi_status status = napi_instanceof(_env, _value, constructor, &result); + NAPI_THROW_IF_FAILED(_env, status, false); + return result; +} + +//////////////////////////////////////////////////////////////////////////////// +// External class +//////////////////////////////////////////////////////////////////////////////// + +template +inline External External::New(napi_env env, T* data) { + napi_value value; + napi_status status = napi_create_external(env, data, nullptr, nullptr, &value); + NAPI_THROW_IF_FAILED(env, status, External()); + return External(env, value); +} + +template +template +inline External External::New(napi_env env, + T* data, + Finalizer finalizeCallback) { + napi_value value; + details::FinalizeData* finalizeData = + new details::FinalizeData({ finalizeCallback, nullptr }); + napi_status status = napi_create_external( + env, + data, + details::FinalizeData::Wrapper, + finalizeData, + &value); + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED(env, status, External()); + } + return External(env, value); +} + +template +template +inline External External::New(napi_env env, + T* data, + Finalizer finalizeCallback, + Hint* finalizeHint) { + napi_value value; + details::FinalizeData* finalizeData = + new details::FinalizeData({ finalizeCallback, finalizeHint }); + napi_status status = napi_create_external( + env, + data, + details::FinalizeData::WrapperWithHint, + finalizeData, + &value); + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED(env, status, External()); + } + return External(env, value); +} + +template +inline External::External() : Value() { +} + +template +inline External::External(napi_env env, napi_value value) : Value(env, value) { +} + +template +inline T* External::Data() const { + void* data; + napi_status status = napi_get_value_external(_env, _value, &data); + NAPI_THROW_IF_FAILED(_env, status, nullptr); + return reinterpret_cast(data); +} + +//////////////////////////////////////////////////////////////////////////////// +// Array class +//////////////////////////////////////////////////////////////////////////////// + +inline Array Array::New(napi_env env) { + napi_value value; + napi_status status = napi_create_array(env, &value); + NAPI_THROW_IF_FAILED(env, status, Array()); + return Array(env, value); +} + +inline Array Array::New(napi_env env, size_t length) { + napi_value value; + napi_status status = napi_create_array_with_length(env, length, &value); + NAPI_THROW_IF_FAILED(env, status, Array()); + return Array(env, value); +} + +inline Array::Array() : Object() { +} + +inline Array::Array(napi_env env, napi_value value) : Object(env, value) { +} + +inline uint32_t Array::Length() const { + uint32_t result; + napi_status status = napi_get_array_length(_env, _value, &result); + NAPI_THROW_IF_FAILED(_env, status, 0); + return result; +} + +//////////////////////////////////////////////////////////////////////////////// +// ArrayBuffer class +//////////////////////////////////////////////////////////////////////////////// + +inline ArrayBuffer ArrayBuffer::New(napi_env env, size_t byteLength) { + napi_value value; + void* data; + napi_status status = napi_create_arraybuffer(env, byteLength, &data, &value); + NAPI_THROW_IF_FAILED(env, status, ArrayBuffer()); + + return ArrayBuffer(env, value, data, byteLength); +} + +inline ArrayBuffer ArrayBuffer::New(napi_env env, + void* externalData, + size_t byteLength) { + napi_value value; + napi_status status = napi_create_external_arraybuffer( + env, externalData, byteLength, nullptr, nullptr, &value); + NAPI_THROW_IF_FAILED(env, status, ArrayBuffer()); + + return ArrayBuffer(env, value, externalData, byteLength); +} + +template +inline ArrayBuffer ArrayBuffer::New(napi_env env, + void* externalData, + size_t byteLength, + Finalizer finalizeCallback) { + napi_value value; + details::FinalizeData* finalizeData = + new details::FinalizeData({ finalizeCallback, nullptr }); + napi_status status = napi_create_external_arraybuffer( + env, + externalData, + byteLength, + details::FinalizeData::Wrapper, + finalizeData, + &value); + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED(env, status, ArrayBuffer()); + } + + return ArrayBuffer(env, value, externalData, byteLength); +} + +template +inline ArrayBuffer ArrayBuffer::New(napi_env env, + void* externalData, + size_t byteLength, + Finalizer finalizeCallback, + Hint* finalizeHint) { + napi_value value; + details::FinalizeData* finalizeData = + new details::FinalizeData({ finalizeCallback, finalizeHint }); + napi_status status = napi_create_external_arraybuffer( + env, + externalData, + byteLength, + details::FinalizeData::WrapperWithHint, + finalizeData, + &value); + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED(env, status, ArrayBuffer()); + } + + return ArrayBuffer(env, value, externalData, byteLength); +} + +inline ArrayBuffer::ArrayBuffer() : Object(), _data(nullptr), _length(0) { +} + +inline ArrayBuffer::ArrayBuffer(napi_env env, napi_value value) + : Object(env, value), _data(nullptr), _length(0) { +} + +inline ArrayBuffer::ArrayBuffer(napi_env env, napi_value value, void* data, size_t length) + : Object(env, value), _data(data), _length(length) { +} + +inline void* ArrayBuffer::Data() const { + EnsureInfo(); + return _data; +} + +inline size_t ArrayBuffer::ByteLength() const { + EnsureInfo(); + return _length; +} + +inline void ArrayBuffer::EnsureInfo() const { + // The ArrayBuffer instance may have been constructed from a napi_value whose + // length/data are not yet known. Fetch and cache these values just once, + // since they can never change during the lifetime of the ArrayBuffer. + if (_data == nullptr) { + napi_status status = napi_get_arraybuffer_info(_env, _value, &_data, &_length); + NAPI_THROW_IF_FAILED_VOID(_env, status); + } +} + +//////////////////////////////////////////////////////////////////////////////// +// DataView class +//////////////////////////////////////////////////////////////////////////////// +inline DataView DataView::New(napi_env env, + Napi::ArrayBuffer arrayBuffer) { + return New(env, arrayBuffer, 0, arrayBuffer.ByteLength()); +} + +inline DataView DataView::New(napi_env env, + Napi::ArrayBuffer arrayBuffer, + size_t byteOffset) { + if (byteOffset > arrayBuffer.ByteLength()) { + NAPI_THROW(RangeError::New(env, + "Start offset is outside the bounds of the buffer")); + return DataView(); + } + return New(env, arrayBuffer, byteOffset, + arrayBuffer.ByteLength() - byteOffset); +} + +inline DataView DataView::New(napi_env env, + Napi::ArrayBuffer arrayBuffer, + size_t byteOffset, + size_t byteLength) { + if (byteOffset + byteLength > arrayBuffer.ByteLength()) { + NAPI_THROW(RangeError::New(env, "Invalid DataView length")); + return DataView(); + } + napi_value value; + napi_status status = napi_create_dataview( + env, byteLength, arrayBuffer, byteOffset, &value); + NAPI_THROW_IF_FAILED(env, status, DataView()); + return DataView(env, value); +} + +inline DataView::DataView() : Object() { +} + +inline DataView::DataView(napi_env env, napi_value value) : Object(env, value) { + napi_status status = napi_get_dataview_info( + _env, + _value /* dataView */, + &_length /* byteLength */, + &_data /* data */, + nullptr /* arrayBuffer */, + nullptr /* byteOffset */); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline Napi::ArrayBuffer DataView::ArrayBuffer() const { + napi_value arrayBuffer; + napi_status status = napi_get_dataview_info( + _env, + _value /* dataView */, + nullptr /* byteLength */, + nullptr /* data */, + &arrayBuffer /* arrayBuffer */, + nullptr /* byteOffset */); + NAPI_THROW_IF_FAILED(_env, status, Napi::ArrayBuffer()); + return Napi::ArrayBuffer(_env, arrayBuffer); +} + +inline size_t DataView::ByteOffset() const { + size_t byteOffset; + napi_status status = napi_get_dataview_info( + _env, + _value /* dataView */, + nullptr /* byteLength */, + nullptr /* data */, + nullptr /* arrayBuffer */, + &byteOffset /* byteOffset */); + NAPI_THROW_IF_FAILED(_env, status, 0); + return byteOffset; +} + +inline size_t DataView::ByteLength() const { + return _length; +} + +inline void* DataView::Data() const { + return _data; +} + +inline float DataView::GetFloat32(size_t byteOffset) const { + return ReadData(byteOffset); +} + +inline double DataView::GetFloat64(size_t byteOffset) const { + return ReadData(byteOffset); +} + +inline int8_t DataView::GetInt8(size_t byteOffset) const { + return ReadData(byteOffset); +} + +inline int16_t DataView::GetInt16(size_t byteOffset) const { + return ReadData(byteOffset); +} + +inline int32_t DataView::GetInt32(size_t byteOffset) const { + return ReadData(byteOffset); +} + +inline uint8_t DataView::GetUint8(size_t byteOffset) const { + return ReadData(byteOffset); +} + +inline uint16_t DataView::GetUint16(size_t byteOffset) const { + return ReadData(byteOffset); +} + +inline uint32_t DataView::GetUint32(size_t byteOffset) const { + return ReadData(byteOffset); +} + +inline void DataView::SetFloat32(size_t byteOffset, float value) const { + WriteData(byteOffset, value); +} + +inline void DataView::SetFloat64(size_t byteOffset, double value) const { + WriteData(byteOffset, value); +} + +inline void DataView::SetInt8(size_t byteOffset, int8_t value) const { + WriteData(byteOffset, value); +} + +inline void DataView::SetInt16(size_t byteOffset, int16_t value) const { + WriteData(byteOffset, value); +} + +inline void DataView::SetInt32(size_t byteOffset, int32_t value) const { + WriteData(byteOffset, value); +} + +inline void DataView::SetUint8(size_t byteOffset, uint8_t value) const { + WriteData(byteOffset, value); +} + +inline void DataView::SetUint16(size_t byteOffset, uint16_t value) const { + WriteData(byteOffset, value); +} + +inline void DataView::SetUint32(size_t byteOffset, uint32_t value) const { + WriteData(byteOffset, value); +} + +template +inline T DataView::ReadData(size_t byteOffset) const { + if (byteOffset + sizeof(T) > _length || + byteOffset + sizeof(T) < byteOffset) { // overflow + NAPI_THROW(RangeError::New(_env, + "Offset is outside the bounds of the DataView")); + return 0; + } + + return *reinterpret_cast(static_cast(_data) + byteOffset); +} + +template +inline void DataView::WriteData(size_t byteOffset, T value) const { + if (byteOffset + sizeof(T) > _length || + byteOffset + sizeof(T) < byteOffset) { // overflow + NAPI_THROW(RangeError::New(_env, + "Offset is outside the bounds of the DataView")); + return; + } + + *reinterpret_cast(static_cast(_data) + byteOffset) = value; +} + +//////////////////////////////////////////////////////////////////////////////// +// TypedArray class +//////////////////////////////////////////////////////////////////////////////// + +inline TypedArray::TypedArray() + : Object(), _type(TypedArray::unknown_array_type), _length(0) { +} + +inline TypedArray::TypedArray(napi_env env, napi_value value) + : Object(env, value), _type(TypedArray::unknown_array_type), _length(0) { +} + +inline TypedArray::TypedArray(napi_env env, + napi_value value, + napi_typedarray_type type, + size_t length) + : Object(env, value), _type(type), _length(length) { +} + +inline napi_typedarray_type TypedArray::TypedArrayType() const { + if (_type == TypedArray::unknown_array_type) { + napi_status status = napi_get_typedarray_info(_env, _value, + &const_cast(this)->_type, &const_cast(this)->_length, + nullptr, nullptr, nullptr); + NAPI_THROW_IF_FAILED(_env, status, napi_int8_array); + } + + return _type; +} + +inline uint8_t TypedArray::ElementSize() const { + switch (TypedArrayType()) { + case napi_int8_array: + case napi_uint8_array: + case napi_uint8_clamped_array: + return 1; + case napi_int16_array: + case napi_uint16_array: + return 2; + case napi_int32_array: + case napi_uint32_array: + case napi_float32_array: + return 4; + case napi_float64_array: + return 8; + default: + return 0; + } +} + +inline size_t TypedArray::ElementLength() const { + if (_type == TypedArray::unknown_array_type) { + napi_status status = napi_get_typedarray_info(_env, _value, + &const_cast(this)->_type, &const_cast(this)->_length, + nullptr, nullptr, nullptr); + NAPI_THROW_IF_FAILED(_env, status, 0); + } + + return _length; +} + +inline size_t TypedArray::ByteOffset() const { + size_t byteOffset; + napi_status status = napi_get_typedarray_info( + _env, _value, nullptr, nullptr, nullptr, nullptr, &byteOffset); + NAPI_THROW_IF_FAILED(_env, status, 0); + return byteOffset; +} + +inline size_t TypedArray::ByteLength() const { + return ElementSize() * ElementLength(); +} + +inline Napi::ArrayBuffer TypedArray::ArrayBuffer() const { + napi_value arrayBuffer; + napi_status status = napi_get_typedarray_info( + _env, _value, nullptr, nullptr, nullptr, &arrayBuffer, nullptr); + NAPI_THROW_IF_FAILED(_env, status, Napi::ArrayBuffer()); + return Napi::ArrayBuffer(_env, arrayBuffer); +} + +//////////////////////////////////////////////////////////////////////////////// +// TypedArrayOf class +//////////////////////////////////////////////////////////////////////////////// + +template +inline TypedArrayOf TypedArrayOf::New(napi_env env, + size_t elementLength, + napi_typedarray_type type) { + Napi::ArrayBuffer arrayBuffer = Napi::ArrayBuffer::New(env, elementLength * sizeof (T)); + return New(env, elementLength, arrayBuffer, 0, type); +} + +template +inline TypedArrayOf TypedArrayOf::New(napi_env env, + size_t elementLength, + Napi::ArrayBuffer arrayBuffer, + size_t bufferOffset, + napi_typedarray_type type) { + napi_value value; + napi_status status = napi_create_typedarray( + env, type, elementLength, arrayBuffer, bufferOffset, &value); + NAPI_THROW_IF_FAILED(env, status, TypedArrayOf()); + + return TypedArrayOf( + env, value, type, elementLength, + reinterpret_cast(reinterpret_cast(arrayBuffer.Data()) + bufferOffset)); +} + +template +inline TypedArrayOf::TypedArrayOf() : TypedArray(), _data(nullptr) { +} + +template +inline TypedArrayOf::TypedArrayOf(napi_env env, napi_value value) + : TypedArray(env, value), _data(nullptr) { + napi_status status = napi_get_typedarray_info( + _env, _value, &_type, &_length, reinterpret_cast(&_data), nullptr, nullptr); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +template +inline TypedArrayOf::TypedArrayOf(napi_env env, + napi_value value, + napi_typedarray_type type, + size_t length, + T* data) + : TypedArray(env, value, type, length), _data(data) { + if (!(type == TypedArrayTypeForPrimitiveType() || + (type == napi_uint8_clamped_array && std::is_same::value))) { + NAPI_THROW(TypeError::New(env, "Array type must match the template parameter. " + "(Uint8 arrays may optionally have the \"clamped\" array type.)")); + } +} + +template +inline T& TypedArrayOf::operator [](size_t index) { + return _data[index]; +} + +template +inline const T& TypedArrayOf::operator [](size_t index) const { + return _data[index]; +} + +template +inline T* TypedArrayOf::Data() { + return _data; +} + +template +inline const T* TypedArrayOf::Data() const { + return _data; +} + +//////////////////////////////////////////////////////////////////////////////// +// Function class +//////////////////////////////////////////////////////////////////////////////// + +template +static inline napi_status +CreateFunction(napi_env env, + const char* utf8name, + napi_callback cb, + CbData* data, + napi_value* result) { + napi_status status = + napi_create_function(env, utf8name, NAPI_AUTO_LENGTH, cb, data, result); + if (status == napi_ok) { + status = Napi::details::AttachData(env, *result, data); + } + + return status; +} + +template +inline Function Function::New(napi_env env, + Callable cb, + const char* utf8name, + void* data) { + typedef decltype(cb(CallbackInfo(nullptr, nullptr))) ReturnType; + typedef details::CallbackData CbData; + auto callbackData = new CbData({ cb, data }); + + napi_value value; + napi_status status = CreateFunction(env, + utf8name, + CbData::Wrapper, + callbackData, + &value); + NAPI_THROW_IF_FAILED(env, status, Function()); + return Function(env, value); +} + +template +inline Function Function::New(napi_env env, + Callable cb, + const std::string& utf8name, + void* data) { + return New(env, cb, utf8name.c_str(), data); +} + +inline Function::Function() : Object() { +} + +inline Function::Function(napi_env env, napi_value value) : Object(env, value) { +} + +inline Value Function::operator ()(const std::initializer_list& args) const { + return Call(Env().Undefined(), args); +} + +inline Value Function::Call(const std::initializer_list& args) const { + return Call(Env().Undefined(), args); +} + +inline Value Function::Call(const std::vector& args) const { + return Call(Env().Undefined(), args); +} + +inline Value Function::Call(size_t argc, const napi_value* args) const { + return Call(Env().Undefined(), argc, args); +} + +inline Value Function::Call(napi_value recv, const std::initializer_list& args) const { + return Call(recv, args.size(), args.begin()); +} + +inline Value Function::Call(napi_value recv, const std::vector& args) const { + return Call(recv, args.size(), args.data()); +} + +inline Value Function::Call(napi_value recv, size_t argc, const napi_value* args) const { + napi_value result; + napi_status status = napi_call_function( + _env, recv, _value, argc, args, &result); + NAPI_THROW_IF_FAILED(_env, status, Value()); + return Value(_env, result); +} + +//inline Value Function::MakeCallback( +// napi_value recv, +// const std::initializer_list& args, +// napi_async_context context) const { +// return MakeCallback(recv, args.size(), args.begin(), context); +//} +// +//inline Value Function::MakeCallback( +// napi_value recv, +// const std::vector& args, +// napi_async_context context) const { +// return MakeCallback(recv, args.size(), args.data(), context); +//} +// +//inline Value Function::MakeCallback( +// napi_value recv, +// size_t argc, +// const napi_value* args, +// napi_async_context context) const { +// napi_value result; +// napi_status status = napi_make_callback( +// _env, context, recv, _value, argc, args, &result); +// NAPI_THROW_IF_FAILED(_env, status, Value()); +// return Value(_env, result); +//} + +inline Object Function::New(const std::initializer_list& args) const { + return New(args.size(), args.begin()); +} + +inline Object Function::New(const std::vector& args) const { + return New(args.size(), args.data()); +} + +inline Object Function::New(size_t argc, const napi_value* args) const { + napi_value result; + napi_status status = napi_new_instance( + _env, _value, argc, args, &result); + NAPI_THROW_IF_FAILED(_env, status, Object()); + return Object(_env, result); +} + +//////////////////////////////////////////////////////////////////////////////// +// Promise class +//////////////////////////////////////////////////////////////////////////////// + +inline Promise::Deferred Promise::Deferred::New(napi_env env) { + return Promise::Deferred(env); +} + +inline Promise::Deferred::Deferred(napi_env env) : _env(env) { + napi_status status = napi_create_promise(_env, &_deferred, &_promise); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline Promise Promise::Deferred::Promise() const { + return Napi::Promise(_env, _promise); +} + +inline Napi::Env Promise::Deferred::Env() const { + return Napi::Env(_env); +} + +inline void Promise::Deferred::Resolve(napi_value value) const { + napi_status status = napi_resolve_deferred(_env, _deferred, value); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline void Promise::Deferred::Reject(napi_value value) const { + napi_status status = napi_reject_deferred(_env, _deferred, value); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline Promise::Promise(napi_env env, napi_value value) : Object(env, value) { +} + +//////////////////////////////////////////////////////////////////////////////// +// Buffer class +//////////////////////////////////////////////////////////////////////////////// + +template +inline Buffer Buffer::New(napi_env env, size_t length) { + napi_value value; + void* data; + napi_status status = napi_create_buffer(env, length * sizeof (T), &data, &value); + NAPI_THROW_IF_FAILED(env, status, Buffer()); + return Buffer(env, value, length, static_cast(data)); +} + +template +inline Buffer Buffer::New(napi_env env, T* data, size_t length) { + napi_value value; + napi_status status = napi_create_external_buffer( + env, length * sizeof (T), data, nullptr, nullptr, &value); + NAPI_THROW_IF_FAILED(env, status, Buffer()); + return Buffer(env, value, length, data); +} + +template +template +inline Buffer Buffer::New(napi_env env, + T* data, + size_t length, + Finalizer finalizeCallback) { + napi_value value; + details::FinalizeData* finalizeData = + new details::FinalizeData({ finalizeCallback, nullptr }); + napi_status status = napi_create_external_buffer( + env, + length * sizeof (T), + data, + details::FinalizeData::Wrapper, + finalizeData, + &value); + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED(env, status, Buffer()); + } + return Buffer(env, value, length, data); +} + +template +template +inline Buffer Buffer::New(napi_env env, + T* data, + size_t length, + Finalizer finalizeCallback, + Hint* finalizeHint) { + napi_value value; + details::FinalizeData* finalizeData = + new details::FinalizeData({ finalizeCallback, finalizeHint }); + napi_status status = napi_create_external_buffer( + env, + length * sizeof (T), + data, + details::FinalizeData::WrapperWithHint, + finalizeData, + &value); + if (status != napi_ok) { + delete finalizeData; + NAPI_THROW_IF_FAILED(env, status, Buffer()); + } + return Buffer(env, value, length, data); +} + +template +inline Buffer Buffer::Copy(napi_env env, const T* data, size_t length) { + napi_value value; + napi_status status = napi_create_buffer_copy( + env, length * sizeof (T), data, nullptr, &value); + NAPI_THROW_IF_FAILED(env, status, Buffer()); + return Buffer(env, value); +} + +template +inline Buffer::Buffer() : Uint8Array(), _length(0), _data(nullptr) { +} + +template +inline Buffer::Buffer(napi_env env, napi_value value) + : Uint8Array(env, value), _length(0), _data(nullptr) { +} + +template +inline Buffer::Buffer(napi_env env, napi_value value, size_t length, T* data) + : Uint8Array(env, value), _length(length), _data(data) { +} + +template +inline size_t Buffer::Length() const { + EnsureInfo(); + return _length; +} + +template +inline T* Buffer::Data() const { + EnsureInfo(); + return _data; +} + +template +inline void Buffer::EnsureInfo() const { + // The Buffer instance may have been constructed from a napi_value whose + // length/data are not yet known. Fetch and cache these values just once, + // since they can never change during the lifetime of the Buffer. + if (_data == nullptr) { + size_t byteLength; + void* voidData; + napi_status status = napi_get_buffer_info(_env, _value, &voidData, &byteLength); + NAPI_THROW_IF_FAILED_VOID(_env, status); + _length = byteLength / sizeof (T); + _data = static_cast(voidData); + } +} + +//////////////////////////////////////////////////////////////////////////////// +// Error class +//////////////////////////////////////////////////////////////////////////////// + +inline Error Error::New(napi_env env) { + napi_status status; + napi_value error = nullptr; + + const napi_extended_error_info* info; + status = napi_get_last_error_info(env, &info); + NAPI_FATAL_IF_FAILED(status, "Error::New", "napi_get_last_error_info"); + + if (status == napi_ok) { + if (info->error_code == napi_pending_exception) { + status = napi_get_and_clear_last_exception(env, &error); + NAPI_FATAL_IF_FAILED(status, "Error::New", "napi_get_and_clear_last_exception"); + } + else { + const char* error_message = info->error_message != nullptr ? + info->error_message : "Error in native callback"; + + bool isExceptionPending; + status = napi_is_exception_pending(env, &isExceptionPending); + NAPI_FATAL_IF_FAILED(status, "Error::New", "napi_is_exception_pending"); + + if (isExceptionPending) { + status = napi_get_and_clear_last_exception(env, &error); + NAPI_FATAL_IF_FAILED(status, "Error::New", "napi_get_and_clear_last_exception"); + } + + napi_value message; + status = napi_create_string_utf8( + env, + error_message, + std::strlen(error_message), + &message); + NAPI_FATAL_IF_FAILED(status, "Error::New", "napi_create_string_utf8"); + + if (status == napi_ok) { + switch (info->error_code) { + case napi_object_expected: + case napi_string_expected: + case napi_boolean_expected: + case napi_number_expected: + status = napi_create_type_error(env, nullptr, message, &error); + break; + default: + status = napi_create_error(env, nullptr, message, &error); + break; + } + NAPI_FATAL_IF_FAILED(status, "Error::New", "napi_create_error"); + } + } + } + + return Error(env, error); +} + +inline Error Error::New(napi_env env, const char* message) { + return Error::New(env, message, std::strlen(message), napi_create_error); +} + +inline Error Error::New(napi_env env, const std::string& message) { + return Error::New(env, message.c_str(), message.size(), napi_create_error); +} + +inline void Error::Fatal(const char*, const char* message) { + // $HACK + //napi_fatal_error(location, NAPI_AUTO_LENGTH, message, NAPI_AUTO_LENGTH); + throw new std::runtime_error(message); +} + +inline Error::Error() : ObjectReference() { +} + +inline Error::Error(napi_env env, napi_value value) : ObjectReference(env, nullptr) { + if (value != nullptr) { + napi_status status = napi_create_reference(env, value, 1, &_ref); + + // Avoid infinite recursion in the failure case. + // Don't try to construct & throw another Error instance. + NAPI_FATAL_IF_FAILED(status, "Error::Error", "napi_create_reference"); + } +} + +inline Error::Error(Error&& other) : ObjectReference(std::move(other)) { +} + +inline Error& Error::operator =(Error&& other) { + static_cast*>(this)->operator=(std::move(other)); + return *this; +} + +inline Error::Error(const Error& other) : ObjectReference(other) { +} + +inline Error& Error::operator =(Error& other) { + Reset(); + + _env = other.Env(); + HandleScope scope(_env); + + napi_value value = other.Value(); + if (value != nullptr) { + napi_status status = napi_create_reference(_env, value, 1, &_ref); + NAPI_THROW_IF_FAILED(_env, status, *this); + } + + return *this; +} + +inline const std::string& Error::Message() const NAPI_NOEXCEPT { + if (_message.size() == 0 && _env != nullptr) { +#ifdef NAPI_CPP_EXCEPTIONS + try { + _message = Get("message").As(); + } + catch (...) { + // Catch all errors here, to include e.g. a std::bad_alloc from + // the std::string::operator=, because this method may not throw. + } +#else // NAPI_CPP_EXCEPTIONS + _message = Get("message").As(); +#endif // NAPI_CPP_EXCEPTIONS + } + return _message; +} + +inline void Error::ThrowAsJavaScriptException() const { + HandleScope scope(_env); + if (!IsEmpty()) { + napi_status status = napi_throw(_env, Value()); + NAPI_THROW_IF_FAILED_VOID(_env, status); + } +} + +#ifdef NAPI_CPP_EXCEPTIONS + +inline const char* Error::what() const NAPI_NOEXCEPT { + return Message().c_str(); +} + +#endif // NAPI_CPP_EXCEPTIONS + +template +inline TError Error::New(napi_env env, + const char* message, + size_t length, + create_error_fn create_error) { + napi_value str; + napi_status status = napi_create_string_utf8(env, message, length, &str); + NAPI_THROW_IF_FAILED(env, status, TError()); + + napi_value error; + status = create_error(env, nullptr, str, &error); + NAPI_THROW_IF_FAILED(env, status, TError()); + + return TError(env, error); +} + +inline TypeError TypeError::New(napi_env env, const char* message) { + return Error::New(env, message, std::strlen(message), napi_create_type_error); +} + +inline TypeError TypeError::New(napi_env env, const std::string& message) { + return Error::New(env, message.c_str(), message.size(), napi_create_type_error); +} + +inline TypeError::TypeError() : Error() { +} + +inline TypeError::TypeError(napi_env env, napi_value value) : Error(env, value) { +} + +inline RangeError RangeError::New(napi_env env, const char* message) { + return Error::New(env, message, std::strlen(message), napi_create_range_error); +} + +inline RangeError RangeError::New(napi_env env, const std::string& message) { + return Error::New(env, message.c_str(), message.size(), napi_create_range_error); +} + +inline RangeError::RangeError() : Error() { +} + +inline RangeError::RangeError(napi_env env, napi_value value) : Error(env, value) { +} + +//////////////////////////////////////////////////////////////////////////////// +// Reference class +//////////////////////////////////////////////////////////////////////////////// + +template +inline Reference Reference::New(const T& value, uint32_t initialRefcount) { + napi_env env = value.Env(); + napi_value val = value; + + if (val == nullptr) { + return Reference(env, nullptr); + } + + napi_ref ref; + napi_status status = napi_create_reference(env, value, initialRefcount, &ref); + NAPI_THROW_IF_FAILED(env, status, Reference()); + + return Reference(env, ref); +} + + +template +inline Reference::Reference() : _env(nullptr), _ref(nullptr), _suppressDestruct(false) { +} + +template +inline Reference::Reference(napi_env env, napi_ref ref) + : _env(env), _ref(ref), _suppressDestruct(false) { +} + +template +inline Reference::~Reference() { + if (_ref != nullptr) { + if (!_suppressDestruct) { + napi_delete_reference(_env, _ref); + } + + _ref = nullptr; + } +} + +template +inline Reference::Reference(Reference&& other) + : _env(other._env), _ref(other._ref), _suppressDestruct(other._suppressDestruct) { + other._env = nullptr; + other._ref = nullptr; + other._suppressDestruct = false; +} + +template +inline Reference& Reference::operator =(Reference&& other) { + Reset(); + _env = other._env; + _ref = other._ref; + _suppressDestruct = other._suppressDestruct; + other._env = nullptr; + other._ref = nullptr; + other._suppressDestruct = false; + return *this; +} + +template +inline Reference::Reference(const Reference& other) + : _env(other._env), _ref(nullptr), _suppressDestruct(false) { + HandleScope scope(_env); + + napi_value value = other.Value(); + if (value != nullptr) { + // Copying is a limited scenario (currently only used for Error object) and always creates a + // strong reference to the given value even if the incoming reference is weak. + napi_status status = napi_create_reference(_env, value, 1, &_ref); + NAPI_FATAL_IF_FAILED(status, "Reference::Reference", "napi_create_reference"); + } +} + +template +inline Reference::operator napi_ref() const { + return _ref; +} + +template +inline bool Reference::operator ==(const Reference &other) const { + HandleScope scope(_env); + return this->Value().StrictEquals(other.Value()); +} + +template +inline bool Reference::operator !=(const Reference &other) const { + return !this->operator ==(other); +} + +template +inline Napi::Env Reference::Env() const { + return Napi::Env(_env); +} + +template +inline bool Reference::IsEmpty() const { + return _ref == nullptr; +} + +template +inline T Reference::Value() const { + if (_ref == nullptr) { + return T(_env, nullptr); + } + + napi_value value; + napi_status status = napi_get_reference_value(_env, _ref, &value); + NAPI_THROW_IF_FAILED(_env, status, T()); + return T(_env, value); +} + +template +inline uint32_t Reference::Ref() { + uint32_t result; + napi_status status = napi_reference_ref(_env, _ref, &result); + NAPI_THROW_IF_FAILED(_env, status, 1); + return result; +} + +template +inline uint32_t Reference::Unref() { + uint32_t result; + napi_status status = napi_reference_unref(_env, _ref, &result); + NAPI_THROW_IF_FAILED(_env, status, 1); + return result; +} + +template +inline void Reference::Reset() { + if (_ref != nullptr) { + napi_status status = napi_delete_reference(_env, _ref); + NAPI_THROW_IF_FAILED_VOID(_env, status); + _ref = nullptr; + } +} + +template +inline void Reference::Reset(const T& value, uint32_t refcount) { + Reset(); + _env = value.Env(); + + napi_value val = value; + if (val != nullptr) { + napi_status status = napi_create_reference(_env, value, refcount, &_ref); + NAPI_THROW_IF_FAILED_VOID(_env, status); + } +} + +template +inline void Reference::SuppressDestruct() { + _suppressDestruct = true; +} + +template +inline Reference Weak(T value) { + return Reference::New(value, 0); +} + +inline ObjectReference Weak(Object value) { + return Reference::New(value, 0); +} + +inline FunctionReference Weak(Function value) { + return Reference::New(value, 0); +} + +template +inline Reference Persistent(T value) { + return Reference::New(value, 1); +} + +inline ObjectReference Persistent(Object value) { + return Reference::New(value, 1); +} + +inline FunctionReference Persistent(Function value) { + return Reference::New(value, 1); +} + +//////////////////////////////////////////////////////////////////////////////// +// ObjectReference class +//////////////////////////////////////////////////////////////////////////////// + +inline ObjectReference::ObjectReference(): Reference() { +} + +inline ObjectReference::ObjectReference(napi_env env, napi_ref ref): Reference(env, ref) { +} + +inline ObjectReference::ObjectReference(Reference&& other) + : Reference(std::move(other)) { +} + +inline ObjectReference& ObjectReference::operator =(Reference&& other) { + static_cast*>(this)->operator=(std::move(other)); + return *this; +} + +inline ObjectReference::ObjectReference(ObjectReference&& other) + : Reference(std::move(other)) { +} + +inline ObjectReference& ObjectReference::operator =(ObjectReference&& other) { + static_cast*>(this)->operator=(std::move(other)); + return *this; +} + +inline ObjectReference::ObjectReference(const ObjectReference& other) + : Reference(other) { +} + +inline Napi::Value ObjectReference::Get(const char* utf8name) const { + EscapableHandleScope scope(_env); + return scope.Escape(Value().Get(utf8name)); +} + +inline Napi::Value ObjectReference::Get(const std::string& utf8name) const { + EscapableHandleScope scope(_env); + return scope.Escape(Value().Get(utf8name)); +} + +inline void ObjectReference::Set(const char* utf8name, napi_value value) { + HandleScope scope(_env); + Value().Set(utf8name, value); +} + +inline void ObjectReference::Set(const char* utf8name, Napi::Value value) { + HandleScope scope(_env); + Value().Set(utf8name, value); +} + +inline void ObjectReference::Set(const char* utf8name, const char* utf8value) { + HandleScope scope(_env); + Value().Set(utf8name, utf8value); +} + +inline void ObjectReference::Set(const char* utf8name, bool boolValue) { + HandleScope scope(_env); + Value().Set(utf8name, boolValue); +} + +inline void ObjectReference::Set(const char* utf8name, double numberValue) { + HandleScope scope(_env); + Value().Set(utf8name, numberValue); +} + +inline void ObjectReference::Set(const std::string& utf8name, napi_value value) { + HandleScope scope(_env); + Value().Set(utf8name, value); +} + +inline void ObjectReference::Set(const std::string& utf8name, Napi::Value value) { + HandleScope scope(_env); + Value().Set(utf8name, value); +} + +inline void ObjectReference::Set(const std::string& utf8name, std::string& utf8value) { + HandleScope scope(_env); + Value().Set(utf8name, utf8value); +} + +inline void ObjectReference::Set(const std::string& utf8name, bool boolValue) { + HandleScope scope(_env); + Value().Set(utf8name, boolValue); +} + +inline void ObjectReference::Set(const std::string& utf8name, double numberValue) { + HandleScope scope(_env); + Value().Set(utf8name, numberValue); +} + +inline Napi::Value ObjectReference::Get(uint32_t index) const { + EscapableHandleScope scope(_env); + return scope.Escape(Value().Get(index)); +} + +inline void ObjectReference::Set(uint32_t index, napi_value value) { + HandleScope scope(_env); + Value().Set(index, value); +} + +inline void ObjectReference::Set(uint32_t index, Napi::Value value) { + HandleScope scope(_env); + Value().Set(index, value); +} + +inline void ObjectReference::Set(uint32_t index, const char* utf8value) { + HandleScope scope(_env); + Value().Set(index, utf8value); +} + +inline void ObjectReference::Set(uint32_t index, const std::string& utf8value) { + HandleScope scope(_env); + Value().Set(index, utf8value); +} + +inline void ObjectReference::Set(uint32_t index, bool boolValue) { + HandleScope scope(_env); + Value().Set(index, boolValue); +} + +inline void ObjectReference::Set(uint32_t index, double numberValue) { + HandleScope scope(_env); + Value().Set(index, numberValue); +} + +//////////////////////////////////////////////////////////////////////////////// +// FunctionReference class +//////////////////////////////////////////////////////////////////////////////// + +inline FunctionReference::FunctionReference(): Reference() { +} + +inline FunctionReference::FunctionReference(napi_env env, napi_ref ref) + : Reference(env, ref) { +} + +inline FunctionReference::FunctionReference(Reference&& other) + : Reference(std::move(other)) { +} + +inline FunctionReference& FunctionReference::operator =(Reference&& other) { + static_cast*>(this)->operator=(std::move(other)); + return *this; +} + +inline FunctionReference::FunctionReference(FunctionReference&& other) + : Reference(std::move(other)) { +} + +inline FunctionReference& FunctionReference::operator =(FunctionReference&& other) { + static_cast*>(this)->operator=(std::move(other)); + return *this; +} + +inline Napi::Value FunctionReference::operator ()( + const std::initializer_list& args) const { + EscapableHandleScope scope(_env); + return scope.Escape(Value()(args)); +} + +inline Napi::Value FunctionReference::Call(const std::initializer_list& args) const { + EscapableHandleScope scope(_env); + Napi::Value result = Value().Call(args); + if (scope.Env().IsExceptionPending()) { + return Value(); + } + return scope.Escape(result); +} + +inline Napi::Value FunctionReference::Call(const std::vector& args) const { + EscapableHandleScope scope(_env); + Napi::Value result = Value().Call(args); + if (scope.Env().IsExceptionPending()) { + return Value(); + } + return scope.Escape(result); +} + +inline Napi::Value FunctionReference::Call( + napi_value recv, const std::initializer_list& args) const { + EscapableHandleScope scope(_env); + Napi::Value result = Value().Call(recv, args); + if (scope.Env().IsExceptionPending()) { + return Value(); + } + return scope.Escape(result); +} + +inline Napi::Value FunctionReference::Call( + napi_value recv, const std::vector& args) const { + EscapableHandleScope scope(_env); + Napi::Value result = Value().Call(recv, args); + if (scope.Env().IsExceptionPending()) { + return Value(); + } + return scope.Escape(result); +} + +inline Napi::Value FunctionReference::Call( + napi_value recv, size_t argc, const napi_value* args) const { + EscapableHandleScope scope(_env); + Napi::Value result = Value().Call(recv, argc, args); + if (scope.Env().IsExceptionPending()) { + return Value(); + } + return scope.Escape(result); +} + +//inline Napi::Value FunctionReference::MakeCallback( +// napi_value recv, +// const std::initializer_list& args, +// napi_async_context context) const { +// EscapableHandleScope scope(_env); +// Napi::Value result = Value().MakeCallback(recv, args, context); +// if (scope.Env().IsExceptionPending()) { +// return Value(); +// } +// return scope.Escape(result); +//} +// +//inline Napi::Value FunctionReference::MakeCallback( +// napi_value recv, +// const std::vector& args, +// napi_async_context context) const { +// EscapableHandleScope scope(_env); +// Napi::Value result = Value().MakeCallback(recv, args, context); +// if (scope.Env().IsExceptionPending()) { +// return Value(); +// } +// return scope.Escape(result); +//} +// +//inline Napi::Value FunctionReference::MakeCallback( +// napi_value recv, +// size_t argc, +// const napi_value* args, +// napi_async_context context) const { +// EscapableHandleScope scope(_env); +// Napi::Value result = Value().MakeCallback(recv, argc, args, context); +// if (scope.Env().IsExceptionPending()) { +// return Value(); +// } +// return scope.Escape(result); +//} + +inline Object FunctionReference::New(const std::initializer_list& args) const { + EscapableHandleScope scope(_env); + return scope.Escape(Value().New(args)).As(); +} + +inline Object FunctionReference::New(const std::vector& args) const { + EscapableHandleScope scope(_env); + return scope.Escape(Value().New(args)).As(); +} + +//////////////////////////////////////////////////////////////////////////////// +// CallbackInfo class +//////////////////////////////////////////////////////////////////////////////// + +inline CallbackInfo::CallbackInfo(napi_env env, napi_callback_info info) + : _env(env), _info(info), _this(nullptr), _dynamicArgs(nullptr), _data(nullptr) { + _argc = _staticArgCount; + _argv = _staticArgs; + napi_status status = napi_get_cb_info(env, info, &_argc, _argv, &_this, &_data); + NAPI_THROW_IF_FAILED_VOID(_env, status); + + if (_argc > _staticArgCount) { + // Use either a fixed-size array (on the stack) or a dynamically-allocated + // array (on the heap) depending on the number of args. + _dynamicArgs = new napi_value[_argc]; + _argv = _dynamicArgs; + + status = napi_get_cb_info(env, info, &_argc, _argv, nullptr, nullptr); + NAPI_THROW_IF_FAILED_VOID(_env, status); + } +} + +inline CallbackInfo::~CallbackInfo() { + if (_dynamicArgs != nullptr) { + delete[] _dynamicArgs; + } +} + +inline Value CallbackInfo::NewTarget() const { + napi_value newTarget; + napi_status status = napi_get_new_target(_env, _info, &newTarget); + NAPI_THROW_IF_FAILED(_env, status, Value()); + return Value(_env, newTarget); +} + +inline bool CallbackInfo::IsConstructCall() const { + return !NewTarget().IsEmpty(); +} + +inline Napi::Env CallbackInfo::Env() const { + return Napi::Env(_env); +} + +inline size_t CallbackInfo::Length() const { + return _argc; +} + +inline const Value CallbackInfo::operator [](size_t index) const { + return index < _argc ? Value(_env, _argv[index]) : Env().Undefined(); +} + +inline Value CallbackInfo::This() const { + if (_this == nullptr) { + return Env().Undefined(); + } + return Object(_env, _this); +} + +inline void* CallbackInfo::Data() const { + return _data; +} + +inline void CallbackInfo::SetData(void* data) { + _data = data; +} + +//////////////////////////////////////////////////////////////////////////////// +// PropertyDescriptor class +//////////////////////////////////////////////////////////////////////////////// + +template +inline PropertyDescriptor +PropertyDescriptor::Accessor(Napi::Env env, + Napi::Object object, + const char* utf8name, + Getter getter, + napi_property_attributes attributes, + void* /*data*/) { + typedef details::CallbackData CbData; + auto callbackData = new CbData({ getter, nullptr }); + + napi_status status = AttachData(env, object, callbackData); + NAPI_THROW_IF_FAILED(env, status, napi_property_descriptor()); + + return PropertyDescriptor({ + utf8name, + nullptr, + nullptr, + CbData::Wrapper, + nullptr, + nullptr, + attributes, + callbackData + }); +} + +template +inline PropertyDescriptor PropertyDescriptor::Accessor(Napi::Env env, + Napi::Object object, + const std::string& utf8name, + Getter getter, + napi_property_attributes attributes, + void* data) { + return Accessor(env, object, utf8name.c_str(), getter, attributes, data); +} + +template +inline PropertyDescriptor PropertyDescriptor::Accessor(Napi::Env env, + Napi::Object object, + Name name, + Getter getter, + napi_property_attributes attributes, + void* /*data*/) { + typedef details::CallbackData CbData; + auto callbackData = new CbData({ getter, nullptr }); + + napi_status status = AttachData(env, object, callbackData); + NAPI_THROW_IF_FAILED(env, status, napi_property_descriptor()); + + return PropertyDescriptor({ + nullptr, + name, + nullptr, + CbData::Wrapper, + nullptr, + nullptr, + attributes, + callbackData + }); +} + +template +inline PropertyDescriptor PropertyDescriptor::Accessor(Napi::Env env, + Napi::Object object, + const char* utf8name, + Getter getter, + Setter setter, + napi_property_attributes attributes, + void* /*data*/) { + typedef details::AccessorCallbackData CbData; + auto callbackData = new CbData({ getter, setter }); + + napi_status status = AttachData(env, object, callbackData); + NAPI_THROW_IF_FAILED(env, status, napi_property_descriptor()); + + return PropertyDescriptor({ + utf8name, + nullptr, + nullptr, + CbData::GetterWrapper, + CbData::SetterWrapper, + nullptr, + attributes, + callbackData + }); +} + +template +inline PropertyDescriptor PropertyDescriptor::Accessor(Napi::Env env, + Napi::Object object, + const std::string& utf8name, + Getter getter, + Setter setter, + napi_property_attributes attributes, + void* data) { + return Accessor(env, object, utf8name.c_str(), getter, setter, attributes, data); +} + +template +inline PropertyDescriptor PropertyDescriptor::Accessor(Napi::Env env, + Napi::Object object, + Name name, + Getter getter, + Setter setter, + napi_property_attributes attributes, + void* /*data*/) { + typedef details::AccessorCallbackData CbData; + auto callbackData = new CbData({ getter, setter }); + + napi_status status = AttachData(env, object, callbackData); + NAPI_THROW_IF_FAILED(env, status, napi_property_descriptor()); + + return PropertyDescriptor({ + nullptr, + name, + nullptr, + CbData::GetterWrapper, + CbData::SetterWrapper, + nullptr, + attributes, + callbackData + }); +} + +template +inline PropertyDescriptor PropertyDescriptor::Function(Napi::Env env, + Napi::Object /*object*/, + const char* utf8name, + Callable cb, + napi_property_attributes attributes, + void* data) { + return PropertyDescriptor({ + utf8name, + nullptr, + nullptr, + nullptr, + nullptr, + Napi::Function::New(env, cb, utf8name, data), + attributes, + nullptr + }); +} + +template +inline PropertyDescriptor PropertyDescriptor::Function(Napi::Env env, + Napi::Object object, + const std::string& utf8name, + Callable cb, + napi_property_attributes attributes, + void* data) { + return Function(env, object, utf8name.c_str(), cb, attributes, data); +} + +template +inline PropertyDescriptor PropertyDescriptor::Function(Napi::Env env, + Napi::Object /*object*/, + Name name, + Callable cb, + napi_property_attributes attributes, + void* data) { + return PropertyDescriptor({ + nullptr, + name, + nullptr, + nullptr, + nullptr, + Napi::Function::New(env, cb, nullptr, data), + attributes, + nullptr + }); +} + +inline PropertyDescriptor PropertyDescriptor::Value(const char* utf8name, + napi_value value, + napi_property_attributes attributes) { + return PropertyDescriptor({ + utf8name, nullptr, nullptr, nullptr, nullptr, value, attributes, nullptr + }); +} + +inline PropertyDescriptor PropertyDescriptor::Value(const std::string& utf8name, + napi_value value, + napi_property_attributes attributes) { + return Value(utf8name.c_str(), value, attributes); +} + +inline PropertyDescriptor PropertyDescriptor::Value(napi_value name, + napi_value value, + napi_property_attributes attributes) { + return PropertyDescriptor({ + nullptr, name, nullptr, nullptr, nullptr, value, attributes, nullptr + }); +} + +inline PropertyDescriptor PropertyDescriptor::Value(Name name, + Napi::Value value, + napi_property_attributes attributes) { + napi_value nameValue = name; + napi_value valueValue = value; + return PropertyDescriptor::Value(nameValue, valueValue, attributes); +} + +inline PropertyDescriptor::PropertyDescriptor(napi_property_descriptor desc) + : _desc(desc) { +} + +inline PropertyDescriptor::operator napi_property_descriptor&() { + return _desc; +} + +inline PropertyDescriptor::operator const napi_property_descriptor&() const { + return _desc; +} + +//////////////////////////////////////////////////////////////////////////////// +// ObjectWrap class +//////////////////////////////////////////////////////////////////////////////// + +template +inline ObjectWrap::ObjectWrap(const Napi::CallbackInfo& callbackInfo) { + napi_env env = callbackInfo.Env(); + napi_value wrapper = callbackInfo.This(); + napi_status status; + napi_ref ref; + T* instance = static_cast(this); + status = napi_wrap(env, wrapper, instance, FinalizeCallback, nullptr, &ref); + NAPI_THROW_IF_FAILED_VOID(env, status); + + Reference* instanceRef = instance; + *instanceRef = Reference(env, ref); +} + +template +inline T* ObjectWrap::Unwrap(Object wrapper) { + T* unwrapped; + napi_status status = napi_unwrap(wrapper.Env(), wrapper, reinterpret_cast(&unwrapped)); + NAPI_THROW_IF_FAILED(wrapper.Env(), status, nullptr); + return unwrapped; +} + +template +inline Function +ObjectWrap::DefineClass(Napi::Env env, + const char* utf8name, + const size_t props_count, + const napi_property_descriptor* descriptors, + void* data) { + napi_status status; + std::vector props(props_count); + + // We copy the descriptors to a local array because before defining the class + // we must replace static method property descriptors with value property + // descriptors such that the value is a function-valued `napi_value` created + // with `CreateFunction()`. + // + // This replacement could be made for instance methods as well, but V8 aborts + // if we do that, because it expects methods defined on the prototype template + // to have `FunctionTemplate`s. + for (size_t index = 0; index < props_count; index++) { + props[index] = descriptors[index]; + napi_property_descriptor* prop = &props[index]; + if (prop->method == T::StaticMethodCallbackWrapper) { + status = CreateFunction(env, + utf8name, + prop->method, + static_cast(prop->data), + &(prop->value)); + NAPI_THROW_IF_FAILED(env, status, Function()); + prop->method = nullptr; + prop->data = nullptr; + } else if (prop->method == T::StaticVoidMethodCallbackWrapper) { + status = CreateFunction(env, + utf8name, + prop->method, + static_cast(prop->data), + &(prop->value)); + NAPI_THROW_IF_FAILED(env, status, Function()); + prop->method = nullptr; + prop->data = nullptr; + } + } + + napi_value value; + status = napi_define_class(env, + utf8name, + NAPI_AUTO_LENGTH, + T::ConstructorCallbackWrapper, + data, + props_count, + props.data(), + &value); + NAPI_THROW_IF_FAILED(env, status, Function()); + + // After defining the class we iterate once more over the property descriptors + // and attach the data associated with accessors and instance methods to the + // newly created JavaScript class. + for (size_t idx = 0; idx < props_count; idx++) { + const napi_property_descriptor* prop = &props[idx]; + + if (prop->getter == T::StaticGetterCallbackWrapper || + prop->setter == T::StaticSetterCallbackWrapper) { + status = Napi::details::AttachData(env, + value, + static_cast(prop->data)); + NAPI_THROW_IF_FAILED(env, status, Function()); + } else if (prop->getter == T::InstanceGetterCallbackWrapper || + prop->setter == T::InstanceSetterCallbackWrapper) { + status = Napi::details::AttachData(env, + value, + static_cast(prop->data)); + NAPI_THROW_IF_FAILED(env, status, Function()); + } else if (prop->method != nullptr && !(prop->attributes & napi_static)) { + if (prop->method == T::InstanceVoidMethodCallbackWrapper) { + status = Napi::details::AttachData(env, + value, + static_cast(prop->data)); + NAPI_THROW_IF_FAILED(env, status, Function()); + } else if (prop->method == T::InstanceMethodCallbackWrapper) { + status = Napi::details::AttachData(env, + value, + static_cast(prop->data)); + NAPI_THROW_IF_FAILED(env, status, Function()); + } + } + } + + return Function(env, value); +} + +template +inline Function ObjectWrap::DefineClass( + Napi::Env env, + const char* utf8name, + const std::initializer_list>& properties, + void* data) { + return DefineClass(env, + utf8name, + properties.size(), + reinterpret_cast(properties.begin()), + data); +} + +template +inline Function ObjectWrap::DefineClass( + Napi::Env env, + const char* utf8name, + const std::vector>& properties, + void* data) { + return DefineClass(env, + utf8name, + properties.size(), + reinterpret_cast(properties.data()), + data); +} + +template +inline ClassPropertyDescriptor ObjectWrap::StaticMethod( + const char* utf8name, + StaticVoidMethodCallback method, + napi_property_attributes attributes, + void* data) { + StaticVoidMethodCallbackData* callbackData = new StaticVoidMethodCallbackData({ method, data }); + + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.method = T::StaticVoidMethodCallbackWrapper; + desc.data = callbackData; + desc.attributes = static_cast(attributes | napi_static); + return desc; +} + +template +inline ClassPropertyDescriptor ObjectWrap::StaticMethod( + const char* utf8name, + StaticMethodCallback method, + napi_property_attributes attributes, + void* data) { + StaticMethodCallbackData* callbackData = new StaticMethodCallbackData({ method, data }); + + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.method = T::StaticMethodCallbackWrapper; + desc.data = callbackData; + desc.attributes = static_cast(attributes | napi_static); + return desc; +} + +template +inline ClassPropertyDescriptor ObjectWrap::StaticMethod( + Symbol name, + StaticVoidMethodCallback method, + napi_property_attributes attributes, + void* data) { + StaticVoidMethodCallbackData* callbackData = new StaticVoidMethodCallbackData({ method, data }); + + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.method = T::StaticVoidMethodCallbackWrapper; + desc.data = callbackData; + desc.attributes = static_cast(attributes | napi_static); + return desc; +} + +template +inline ClassPropertyDescriptor ObjectWrap::StaticMethod( + Symbol name, + StaticMethodCallback method, + napi_property_attributes attributes, + void* data) { + StaticMethodCallbackData* callbackData = new StaticMethodCallbackData({ method, data }); + + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.method = T::StaticMethodCallbackWrapper; + desc.data = callbackData; + desc.attributes = static_cast(attributes | napi_static); + return desc; +} + +template +inline ClassPropertyDescriptor ObjectWrap::StaticAccessor( + const char* utf8name, + StaticGetterCallback getter, + StaticSetterCallback setter, + napi_property_attributes attributes, + void* data) { + StaticAccessorCallbackData* callbackData = + new StaticAccessorCallbackData({ getter, setter, data }); + + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.getter = getter != nullptr ? T::StaticGetterCallbackWrapper : nullptr; + desc.setter = setter != nullptr ? T::StaticSetterCallbackWrapper : nullptr; + desc.data = callbackData; + desc.attributes = static_cast(attributes | napi_static); + return desc; +} + +template +inline ClassPropertyDescriptor ObjectWrap::StaticAccessor( + Symbol name, + StaticGetterCallback getter, + StaticSetterCallback setter, + napi_property_attributes attributes, + void* data) { + StaticAccessorCallbackData* callbackData = + new StaticAccessorCallbackData({ getter, setter, data }); + + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.getter = getter != nullptr ? T::StaticGetterCallbackWrapper : nullptr; + desc.setter = setter != nullptr ? T::StaticSetterCallbackWrapper : nullptr; + desc.data = callbackData; + desc.attributes = static_cast(attributes | napi_static); + return desc; +} + +template +inline ClassPropertyDescriptor ObjectWrap::InstanceMethod( + const char* utf8name, + InstanceVoidMethodCallback method, + napi_property_attributes attributes, + void* data) { + InstanceVoidMethodCallbackData* callbackData = + new InstanceVoidMethodCallbackData({ method, data}); + + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.method = T::InstanceVoidMethodCallbackWrapper; + desc.data = callbackData; + desc.attributes = attributes; + return desc; +} + +template +inline ClassPropertyDescriptor ObjectWrap::InstanceMethod( + const char* utf8name, + InstanceMethodCallback method, + napi_property_attributes attributes, + void* data) { + InstanceMethodCallbackData* callbackData = new InstanceMethodCallbackData({ method, data }); + + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.method = T::InstanceMethodCallbackWrapper; + desc.data = callbackData; + desc.attributes = attributes; + return desc; +} + +template +inline ClassPropertyDescriptor ObjectWrap::InstanceMethod( + Symbol name, + InstanceVoidMethodCallback method, + napi_property_attributes attributes, + void* data) { + InstanceVoidMethodCallbackData* callbackData = + new InstanceVoidMethodCallbackData({ method, data}); + + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.method = T::InstanceVoidMethodCallbackWrapper; + desc.data = callbackData; + desc.attributes = attributes; + return desc; +} + +template +inline ClassPropertyDescriptor ObjectWrap::InstanceMethod( + Symbol name, + InstanceMethodCallback method, + napi_property_attributes attributes, + void* data) { + InstanceMethodCallbackData* callbackData = new InstanceMethodCallbackData({ method, data }); + + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.method = T::InstanceMethodCallbackWrapper; + desc.data = callbackData; + desc.attributes = attributes; + return desc; +} + +template +inline ClassPropertyDescriptor ObjectWrap::InstanceAccessor( + const char* utf8name, + InstanceGetterCallback getter, + InstanceSetterCallback setter, + napi_property_attributes attributes, + void* data) { + InstanceAccessorCallbackData* callbackData = + new InstanceAccessorCallbackData({ getter, setter, data }); + + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.getter = getter != nullptr ? T::InstanceGetterCallbackWrapper : nullptr; + desc.setter = setter != nullptr ? T::InstanceSetterCallbackWrapper : nullptr; + desc.data = callbackData; + desc.attributes = attributes; + return desc; +} + +template +inline ClassPropertyDescriptor ObjectWrap::InstanceAccessor( + Symbol name, + InstanceGetterCallback getter, + InstanceSetterCallback setter, + napi_property_attributes attributes, + void* data) { + InstanceAccessorCallbackData* callbackData = + new InstanceAccessorCallbackData({ getter, setter, data }); + + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.getter = getter != nullptr ? T::InstanceGetterCallbackWrapper : nullptr; + desc.setter = setter != nullptr ? T::InstanceSetterCallbackWrapper : nullptr; + desc.data = callbackData; + desc.attributes = attributes; + return desc; +} + +template +inline ClassPropertyDescriptor ObjectWrap::StaticValue(const char* utf8name, + Napi::Value value, napi_property_attributes attributes) { + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.value = value; + desc.attributes = static_cast(attributes | napi_static); + return desc; +} + +template +inline ClassPropertyDescriptor ObjectWrap::StaticValue(Symbol name, + Napi::Value value, napi_property_attributes attributes) { + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.value = value; + desc.attributes = static_cast(attributes | napi_static); + return desc; +} + +template +inline ClassPropertyDescriptor ObjectWrap::InstanceValue( + const char* utf8name, + Napi::Value value, + napi_property_attributes attributes) { + napi_property_descriptor desc = napi_property_descriptor(); + desc.utf8name = utf8name; + desc.value = value; + desc.attributes = attributes; + return desc; +} + +template +inline ClassPropertyDescriptor ObjectWrap::InstanceValue( + Symbol name, + Napi::Value value, + napi_property_attributes attributes) { + napi_property_descriptor desc = napi_property_descriptor(); + desc.name = name; + desc.value = value; + desc.attributes = attributes; + return desc; +} + +template +inline napi_value ObjectWrap::ConstructorCallbackWrapper( + napi_env env, + napi_callback_info info) { + napi_value new_target; + napi_status status = napi_get_new_target(env, info, &new_target); + if (status != napi_ok) return nullptr; + + bool isConstructCall = (new_target != nullptr); + if (!isConstructCall) { + napi_throw_type_error(env, nullptr, "Class constructors cannot be invoked without 'new'"); + return nullptr; + } + + T* instance; + napi_value wrapper = details::WrapCallback([&] { + CallbackInfo callbackInfo(env, info); + instance = new T(callbackInfo); + return callbackInfo.This(); + }); + + return wrapper; +} + +template +inline napi_value ObjectWrap::StaticVoidMethodCallbackWrapper( + napi_env env, + napi_callback_info info) { + return details::WrapCallback([&] { + CallbackInfo callbackInfo(env, info); + StaticVoidMethodCallbackData* callbackData = + reinterpret_cast(callbackInfo.Data()); + callbackInfo.SetData(callbackData->data); + callbackData->callback(callbackInfo); + return nullptr; + }); +} + +template +inline napi_value ObjectWrap::StaticMethodCallbackWrapper( + napi_env env, + napi_callback_info info) { + return details::WrapCallback([&] { + CallbackInfo callbackInfo(env, info); + StaticMethodCallbackData* callbackData = + reinterpret_cast(callbackInfo.Data()); + callbackInfo.SetData(callbackData->data); + return callbackData->callback(callbackInfo); + }); +} + +template +inline napi_value ObjectWrap::StaticGetterCallbackWrapper( + napi_env env, + napi_callback_info info) { + return details::WrapCallback([&] { + CallbackInfo callbackInfo(env, info); + StaticAccessorCallbackData* callbackData = + reinterpret_cast(callbackInfo.Data()); + callbackInfo.SetData(callbackData->data); + return callbackData->getterCallback(callbackInfo); + }); +} + +template +inline napi_value ObjectWrap::StaticSetterCallbackWrapper( + napi_env env, + napi_callback_info info) { + return details::WrapCallback([&] { + CallbackInfo callbackInfo(env, info); + StaticAccessorCallbackData* callbackData = + reinterpret_cast(callbackInfo.Data()); + callbackInfo.SetData(callbackData->data); + callbackData->setterCallback(callbackInfo, callbackInfo[0]); + return nullptr; + }); +} + +template +inline napi_value ObjectWrap::InstanceVoidMethodCallbackWrapper( + napi_env env, + napi_callback_info info) { + return details::WrapCallback([&] { + CallbackInfo callbackInfo(env, info); + InstanceVoidMethodCallbackData* callbackData = + reinterpret_cast(callbackInfo.Data()); + callbackInfo.SetData(callbackData->data); + T* instance = Unwrap(callbackInfo.This().As()); + auto cb = callbackData->callback; + (instance->*cb)(callbackInfo); + return nullptr; + }); +} + +template +inline napi_value ObjectWrap::InstanceMethodCallbackWrapper( + napi_env env, + napi_callback_info info) { + return details::WrapCallback([&] { + CallbackInfo callbackInfo(env, info); + InstanceMethodCallbackData* callbackData = + reinterpret_cast(callbackInfo.Data()); + callbackInfo.SetData(callbackData->data); + T* instance = Unwrap(callbackInfo.This().As()); + auto cb = callbackData->callback; + return (instance->*cb)(callbackInfo); + }); +} + +template +inline napi_value ObjectWrap::InstanceGetterCallbackWrapper( + napi_env env, + napi_callback_info info) { + return details::WrapCallback([&] { + CallbackInfo callbackInfo(env, info); + InstanceAccessorCallbackData* callbackData = + reinterpret_cast(callbackInfo.Data()); + callbackInfo.SetData(callbackData->data); + T* instance = Unwrap(callbackInfo.This().As()); + auto cb = callbackData->getterCallback; + return (instance->*cb)(callbackInfo); + }); +} + +template +inline napi_value ObjectWrap::InstanceSetterCallbackWrapper( + napi_env env, + napi_callback_info info) { + return details::WrapCallback([&] { + CallbackInfo callbackInfo(env, info); + InstanceAccessorCallbackData* callbackData = + reinterpret_cast(callbackInfo.Data()); + callbackInfo.SetData(callbackData->data); + T* instance = Unwrap(callbackInfo.This().As()); + auto cb = callbackData->setterCallback; + (instance->*cb)(callbackInfo, callbackInfo[0]); + return nullptr; + }); +} + +template +inline void ObjectWrap::FinalizeCallback(napi_env /*env*/, void* data, void* /*hint*/) { + T* instance = reinterpret_cast(data); + delete instance; +} + +//////////////////////////////////////////////////////////////////////////////// +// HandleScope class +//////////////////////////////////////////////////////////////////////////////// + +inline HandleScope::HandleScope(napi_env env, napi_handle_scope scope) + : _env(env), _scope(scope) { +} + +inline HandleScope::HandleScope(Napi::Env env) : _env(env) { + napi_status status = napi_open_handle_scope(_env, &_scope); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline HandleScope::~HandleScope() { + napi_close_handle_scope(_env, _scope); +} + +inline HandleScope::operator napi_handle_scope() const { + return _scope; +} + +inline Napi::Env HandleScope::Env() const { + return Napi::Env(_env); +} + +//////////////////////////////////////////////////////////////////////////////// +// EscapableHandleScope class +//////////////////////////////////////////////////////////////////////////////// + +inline EscapableHandleScope::EscapableHandleScope( + napi_env env, napi_escapable_handle_scope scope) : _env(env), _scope(scope) { +} + +inline EscapableHandleScope::EscapableHandleScope(Napi::Env env) : _env(env) { + napi_status status = napi_open_escapable_handle_scope(_env, &_scope); + NAPI_THROW_IF_FAILED_VOID(_env, status); +} + +inline EscapableHandleScope::~EscapableHandleScope() { + napi_close_escapable_handle_scope(_env, _scope); +} + +inline EscapableHandleScope::operator napi_escapable_handle_scope() const { + return _scope; +} + +inline Napi::Env EscapableHandleScope::Env() const { + return Napi::Env(_env); +} + +inline Value EscapableHandleScope::Escape(napi_value escapee) { + napi_value result; + napi_status status = napi_escape_handle(_env, _scope, escapee, &result); + NAPI_THROW_IF_FAILED(_env, status, Value()); + return Value(_env, result); +} + +////////////////////////////////////////////////////////////////////////////////// +//// AsyncContext class +////////////////////////////////////////////////////////////////////////////////// +// +//inline AsyncContext::AsyncContext(napi_env env, const char* resource_name) +// : AsyncContext(env, resource_name, Object::New(env)) { +//} +// +//inline AsyncContext::AsyncContext(napi_env env, +// const char* resource_name, +// const Object& resource) +// : _env(env), +// _context(nullptr) { +// napi_value resource_id; +// napi_status status = napi_create_string_utf8( +// _env, resource_name, NAPI_AUTO_LENGTH, &resource_id); +// NAPI_THROW_IF_FAILED_VOID(_env, status); +// +// status = napi_async_init(_env, resource, resource_id, &_context); +// NAPI_THROW_IF_FAILED_VOID(_env, status); +//} +// +//inline AsyncContext::~AsyncContext() { +// if (_context != nullptr) { +// napi_async_destroy(_env, _context); +// _context = nullptr; +// } +//} +// +//inline AsyncContext::AsyncContext(AsyncContext&& other) { +// _env = other._env; +// other._env = nullptr; +// _context = other._context; +// other._context = nullptr; +//} +// +//inline AsyncContext& AsyncContext::operator =(AsyncContext&& other) { +// _env = other._env; +// other._env = nullptr; +// _context = other._context; +// other._context = nullptr; +// return *this; +//} +// +//inline AsyncContext::operator napi_async_context() const { +// return _context; +//} +// +////////////////////////////////////////////////////////////////////////////////// +//// AsyncWorker class +////////////////////////////////////////////////////////////////////////////////// +// +//inline AsyncWorker::AsyncWorker(const Function& callback) +// : AsyncWorker(callback, "generic") { +//} +// +//inline AsyncWorker::AsyncWorker(const Function& callback, +// const char* resource_name) +// : AsyncWorker(callback, resource_name, Object::New(callback.Env())) { +//} +// +//inline AsyncWorker::AsyncWorker(const Function& callback, +// const char* resource_name, +// const Object& resource) +// : AsyncWorker(Object::New(callback.Env()), +// callback, +// resource_name, +// resource) { +//} +// +//inline AsyncWorker::AsyncWorker(const Object& receiver, +// const Function& callback) +// : AsyncWorker(receiver, callback, "generic") { +//} +// +//inline AsyncWorker::AsyncWorker(const Object& receiver, +// const Function& callback, +// const char* resource_name) +// : AsyncWorker(receiver, +// callback, +// resource_name, +// Object::New(callback.Env())) { +//} +// +//inline AsyncWorker::AsyncWorker(const Object& receiver, +// const Function& callback, +// const char* resource_name, +// const Object& resource) +// : _env(callback.Env()), +// _receiver(Napi::Persistent(receiver)), +// _callback(Napi::Persistent(callback)) { +// napi_value resource_id; +// napi_status status = napi_create_string_latin1( +// _env, resource_name, NAPI_AUTO_LENGTH, &resource_id); +// NAPI_THROW_IF_FAILED_VOID(_env, status); +// +// status = napi_create_async_work(_env, resource, resource_id, OnExecute, +// OnWorkComplete, this, &_work); +// NAPI_THROW_IF_FAILED_VOID(_env, status); +//} +// +//inline AsyncWorker::~AsyncWorker() { +// if (_work != nullptr) { +// napi_delete_async_work(_env, _work); +// _work = nullptr; +// } +//} +// +//inline AsyncWorker::AsyncWorker(AsyncWorker&& other) { +// _env = other._env; +// other._env = nullptr; +// _work = other._work; +// other._work = nullptr; +// _receiver = std::move(other._receiver); +// _callback = std::move(other._callback); +// _error = std::move(other._error); +//} +// +//inline AsyncWorker& AsyncWorker::operator =(AsyncWorker&& other) { +// _env = other._env; +// other._env = nullptr; +// _work = other._work; +// other._work = nullptr; +// _receiver = std::move(other._receiver); +// _callback = std::move(other._callback); +// _error = std::move(other._error); +// return *this; +//} +// +//inline AsyncWorker::operator napi_async_work() const { +// return _work; +//} +// +//inline Napi::Env AsyncWorker::Env() const { +// return Napi::Env(_env); +//} +// +//inline void AsyncWorker::Queue() { +// napi_status status = napi_queue_async_work(_env, _work); +// NAPI_THROW_IF_FAILED_VOID(_env, status); +//} +// +//inline void AsyncWorker::Cancel() { +// napi_status status = napi_cancel_async_work(_env, _work); +// NAPI_THROW_IF_FAILED_VOID(_env, status); +//} +// +//inline ObjectReference& AsyncWorker::Receiver() { +// return _receiver; +//} +// +//inline FunctionReference& AsyncWorker::Callback() { +// return _callback; +//} +// +//inline void AsyncWorker::OnOK() { +// _callback.MakeCallback(_receiver.Value(), std::initializer_list{}); +//} +// +//inline void AsyncWorker::OnError(const Error& e) { +// _callback.MakeCallback(_receiver.Value(), std::initializer_list{ e.Value() }); +//} +// +//inline void AsyncWorker::SetError(const std::string& error) { +// _error = error; +//} +// +//inline void AsyncWorker::OnExecute(napi_env /*env*/, void* this_pointer) { +// AsyncWorker* self = static_cast(this_pointer); +//#ifdef NAPI_CPP_EXCEPTIONS +// try { +// self->Execute(); +// } catch (const std::exception& e) { +// self->SetError(e.what()); +// } +//#else // NAPI_CPP_EXCEPTIONS +// self->Execute(); +//#endif // NAPI_CPP_EXCEPTIONS +//} +// +//inline void AsyncWorker::OnWorkComplete( +// napi_env /*env*/, napi_status status, void* this_pointer) { +// AsyncWorker* self = static_cast(this_pointer); +// if (status != napi_cancelled) { +// HandleScope scope(self->_env); +// details::WrapCallback([&] { +// if (self->_error.size() == 0) { +// self->OnOK(); +// } +// else { +// self->OnError(Error::New(self->_env, self->_error)); +// } +// return nullptr; +// }); +// } +// delete self; +//} +// +////////////////////////////////////////////////////////////////////////////////// +//// Memory Management class +////////////////////////////////////////////////////////////////////////////////// +// +//inline int64_t MemoryManagement::AdjustExternalMemory(Env env, int64_t change_in_bytes) { +// int64_t result; +// napi_status status = napi_adjust_external_memory(env, change_in_bytes, &result); +// NAPI_THROW_IF_FAILED(env, status, 0); +// return result; +//} +// +////////////////////////////////////////////////////////////////////////////////// +//// Version Management class +////////////////////////////////////////////////////////////////////////////////// +// +//inline uint32_t VersionManagement::GetNapiVersion(Env env) { +// uint32_t result; +// napi_status status = napi_get_version(env, &result); +// NAPI_THROW_IF_FAILED(env, status, 0); +// return result; +//} +// +//inline const napi_node_version* VersionManagement::GetNodeVersion(Env env) { +// const napi_node_version* result; +// napi_status status = napi_get_node_version(env, &result); +// NAPI_THROW_IF_FAILED(env, status, 0); +// return result; +//} + +// These macros shouldn't be useful in user code. +#undef NAPI_THROW +#undef NAPI_THROW_IF_FAILED + +} // namespace Napi + +#endif // SRC_NAPI_INL_H_ diff --git a/Source/Napi/napi.h b/Source/Napi/napi.h new file mode 100644 index 000000000..a16a77490 --- /dev/null +++ b/Source/Napi/napi.h @@ -0,0 +1,1766 @@ +#ifndef SRC_NAPI_H_ +#define SRC_NAPI_H_ + +#include "js_native_api.h" +#include +#include +#include +#include + +// VS2015 RTM has bugs with constexpr, so require min of VS2015 Update 3 (known good version) +#if !defined(_MSC_VER) || _MSC_FULL_VER >= 190024210 +#define NAPI_HAS_CONSTEXPR 1 +#endif + +// VS2013 does not support char16_t literal strings, so we'll work around it using wchar_t strings +// and casting them. This is safe as long as the character sizes are the same. +#if defined(_MSC_VER) && _MSC_VER <= 1800 +static_assert(sizeof(char16_t) == sizeof(wchar_t), "Size mismatch between char16_t and wchar_t"); +#define NAPI_WIDE_TEXT(x) reinterpret_cast(L ## x) +#else +#define NAPI_WIDE_TEXT(x) u ## x +#endif + +// If C++ exceptions are not explicitly enabled or disabled, enable them +// if exceptions were enabled in the compiler settings. +#if !defined(NAPI_CPP_EXCEPTIONS) && !defined(NAPI_DISABLE_CPP_EXCEPTIONS) + #if defined(_CPPUNWIND) || defined (__EXCEPTIONS) + #define NAPI_CPP_EXCEPTIONS + #else + #error Exception support not detected. \ + Define either NAPI_CPP_EXCEPTIONS or NAPI_DISABLE_CPP_EXCEPTIONS. + #endif +#endif + +#ifdef _NOEXCEPT + #define NAPI_NOEXCEPT _NOEXCEPT +#else + #define NAPI_NOEXCEPT noexcept +#endif + +//////////////////////////////////////////////////////////////////////////////// +/// N-API C++ Wrapper Classes +/// +/// These classes wrap the "N-API" ABI-stable C APIs for Node.js, providing a +/// C++ object model and C++ exception-handling semantics with low overhead. +/// The wrappers are all header-only so that they do not affect the ABI. +//////////////////////////////////////////////////////////////////////////////// +namespace Napi { + + // Forward declarations + class Env; + class Value; + class Boolean; + class Number; +// currently experimental guard with version of NAPI_VERSION that it is +// released in once it is no longer experimental +#if (NAPI_VERSION > 2147483646) + class BigInt; +#endif // NAPI_EXPERIMENTAL + class String; + class Object; + class Array; + class Function; + template class Buffer; + class Error; + class PropertyDescriptor; + class CallbackInfo; + template class Reference; + class TypedArray; + template class TypedArrayOf; + + typedef TypedArrayOf Int8Array; ///< Typed-array of signed 8-bit integers + typedef TypedArrayOf Uint8Array; ///< Typed-array of unsigned 8-bit integers + typedef TypedArrayOf Int16Array; ///< Typed-array of signed 16-bit integers + typedef TypedArrayOf Uint16Array; ///< Typed-array of unsigned 16-bit integers + typedef TypedArrayOf Int32Array; ///< Typed-array of signed 32-bit integers + typedef TypedArrayOf Uint32Array; ///< Typed-array of unsigned 32-bit integers + typedef TypedArrayOf Float32Array; ///< Typed-array of 32-bit floating-point values + typedef TypedArrayOf Float64Array; ///< Typed-array of 64-bit floating-point values +// currently experimental guard with version of NAPI_VERSION that it is +// released in once it is no longer experimental +#if (NAPI_VERSION > 2147483646) + typedef TypedArrayOf BigInt64Array; ///< Typed array of signed 64-bit integers + typedef TypedArrayOf BigUint64Array; ///< Typed array of unsigned 64-bit integers +#endif // NAPI_EXPERIMENTAL + + /// Defines the signature of a N-API C++ module's registration callback (init) function. + typedef Object (*ModuleRegisterCallback)(Env env, Object exports); + + class MemoryManagement; + + /// Environment for N-API values and operations. + /// + /// All N-API values and operations must be associated with an environment. An environment + /// instance is always provided to callback functions; that environment must then be used for any + /// creation of N-API values or other N-API operations within the callback. (Many methods infer + /// the environment from the `this` instance that the method is called on.) + /// + /// In the future, multiple environments per process may be supported, although current + /// implementations only support one environment per process. + /// + /// In the V8 JavaScript engine, a N-API environment approximately corresponds to an Isolate. + class Env { + public: + Env(napi_env env); + + operator napi_env() const; + + Object Global() const; + Value Undefined() const; + Value Null() const; + + bool IsExceptionPending() const; + Error GetAndClearPendingException(); + + private: + napi_env _env; + }; + + /// A JavaScript value of unknown type. + /// + /// For type-specific operations, convert to one of the Value subclasses using a `To*` or `As()` + /// method. The `To*` methods do type coercion; the `As()` method does not. + /// + /// Napi::Value value = ... + /// if (!value.IsString()) throw Napi::TypeError::New(env, "Invalid arg..."); + /// Napi::String str = value.As(); // Cast to a string value + /// + /// Napi::Value anotherValue = ... + /// bool isTruthy = anotherValue.ToBoolean(); // Coerce to a boolean value + class Value { + public: + Value(); ///< Creates a new _empty_ Value instance. + Value(napi_env env, napi_value value); ///< Wraps a N-API value primitive. + + /// Creates a JS value from a C++ primitive. + /// + /// `value` may be any of: + /// - bool + /// - Any integer type + /// - Any floating point type + /// - const char* (encoded using UTF-8, null-terminated) + /// - const char16_t* (encoded using UTF-16-LE, null-terminated) + /// - std::string (encoded using UTF-8) + /// - std::u16string + /// - napi::Value + /// - napi_value + template + static Value From(napi_env env, const T& value); + + /// Converts to a N-API value primitive. + /// + /// If the instance is _empty_, this returns `nullptr`. + operator napi_value() const; + + /// Tests if this value strictly equals another value. + bool operator ==(const Value& other) const; + + /// Tests if this value does not strictly equal another value. + bool operator !=(const Value& other) const; + + /// Tests if this value strictly equals another value. + bool StrictEquals(const Value& other) const; + + /// Gets the environment the value is associated with. + Napi::Env Env() const; + + /// Checks if the value is empty (uninitialized). + /// + /// An empty value is invalid, and most attempts to perform an operation on an empty value + /// will result in an exception. Note an empty value is distinct from JavaScript `null` or + /// `undefined`, which are valid values. + /// + /// When C++ exceptions are disabled at compile time, a method with a `Value` return type may + /// return an empty value to indicate a pending exception. So when not using C++ exceptions, + /// callers should check whether the value is empty before attempting to use it. + bool IsEmpty() const; + + napi_valuetype Type() const; ///< Gets the type of the value. + + bool IsUndefined() const; ///< Tests if a value is an undefined JavaScript value. + bool IsNull() const; ///< Tests if a value is a null JavaScript value. + bool IsBoolean() const; ///< Tests if a value is a JavaScript boolean. + bool IsNumber() const; ///< Tests if a value is a JavaScript number. +// currently experimental guard with version of NAPI_VERSION that it is +// released in once it is no longer experimental +#if (NAPI_VERSION > 2147483646) + bool IsBigInt() const; ///< Tests if a value is a JavaScript bigint. +#endif // NAPI_EXPERIMENTAL + bool IsString() const; ///< Tests if a value is a JavaScript string. + bool IsSymbol() const; ///< Tests if a value is a JavaScript symbol. + bool IsArray() const; ///< Tests if a value is a JavaScript array. + bool IsArrayBuffer() const; ///< Tests if a value is a JavaScript array buffer. + bool IsTypedArray() const; ///< Tests if a value is a JavaScript typed array. + bool IsObject() const; ///< Tests if a value is a JavaScript object. + bool IsFunction() const; ///< Tests if a value is a JavaScript function. + bool IsPromise() const; ///< Tests if a value is a JavaScript promise. + bool IsDataView() const; ///< Tests if a value is a JavaScript data view. + //bool IsBuffer() const; ///< Tests if a value is a Node buffer. + bool IsExternal() const; ///< Tests if a value is a pointer to external data. + + /// Casts to another type of `Napi::Value`, when the actual type is known or assumed. + /// + /// This conversion does NOT coerce the type. Calling any methods inappropriate for the actual + /// value type will throw `Napi::Error`. + template T As() const; + + Boolean ToBoolean() const; ///< Coerces a value to a JavaScript boolean. + Number ToNumber() const; ///< Coerces a value to a JavaScript number. + String ToString() const; ///< Coerces a value to a JavaScript string. + Object ToObject() const; ///< Coerces a value to a JavaScript object. + + protected: + /// !cond INTERNAL + napi_env _env; + napi_value _value; + /// !endcond + }; + + /// A JavaScript boolean value. + class Boolean : public Value { + public: + static Boolean New( + napi_env env, ///< N-API environment + bool value ///< Boolean value + ); + + Boolean(); ///< Creates a new _empty_ Boolean instance. + Boolean(napi_env env, napi_value value); ///< Wraps a N-API value primitive. + + operator bool() const; ///< Converts a Boolean value to a boolean primitive. + bool Value() const; ///< Converts a Boolean value to a boolean primitive. + }; + + /// A JavaScript number value. + class Number : public Value { + public: + static Number New( + napi_env env, ///< N-API environment + double value ///< Number value + ); + + Number(); ///< Creates a new _empty_ Number instance. + Number(napi_env env, napi_value value); ///< Wraps a N-API value primitive. + + operator int32_t() const; ///< Converts a Number value to a 32-bit signed integer value. + operator uint32_t() const; ///< Converts a Number value to a 32-bit unsigned integer value. + operator int64_t() const; ///< Converts a Number value to a 64-bit signed integer value. + operator float() const; ///< Converts a Number value to a 32-bit floating-point value. + operator double() const; ///< Converts a Number value to a 64-bit floating-point value. + + int32_t Int32Value() const; ///< Converts a Number value to a 32-bit signed integer value. + uint32_t Uint32Value() const; ///< Converts a Number value to a 32-bit unsigned integer value. + int64_t Int64Value() const; ///< Converts a Number value to a 64-bit signed integer value. + float FloatValue() const; ///< Converts a Number value to a 32-bit floating-point value. + double DoubleValue() const; ///< Converts a Number value to a 64-bit floating-point value. + }; + +// currently experimental guard with version of NAPI_VERSION that it is +// released in once it is no longer experimental +#if (NAPI_VERSION > 2147483646) + /// A JavaScript bigint value. + class BigInt : public Value { + public: + static BigInt New( + napi_env env, ///< N-API environment + int64_t value ///< Number value + ); + static BigInt New( + napi_env env, ///< N-API environment + uint64_t value ///< Number value + ); + + /// Creates a new BigInt object using a specified sign bit and a + /// specified list of digits/words. + /// The resulting number is calculated as: + /// (-1)^sign_bit * (words[0] * (2^64)^0 + words[1] * (2^64)^1 + ...) + static BigInt New( + napi_env env, ///< N-API environment + int sign_bit, ///< Sign bit. 1 if negative. + size_t word_count, ///< Number of words in array + const uint64_t* words ///< Array of words + ); + + BigInt(); ///< Creates a new _empty_ BigInt instance. + BigInt(napi_env env, napi_value value); ///< Wraps a N-API value primitive. + + int64_t Int64Value(bool* lossless) const; ///< Converts a BigInt value to a 64-bit signed integer value. + uint64_t Uint64Value(bool* lossless) const; ///< Converts a BigInt value to a 64-bit unsigned integer value. + + size_t WordCount() const; ///< The number of 64-bit words needed to store the result of ToWords(). + + /// Writes the contents of this BigInt to a specified memory location. + /// `sign_bit` must be provided and will be set to 1 if this BigInt is negative. + /// `*word_count` has to be initialized to the length of the `words` array. + /// Upon return, it will be set to the actual number of words that would + /// be needed to store this BigInt (i.e. the return value of `WordCount()`). + void ToWords(int* sign_bit, size_t* word_count, uint64_t* words); + }; +#endif // NAPI_EXPERIMENTAL + + /// A JavaScript string or symbol value (that can be used as a property name). + class Name : public Value { + public: + Name(); ///< Creates a new _empty_ Name instance. + Name(napi_env env, napi_value value); ///< Wraps a N-API value primitive. + }; + + /// A JavaScript string value. + class String : public Name { + public: + /// Creates a new String value from a UTF-8 encoded C++ string. + static String New( + napi_env env, ///< N-API environment + const std::string& value ///< UTF-8 encoded C++ string + ); + + /// Creates a new String value from a UTF-16 encoded C++ string. + static String New( + napi_env env, ///< N-API environment + const std::u16string& value ///< UTF-16 encoded C++ string + ); + + /// Creates a new String value from a UTF-8 encoded C string. + static String New( + napi_env env, ///< N-API environment + const char* value ///< UTF-8 encoded null-terminated C string + ); + + /// Creates a new String value from a UTF-16 encoded C string. + static String New( + napi_env env, ///< N-API environment + const char16_t* value ///< UTF-16 encoded null-terminated C string + ); + + /// Creates a new String value from a UTF-8 encoded C string with specified length. + static String New( + napi_env env, ///< N-API environment + const char* value, ///< UTF-8 encoded C string (not necessarily null-terminated) + size_t length ///< length of the string in bytes + ); + + /// Creates a new String value from a UTF-16 encoded C string with specified length. + static String New( + napi_env env, ///< N-API environment + const char16_t* value, ///< UTF-16 encoded C string (not necessarily null-terminated) + size_t length ///< Length of the string in 2-byte code units + ); + + /// Creates a new String based on the original object's type. + /// + /// `value` may be any of: + /// - const char* (encoded using UTF-8, null-terminated) + /// - const char16_t* (encoded using UTF-16-LE, null-terminated) + /// - std::string (encoded using UTF-8) + /// - std::u16string + template + static String From(napi_env env, const T& value); + + String(); ///< Creates a new _empty_ String instance. + String(napi_env env, napi_value value); ///< Wraps a N-API value primitive. + + operator std::string() const; ///< Converts a String value to a UTF-8 encoded C++ string. + operator std::u16string() const; ///< Converts a String value to a UTF-16 encoded C++ string. + std::string Utf8Value() const; ///< Converts a String value to a UTF-8 encoded C++ string. + std::u16string Utf16Value() const; ///< Converts a String value to a UTF-16 encoded C++ string. + }; + + /// A JavaScript symbol value. + class Symbol : public Name { + public: + /// Creates a new Symbol value with an optional description. + static Symbol New( + napi_env env, ///< N-API environment + const char* description = nullptr ///< Optional UTF-8 encoded null-terminated C string + /// describing the symbol + ); + + /// Creates a new Symbol value with a description. + static Symbol New( + napi_env env, ///< N-API environment + const std::string& description ///< UTF-8 encoded C++ string describing the symbol + ); + + /// Creates a new Symbol value with a description. + static Symbol New( + napi_env env, ///< N-API environment + String description ///< String value describing the symbol + ); + + /// Creates a new Symbol value with a description. + static Symbol New( + napi_env env, ///< N-API environment + napi_value description ///< String value describing the symbol + ); + + /// Get a public Symbol (e.g. Symbol.iterator). + static Symbol WellKnown(napi_env, const std::string& name); + + Symbol(); ///< Creates a new _empty_ Symbol instance. + Symbol(napi_env env, napi_value value); ///< Wraps a N-API value primitive. + }; + + /// A JavaScript object value. + class Object : public Value { + public: + /// Enables property and element assignments using indexing syntax. + /// + /// Example: + /// + /// Napi::Value propertyValue = object1['A']; + /// object2['A'] = propertyValue; + /// Napi::Value elementValue = array[0]; + /// array[1] = elementValue; + template + class PropertyLValue { + public: + /// Converts an L-value to a value. + operator Value() const; + + /// Assigns a value to the property. The type of value can be + /// anything supported by `Object::Set`. + template + PropertyLValue& operator =(ValueType value); + + private: + PropertyLValue() = delete; + PropertyLValue(Object object, Key key); + napi_env _env; + napi_value _object; + Key _key; + + friend class Napi::Object; + }; + + /// Creates a new Object value. + static Object New( + napi_env env ///< N-API environment + ); + + Object(); ///< Creates a new _empty_ Object instance. + Object(napi_env env, napi_value value); ///< Wraps a N-API value primitive. + + /// Gets or sets a named property. + PropertyLValue operator []( + const char* utf8name ///< UTF-8 encoded null-terminated property name + ); + + /// Gets or sets a named property. + PropertyLValue operator []( + const std::string& utf8name ///< UTF-8 encoded property name + ); + + /// Gets or sets an indexed property or array element. + PropertyLValue operator []( + uint32_t index /// Property / element index + ); + + /// Gets a named property. + Value operator []( + const char* utf8name ///< UTF-8 encoded null-terminated property name + ) const; + + /// Gets a named property. + Value operator []( + const std::string& utf8name ///< UTF-8 encoded property name + ) const; + + /// Gets an indexed property or array element. + Value operator []( + uint32_t index ///< Property / element index + ) const; + + /// Checks whether a property is present. + bool Has( + napi_value key ///< Property key primitive + ) const; + + /// Checks whether a property is present. + bool Has( + Value key ///< Property key + ) const; + + /// Checks whether a named property is present. + bool Has( + const char* utf8name ///< UTF-8 encoded null-terminated property name + ) const; + + /// Checks whether a named property is present. + bool Has( + const std::string& utf8name ///< UTF-8 encoded property name + ) const; + + /// Checks whether a own property is present. + bool HasOwnProperty( + napi_value key ///< Property key primitive + ) const; + + /// Checks whether a own property is present. + bool HasOwnProperty( + Value key ///< Property key + ) const; + + /// Checks whether a own property is present. + bool HasOwnProperty( + const char* utf8name ///< UTF-8 encoded null-terminated property name + ) const; + + /// Checks whether a own property is present. + bool HasOwnProperty( + const std::string& utf8name ///< UTF-8 encoded property name + ) const; + + /// Gets a property. + Value Get( + napi_value key ///< Property key primitive + ) const; + + /// Gets a property. + Value Get( + Value key ///< Property key + ) const; + + /// Gets a named property. + Value Get( + const char* utf8name ///< UTF-8 encoded null-terminated property name + ) const; + + /// Gets a named property. + Value Get( + const std::string& utf8name ///< UTF-8 encoded property name + ) const; + + /// Sets a property. + template + void Set( + napi_value key, ///< Property key primitive + const ValueType& value ///< Property value primitive + ); + + /// Sets a property. + template + void Set( + Value key, ///< Property key + const ValueType& value ///< Property value + ); + + /// Sets a named property. + template + void Set( + const char* utf8name, ///< UTF-8 encoded null-terminated property name + const ValueType& value + ); + + /// Sets a named property. + template + void Set( + const std::string& utf8name, ///< UTF-8 encoded property name + const ValueType& value ///< Property value primitive + ); + + /// Delete property. + bool Delete( + napi_value key ///< Property key primitive + ); + + /// Delete property. + bool Delete( + Value key ///< Property key + ); + + /// Delete property. + bool Delete( + const char* utf8name ///< UTF-8 encoded null-terminated property name + ); + + /// Delete property. + bool Delete( + const std::string& utf8name ///< UTF-8 encoded property name + ); + + /// Checks whether an indexed property is present. + bool Has( + uint32_t index ///< Property / element index + ) const; + + /// Gets an indexed property or array element. + Value Get( + uint32_t index ///< Property / element index + ) const; + + /// Sets an indexed property or array element. + template + void Set( + uint32_t index, ///< Property / element index + const ValueType& value ///< Property value primitive + ); + + /// Deletes an indexed property or array element. + bool Delete( + uint32_t index ///< Property / element index + ); + + Array GetPropertyNames(); ///< Get all property names + + /// Defines a property on the object. + void DefineProperty( + const PropertyDescriptor& property ///< Descriptor for the property to be defined + ); + + /// Defines properties on the object. + void DefineProperties( + const std::initializer_list& properties + ///< List of descriptors for the properties to be defined + ); + + /// Defines properties on the object. + void DefineProperties( + const std::vector& properties + ///< Vector of descriptors for the properties to be defined + ); + + /// Checks if an object is an instance created by a constructor function. + /// + /// This is equivalent to the JavaScript `instanceof` operator. + bool InstanceOf( + const Function& constructor ///< Constructor function + ) const; + }; + + template + class External : public Value { + public: + static External New(napi_env env, T* data); + + // Finalizer must implement operator() accepting a T* and returning void. + template + static External New(napi_env env, + T* data, + Finalizer finalizeCallback); + // Finalizer must implement operator() accepting a T* and Hint* and returning void. + template + static External New(napi_env env, + T* data, + Finalizer finalizeCallback, + Hint* finalizeHint); + + External(); + External(napi_env env, napi_value value); + + T* Data() const; + }; + + class Array : public Object { + public: + static Array New(napi_env env); + static Array New(napi_env env, size_t length); + + Array(); + Array(napi_env env, napi_value value); + + uint32_t Length() const; + }; + + /// A JavaScript array buffer value. + class ArrayBuffer : public Object { + public: + /// Creates a new ArrayBuffer instance over a new automatically-allocated buffer. + static ArrayBuffer New( + napi_env env, ///< N-API environment + size_t byteLength ///< Length of the buffer to be allocated, in bytes + ); + + /// Creates a new ArrayBuffer instance, using an external buffer with specified byte length. + static ArrayBuffer New( + napi_env env, ///< N-API environment + void* externalData, ///< Pointer to the external buffer to be used by the array + size_t byteLength ///< Length of the external buffer to be used by the array, in bytes + ); + + /// Creates a new ArrayBuffer instance, using an external buffer with specified byte length. + template + static ArrayBuffer New( + napi_env env, ///< N-API environment + void* externalData, ///< Pointer to the external buffer to be used by the array + size_t byteLength, ///< Length of the external buffer to be used by the array, + /// in bytes + Finalizer finalizeCallback ///< Function to be called when the array buffer is destroyed; + /// must implement `operator()`, accept a `void*` (which is the + /// data buffer pointer), and return `void` + ); + + /// Creates a new ArrayBuffer instance, using an external buffer with specified byte length. + template + static ArrayBuffer New( + napi_env env, ///< N-API environment + void* externalData, ///< Pointer to the external buffer to be used by the array + size_t byteLength, ///< Length of the external buffer to be used by the array, + /// in bytes + Finalizer finalizeCallback, ///< Function to be called when the array buffer is destroyed; + /// must implement `operator()`, accept a `void*` (which is the + /// data buffer pointer) and `Hint*`, and return `void` + Hint* finalizeHint ///< Hint (second parameter) to be passed to the finalize callback + ); + + ArrayBuffer(); ///< Creates a new _empty_ ArrayBuffer instance. + ArrayBuffer(napi_env env, napi_value value); ///< Wraps a N-API value primitive. + + void* Data() const; ///< Gets a pointer to the data buffer. + size_t ByteLength() const; ///< Gets the length of the array buffer in bytes. + + private: + mutable void* _data; + mutable size_t _length; + + ArrayBuffer(napi_env env, napi_value value, void* data, size_t length); + void EnsureInfo() const; + }; + + /// A JavaScript typed-array value with unknown array type. + /// + /// For type-specific operations, cast to a `TypedArrayOf` instance using the `As()` + /// method: + /// + /// Napi::TypedArray array = ... + /// if (t.TypedArrayType() == napi_int32_array) { + /// Napi::Int32Array int32Array = t.As(); + /// } + class TypedArray : public Object { + public: + TypedArray(); ///< Creates a new _empty_ TypedArray instance. + TypedArray(napi_env env, napi_value value); ///< Wraps a N-API value primitive. + + napi_typedarray_type TypedArrayType() const; ///< Gets the type of this typed-array. + Napi::ArrayBuffer ArrayBuffer() const; ///< Gets the backing array buffer. + + uint8_t ElementSize() const; ///< Gets the size in bytes of one element in the array. + size_t ElementLength() const; ///< Gets the number of elements in the array. + size_t ByteOffset() const; ///< Gets the offset into the buffer where the array starts. + size_t ByteLength() const; ///< Gets the length of the array in bytes. + + protected: + /// !cond INTERNAL + napi_typedarray_type _type; + size_t _length; + + TypedArray(napi_env env, napi_value value, napi_typedarray_type type, size_t length); + + static const napi_typedarray_type unknown_array_type = static_cast(-1); + + template + static +#if defined(NAPI_HAS_CONSTEXPR) + constexpr +#endif + napi_typedarray_type TypedArrayTypeForPrimitiveType() { + return std::is_same::value ? napi_int8_array + : std::is_same::value ? napi_uint8_array + : std::is_same::value ? napi_int16_array + : std::is_same::value ? napi_uint16_array + : std::is_same::value ? napi_int32_array + : std::is_same::value ? napi_uint32_array + : std::is_same::value ? napi_float32_array + : std::is_same::value ? napi_float64_array +// currently experimental guard with version of NAPI_VERSION that it is +// released in once it is no longer experimental +#if (NAPI_VERSION > 2147483646) + : std::is_same::value ? napi_bigint64_array + : std::is_same::value ? napi_biguint64_array +#endif // NAPI_EXPERIMENTAL + : unknown_array_type; + } + /// !endcond + }; + + /// A JavaScript typed-array value with known array type. + /// + /// Note while it is possible to create and access Uint8 "clamped" arrays using this class, + /// the _clamping_ behavior is only applied in JavaScript. + template + class TypedArrayOf : public TypedArray { + public: + /// Creates a new TypedArray instance over a new automatically-allocated array buffer. + /// + /// The array type parameter can normally be omitted (because it is inferred from the template + /// parameter T), except when creating a "clamped" array: + /// + /// Uint8Array::New(env, length, napi_uint8_clamped_array) + static TypedArrayOf New( + napi_env env, ///< N-API environment + size_t elementLength, ///< Length of the created array, as a number of elements +#if defined(NAPI_HAS_CONSTEXPR) + napi_typedarray_type type = TypedArray::TypedArrayTypeForPrimitiveType() +#else + napi_typedarray_type type +#endif + ///< Type of array, if different from the default array type for the template parameter T. + ); + + /// Creates a new TypedArray instance over a provided array buffer. + /// + /// The array type parameter can normally be omitted (because it is inferred from the template + /// parameter T), except when creating a "clamped" array: + /// + /// Uint8Array::New(env, length, buffer, 0, napi_uint8_clamped_array) + static TypedArrayOf New( + napi_env env, ///< N-API environment + size_t elementLength, ///< Length of the created array, as a number of elements + Napi::ArrayBuffer arrayBuffer, ///< Backing array buffer instance to use + size_t bufferOffset, ///< Offset into the array buffer where the typed-array starts +#if defined(NAPI_HAS_CONSTEXPR) + napi_typedarray_type type = TypedArray::TypedArrayTypeForPrimitiveType() +#else + napi_typedarray_type type +#endif + ///< Type of array, if different from the default array type for the template parameter T. + ); + + TypedArrayOf(); ///< Creates a new _empty_ TypedArrayOf instance. + TypedArrayOf(napi_env env, napi_value value); ///< Wraps a N-API value primitive. + + T& operator [](size_t index); ///< Gets or sets an element in the array. + const T& operator [](size_t index) const; ///< Gets an element in the array. + + /// Gets a pointer to the array's backing buffer. + /// + /// This is not necessarily the same as the `ArrayBuffer::Data()` pointer, because the + /// typed-array may have a non-zero `ByteOffset()` into the `ArrayBuffer`. + T* Data(); + + /// Gets a pointer to the array's backing buffer. + /// + /// This is not necessarily the same as the `ArrayBuffer::Data()` pointer, because the + /// typed-array may have a non-zero `ByteOffset()` into the `ArrayBuffer`. + const T* Data() const; + + private: + T* _data; + + TypedArrayOf(napi_env env, + napi_value value, + napi_typedarray_type type, + size_t length, + T* data); + }; + + /// The DataView provides a low-level interface for reading/writing multiple + /// number types in an ArrayBuffer irrespective of the platform's endianness. + class DataView : public Object { + public: + static DataView New(napi_env env, + Napi::ArrayBuffer arrayBuffer); + static DataView New(napi_env env, + Napi::ArrayBuffer arrayBuffer, + size_t byteOffset); + static DataView New(napi_env env, + Napi::ArrayBuffer arrayBuffer, + size_t byteOffset, + size_t byteLength); + + DataView(); ///< Creates a new _empty_ DataView instance. + DataView(napi_env env, napi_value value); ///< Wraps a N-API value primitive. + + Napi::ArrayBuffer ArrayBuffer() const; ///< Gets the backing array buffer. + size_t ByteOffset() const; ///< Gets the offset into the buffer where the array starts. + size_t ByteLength() const; ///< Gets the length of the array in bytes. + + void* Data() const; + + float GetFloat32(size_t byteOffset) const; + double GetFloat64(size_t byteOffset) const; + int8_t GetInt8(size_t byteOffset) const; + int16_t GetInt16(size_t byteOffset) const; + int32_t GetInt32(size_t byteOffset) const; + uint8_t GetUint8(size_t byteOffset) const; + uint16_t GetUint16(size_t byteOffset) const; + uint32_t GetUint32(size_t byteOffset) const; + + void SetFloat32(size_t byteOffset, float value) const; + void SetFloat64(size_t byteOffset, double value) const; + void SetInt8(size_t byteOffset, int8_t value) const; + void SetInt16(size_t byteOffset, int16_t value) const; + void SetInt32(size_t byteOffset, int32_t value) const; + void SetUint8(size_t byteOffset, uint8_t value) const; + void SetUint16(size_t byteOffset, uint16_t value) const; + void SetUint32(size_t byteOffset, uint32_t value) const; + + private: + template + T ReadData(size_t byteOffset) const; + + template + void WriteData(size_t byteOffset, T value) const; + + void* _data; + size_t _length; + }; + + class Function : public Object { + public: + /// Callable must implement operator() accepting a const CallbackInfo& + /// and return either void or Value. + template + static Function New(napi_env env, + Callable cb, + const char* utf8name = nullptr, + void* data = nullptr); + /// Callable must implement operator() accepting a const CallbackInfo& + /// and return either void or Value. + template + static Function New(napi_env env, + Callable cb, + const std::string& utf8name, + void* data = nullptr); + + Function(); + Function(napi_env env, napi_value value); + + Value operator ()(const std::initializer_list& args) const; + + Value Call(const std::initializer_list& args) const; + Value Call(const std::vector& args) const; + Value Call(size_t argc, const napi_value* args) const; + Value Call(napi_value recv, const std::initializer_list& args) const; + Value Call(napi_value recv, const std::vector& args) const; + Value Call(napi_value recv, size_t argc, const napi_value* args) const; + + //Value MakeCallback(napi_value recv, + // const std::initializer_list& args, + // napi_async_context context = nullptr) const; + //Value MakeCallback(napi_value recv, + // const std::vector& args, + // napi_async_context context = nullptr) const; + //Value MakeCallback(napi_value recv, + // size_t argc, + // const napi_value* args, + // napi_async_context context = nullptr) const; + + Object New(const std::initializer_list& args) const; + Object New(const std::vector& args) const; + Object New(size_t argc, const napi_value* args) const; + }; + + class Promise : public Object { + public: + class Deferred { + public: + static Deferred New(napi_env env); + Deferred(napi_env env); + + Napi::Promise Promise() const; + Napi::Env Env() const; + + void Resolve(napi_value value) const; + void Reject(napi_value value) const; + + private: + napi_env _env; + napi_deferred _deferred; + napi_value _promise; + }; + + Promise(napi_env env, napi_value value); + }; + + template + class Buffer : public Uint8Array { + public: + static Buffer New(napi_env env, size_t length); + static Buffer New(napi_env env, T* data, size_t length); + + // Finalizer must implement operator() accepting a T* and returning void. + template + static Buffer New(napi_env env, T* data, + size_t length, + Finalizer finalizeCallback); + // Finalizer must implement operator() accepting a T* and Hint* and returning void. + template + static Buffer New(napi_env env, T* data, + size_t length, + Finalizer finalizeCallback, + Hint* finalizeHint); + + static Buffer Copy(napi_env env, const T* data, size_t length); + + Buffer(); + Buffer(napi_env env, napi_value value); + size_t Length() const; + T* Data() const; + + private: + mutable size_t _length; + mutable T* _data; + + Buffer(napi_env env, napi_value value, size_t length, T* data); + void EnsureInfo() const; + }; + + /// Holds a counted reference to a value; initially a weak reference unless otherwise specified, + /// may be changed to/from a strong reference by adjusting the refcount. + /// + /// The referenced value is not immediately destroyed when the reference count is zero; it is + /// merely then eligible for garbage-collection if there are no other references to the value. + template + class Reference { + public: + static Reference New(const T& value, uint32_t initialRefcount = 0); + + Reference(); + Reference(napi_env env, napi_ref ref); + ~Reference(); + + // A reference can be moved but cannot be copied. + Reference(Reference&& other); + Reference& operator =(Reference&& other); + Reference& operator =(Reference&) = delete; + + operator napi_ref() const; + bool operator ==(const Reference &other) const; + bool operator !=(const Reference &other) const; + + Napi::Env Env() const; + bool IsEmpty() const; + + // Note when getting the value of a Reference it is usually correct to do so + // within a HandleScope so that the value handle gets cleaned up efficiently. + T Value() const; + + uint32_t Ref(); + uint32_t Unref(); + void Reset(); + void Reset(const T& value, uint32_t refcount = 0); + + // Call this on a reference that is declared as static data, to prevent its destructor + // from running at program shutdown time, which would attempt to reset the reference when + // the environment is no longer valid. + void SuppressDestruct(); + + protected: + Reference(const Reference&); + + /// !cond INTERNAL + napi_env _env; + napi_ref _ref; + /// !endcond + + private: + bool _suppressDestruct; + }; + + class ObjectReference: public Reference { + public: + ObjectReference(); + ObjectReference(napi_env env, napi_ref ref); + + // A reference can be moved but cannot be copied. + ObjectReference(Reference&& other); + ObjectReference& operator =(Reference&& other); + ObjectReference(ObjectReference&& other); + ObjectReference& operator =(ObjectReference&& other); + ObjectReference& operator =(ObjectReference&) = delete; + + Napi::Value Get(const char* utf8name) const; + Napi::Value Get(const std::string& utf8name) const; + void Set(const char* utf8name, napi_value value); + void Set(const char* utf8name, Napi::Value value); + void Set(const char* utf8name, const char* utf8value); + void Set(const char* utf8name, bool boolValue); + void Set(const char* utf8name, double numberValue); + void Set(const std::string& utf8name, napi_value value); + void Set(const std::string& utf8name, Napi::Value value); + void Set(const std::string& utf8name, std::string& utf8value); + void Set(const std::string& utf8name, bool boolValue); + void Set(const std::string& utf8name, double numberValue); + + Napi::Value Get(uint32_t index) const; + void Set(uint32_t index, const napi_value value); + void Set(uint32_t index, const Napi::Value value); + void Set(uint32_t index, const char* utf8value); + void Set(uint32_t index, const std::string& utf8value); + void Set(uint32_t index, bool boolValue); + void Set(uint32_t index, double numberValue); + + protected: + ObjectReference(const ObjectReference&); + }; + + class FunctionReference: public Reference { + public: + FunctionReference(); + FunctionReference(napi_env env, napi_ref ref); + + // A reference can be moved but cannot be copied. + FunctionReference(Reference&& other); + FunctionReference& operator =(Reference&& other); + FunctionReference(FunctionReference&& other); + FunctionReference& operator =(FunctionReference&& other); + FunctionReference(const FunctionReference&) = delete; + FunctionReference& operator =(FunctionReference&) = delete; + + Napi::Value operator ()(const std::initializer_list& args) const; + + Napi::Value Call(const std::initializer_list& args) const; + Napi::Value Call(const std::vector& args) const; + Napi::Value Call(napi_value recv, const std::initializer_list& args) const; + Napi::Value Call(napi_value recv, const std::vector& args) const; + Napi::Value Call(napi_value recv, size_t argc, const napi_value* args) const; + + //Napi::Value MakeCallback(napi_value recv, + // const std::initializer_list& args, + // napi_async_context context = nullptr) const; + //Napi::Value MakeCallback(napi_value recv, + // const std::vector& args, + // napi_async_context context = nullptr) const; + //Napi::Value MakeCallback(napi_value recv, + // size_t argc, + // const napi_value* args, + // napi_async_context context = nullptr) const; + + Object New(const std::initializer_list& args) const; + Object New(const std::vector& args) const; + }; + + // Shortcuts to creating a new reference with inferred type and refcount = 0. + template Reference Weak(T value); + ObjectReference Weak(Object value); + FunctionReference Weak(Function value); + + // Shortcuts to creating a new reference with inferred type and refcount = 1. + template Reference Persistent(T value); + ObjectReference Persistent(Object value); + FunctionReference Persistent(Function value); + + /// A persistent reference to a JavaScript error object. Use of this class depends somewhat + /// on whether C++ exceptions are enabled at compile time. + /// + /// ### Handling Errors With C++ Exceptions + /// + /// If C++ exceptions are enabled, then the `Error` class extends `std::exception` and enables + /// integrated error-handling for C++ exceptions and JavaScript exceptions. + /// + /// If a N-API call fails without executing any JavaScript code (for example due to an invalid + /// argument), then the N-API wrapper automatically converts and throws the error as a C++ + /// exception of type `Napi::Error`. Or if a JavaScript function called by C++ code via N-API + /// throws a JavaScript exception, then the N-API wrapper automatically converts and throws it as + /// a C++ exception of type `Napi::Error`. + /// + /// If a C++ exception of type `Napi::Error` escapes from a N-API C++ callback, then the N-API + /// wrapper automatically converts and throws it as a JavaScript exception. Therefore, catching + /// a C++ exception of type `Napi::Error` prevents a JavaScript exception from being thrown. + /// + /// #### Example 1A - Throwing a C++ exception: + /// + /// Napi::Env env = ... + /// throw Napi::Error::New(env, "Example exception"); + /// + /// Following C++ statements will not be executed. The exception will bubble up as a C++ + /// exception of type `Napi::Error`, until it is either caught while still in C++, or else + /// automatically propataged as a JavaScript exception when the callback returns to JavaScript. + /// + /// #### Example 2A - Propagating a N-API C++ exception: + /// + /// Napi::Function jsFunctionThatThrows = someObj.As(); + /// Napi::Value result = jsFunctionThatThrows({ arg1, arg2 }); + /// + /// Following C++ statements will not be executed. The exception will bubble up as a C++ + /// exception of type `Napi::Error`, until it is either caught while still in C++, or else + /// automatically propagated as a JavaScript exception when the callback returns to JavaScript. + /// + /// #### Example 3A - Handling a N-API C++ exception: + /// + /// Napi::Function jsFunctionThatThrows = someObj.As(); + /// Napi::Value result; + /// try { + /// result = jsFunctionThatThrows({ arg1, arg2 }); + /// } catch (const Napi::Error& e) { + /// cerr << "Caught JavaScript exception: " + e.what(); + /// } + /// + /// Since the exception was caught here, it will not be propagated as a JavaScript exception. + /// + /// ### Handling Errors Without C++ Exceptions + /// + /// If C++ exceptions are disabled (by defining `NAPI_DISABLE_CPP_EXCEPTIONS`) then this class + /// does not extend `std::exception`, and APIs in the `Napi` namespace do not throw C++ + /// exceptions when they fail. Instead, they raise _pending_ JavaScript exceptions and + /// return _empty_ `Value`s. Calling code should check `Value::IsEmpty()` before attempting + /// to use a returned value, and may use methods on the `Env` class to check for, get, and + /// clear a pending JavaScript exception. If the pending exception is not cleared, it will + /// be thrown when the native callback returns to JavaScript. + /// + /// #### Example 1B - Throwing a JS exception + /// + /// Napi::Env env = ... + /// Napi::Error::New(env, "Example exception").ThrowAsJavaScriptException(); + /// return; + /// + /// After throwing a JS exception, the code should generally return immediately from the native + /// callback, after performing any necessary cleanup. + /// + /// #### Example 2B - Propagating a N-API JS exception: + /// + /// Napi::Function jsFunctionThatThrows = someObj.As(); + /// Napi::Value result = jsFunctionThatThrows({ arg1, arg2 }); + /// if (result.IsEmpty()) return; + /// + /// An empty value result from a N-API call indicates an error occurred, and a JavaScript + /// exception is pending. To let the exception propagate, the code should generally return + /// immediately from the native callback, after performing any necessary cleanup. + /// + /// #### Example 3B - Handling a N-API JS exception: + /// + /// Napi::Function jsFunctionThatThrows = someObj.As(); + /// Napi::Value result = jsFunctionThatThrows({ arg1, arg2 }); + /// if (result.IsEmpty()) { + /// Napi::Error e = env.GetAndClearPendingException(); + /// cerr << "Caught JavaScript exception: " + e.Message(); + /// } + /// + /// Since the exception was cleared here, it will not be propagated as a JavaScript exception + /// after the native callback returns. + class Error : public ObjectReference +#ifdef NAPI_CPP_EXCEPTIONS + , public std::exception +#endif // NAPI_CPP_EXCEPTIONS + { + public: + static Error New(napi_env env); + static Error New(napi_env env, const char* message); + static Error New(napi_env env, const std::string& message); + + static void Fatal(const char* location, const char* message); + + Error(); + Error(napi_env env, napi_value value); + + // An error can be moved or copied. + Error(Error&& other); + Error& operator =(Error&& other); + Error(const Error&); + Error& operator =(Error&); + + const std::string& Message() const NAPI_NOEXCEPT; + void ThrowAsJavaScriptException() const; + +#ifdef NAPI_CPP_EXCEPTIONS + const char* what() const NAPI_NOEXCEPT override; +#endif // NAPI_CPP_EXCEPTIONS + + protected: + /// !cond INTERNAL + typedef napi_status (*create_error_fn)(napi_env envb, napi_value code, napi_value msg, napi_value* result); + + template + static TError New(napi_env env, + const char* message, + size_t length, + create_error_fn create_error); + /// !endcond + + private: + mutable std::string _message; + }; + + class TypeError : public Error { + public: + static TypeError New(napi_env env, const char* message); + static TypeError New(napi_env env, const std::string& message); + + TypeError(); + TypeError(napi_env env, napi_value value); + }; + + class RangeError : public Error { + public: + static RangeError New(napi_env env, const char* message); + static RangeError New(napi_env env, const std::string& message); + + RangeError(); + RangeError(napi_env env, napi_value value); + }; + + class CallbackInfo { + public: + CallbackInfo(napi_env env, napi_callback_info info); + ~CallbackInfo(); + + // Disallow copying to prevent multiple free of _dynamicArgs + CallbackInfo(CallbackInfo const &) = delete; + void operator=(CallbackInfo const &) = delete; + + Napi::Env Env() const; + Value NewTarget() const; + bool IsConstructCall() const; + size_t Length() const; + const Value operator [](size_t index) const; + Value This() const; + void* Data() const; + void SetData(void* data); + + private: + const size_t _staticArgCount = 6; + napi_env _env; + napi_callback_info _info; + napi_value _this; + size_t _argc; + napi_value* _argv; + napi_value _staticArgs[6]; + napi_value* _dynamicArgs; + void* _data; + }; + + class PropertyDescriptor { + public: +#ifndef NODE_ADDON_API_DISABLE_DEPRECATED + template + static PropertyDescriptor Accessor(const char* utf8name, + Getter getter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor(const std::string& utf8name, + Getter getter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor(napi_value name, + Getter getter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor(Name name, + Getter getter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor(const char* utf8name, + Getter getter, + Setter setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor(const std::string& utf8name, + Getter getter, + Setter setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor(napi_value name, + Getter getter, + Setter setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor(Name name, + Getter getter, + Setter setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Function(const char* utf8name, + Callable cb, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Function(const std::string& utf8name, + Callable cb, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Function(napi_value name, + Callable cb, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Function(Name name, + Callable cb, + napi_property_attributes attributes = napi_default, + void* data = nullptr); +#endif // !NODE_ADDON_API_DISABLE_DEPRECATED + + template + static PropertyDescriptor Accessor(Napi::Env env, + Napi::Object object, + const char* utf8name, + Getter getter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor(Napi::Env env, + Napi::Object object, + const std::string& utf8name, + Getter getter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor(Napi::Env env, + Napi::Object object, + Name name, + Getter getter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor(Napi::Env env, + Napi::Object object, + const char* utf8name, + Getter getter, + Setter setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor(Napi::Env env, + Napi::Object object, + const std::string& utf8name, + Getter getter, + Setter setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Accessor(Napi::Env env, + Napi::Object object, + Name name, + Getter getter, + Setter setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Function(Napi::Env env, + Napi::Object object, + const char* utf8name, + Callable cb, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Function(Napi::Env env, + Napi::Object object, + const std::string& utf8name, + Callable cb, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + template + static PropertyDescriptor Function(Napi::Env env, + Napi::Object object, + Name name, + Callable cb, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor Value(const char* utf8name, + napi_value value, + napi_property_attributes attributes = napi_default); + static PropertyDescriptor Value(const std::string& utf8name, + napi_value value, + napi_property_attributes attributes = napi_default); + static PropertyDescriptor Value(napi_value name, + napi_value value, + napi_property_attributes attributes = napi_default); + static PropertyDescriptor Value(Name name, + Napi::Value value, + napi_property_attributes attributes = napi_default); + + PropertyDescriptor(napi_property_descriptor desc); + + operator napi_property_descriptor&(); + operator const napi_property_descriptor&() const; + + private: + napi_property_descriptor _desc; + }; + + /// Property descriptor for use with `ObjectWrap::DefineClass()`. + /// + /// This is different from the standalone `PropertyDescriptor` because it is specific to each + /// `ObjectWrap` subclass. This prevents using descriptors from a different class when + /// defining a new class (preventing the callbacks from having incorrect `this` pointers). + template + class ClassPropertyDescriptor { + public: + ClassPropertyDescriptor(napi_property_descriptor desc) : _desc(desc) {} + + operator napi_property_descriptor&() { return _desc; } + operator const napi_property_descriptor&() const { return _desc; } + + private: + napi_property_descriptor _desc; + }; + + /// Base class to be extended by C++ classes exposed to JavaScript; each C++ class instance gets + /// "wrapped" by a JavaScript object that is managed by this class. + /// + /// At initialization time, the `DefineClass()` method must be used to + /// hook up the accessor and method callbacks. It takes a list of + /// property descriptors, which can be constructed via the various + /// static methods on the base class. + /// + /// #### Example: + /// + /// class Example: public Napi::ObjectWrap { + /// public: + /// static void Initialize(Napi::Env& env, Napi::Object& target) { + /// Napi::Function constructor = DefineClass(env, "Example", { + /// InstanceAccessor("value", &Example::GetSomething, &Example::SetSomething), + /// InstanceMethod("doSomething", &Example::DoSomething), + /// }); + /// target.Set("Example", constructor); + /// } + /// + /// Example(const Napi::CallbackInfo& info); // Constructor + /// Napi::Value GetSomething(const Napi::CallbackInfo& info); + /// void SetSomething(const Napi::CallbackInfo& info, const Napi::Value& value); + /// Napi::Value DoSomething(const Napi::CallbackInfo& info); + /// } + template + class ObjectWrap : public Reference { + public: + ObjectWrap(const CallbackInfo& callbackInfo); + + static T* Unwrap(Object wrapper); + + // Methods exposed to JavaScript must conform to one of these callback signatures. + typedef void (*StaticVoidMethodCallback)(const CallbackInfo& info); + typedef Napi::Value (*StaticMethodCallback)(const CallbackInfo& info); + typedef Napi::Value (*StaticGetterCallback)(const CallbackInfo& info); + typedef void (*StaticSetterCallback)(const CallbackInfo& info, const Napi::Value& value); + typedef void (T::*InstanceVoidMethodCallback)(const CallbackInfo& info); + typedef Napi::Value (T::*InstanceMethodCallback)(const CallbackInfo& info); + typedef Napi::Value (T::*InstanceGetterCallback)(const CallbackInfo& info); + typedef void (T::*InstanceSetterCallback)(const CallbackInfo& info, const Napi::Value& value); + + typedef ClassPropertyDescriptor PropertyDescriptor; + + static Function DefineClass(Napi::Env env, + const char* utf8name, + const std::initializer_list& properties, + void* data = nullptr); + static Function DefineClass(Napi::Env env, + const char* utf8name, + const std::vector& properties, + void* data = nullptr); + static PropertyDescriptor StaticMethod(const char* utf8name, + StaticVoidMethodCallback method, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor StaticMethod(const char* utf8name, + StaticMethodCallback method, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor StaticMethod(Symbol name, + StaticVoidMethodCallback method, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor StaticMethod(Symbol name, + StaticMethodCallback method, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor StaticAccessor(const char* utf8name, + StaticGetterCallback getter, + StaticSetterCallback setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor StaticAccessor(Symbol name, + StaticGetterCallback getter, + StaticSetterCallback setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor InstanceMethod(const char* utf8name, + InstanceVoidMethodCallback method, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor InstanceMethod(const char* utf8name, + InstanceMethodCallback method, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor InstanceMethod(Symbol name, + InstanceVoidMethodCallback method, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor InstanceMethod(Symbol name, + InstanceMethodCallback method, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor InstanceAccessor(const char* utf8name, + InstanceGetterCallback getter, + InstanceSetterCallback setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor InstanceAccessor(Symbol name, + InstanceGetterCallback getter, + InstanceSetterCallback setter, + napi_property_attributes attributes = napi_default, + void* data = nullptr); + static PropertyDescriptor StaticValue(const char* utf8name, + Napi::Value value, + napi_property_attributes attributes = napi_default); + static PropertyDescriptor StaticValue(Symbol name, + Napi::Value value, + napi_property_attributes attributes = napi_default); + static PropertyDescriptor InstanceValue(const char* utf8name, + Napi::Value value, + napi_property_attributes attributes = napi_default); + static PropertyDescriptor InstanceValue(Symbol name, + Napi::Value value, + napi_property_attributes attributes = napi_default); + + private: + static napi_value ConstructorCallbackWrapper(napi_env env, napi_callback_info info); + static napi_value StaticVoidMethodCallbackWrapper(napi_env env, napi_callback_info info); + static napi_value StaticMethodCallbackWrapper(napi_env env, napi_callback_info info); + static napi_value StaticGetterCallbackWrapper(napi_env env, napi_callback_info info); + static napi_value StaticSetterCallbackWrapper(napi_env env, napi_callback_info info); + static napi_value InstanceVoidMethodCallbackWrapper(napi_env env, napi_callback_info info); + static napi_value InstanceMethodCallbackWrapper(napi_env env, napi_callback_info info); + static napi_value InstanceGetterCallbackWrapper(napi_env env, napi_callback_info info); + static napi_value InstanceSetterCallbackWrapper(napi_env env, napi_callback_info info); + static void FinalizeCallback(napi_env env, void* data, void* hint); + static Function DefineClass(Napi::Env env, + const char* utf8name, + const size_t props_count, + const napi_property_descriptor* props, + void* data = nullptr); + + template + struct MethodCallbackData { + TCallback callback; + void* data; + }; + typedef MethodCallbackData StaticVoidMethodCallbackData; + typedef MethodCallbackData StaticMethodCallbackData; + typedef MethodCallbackData InstanceVoidMethodCallbackData; + typedef MethodCallbackData InstanceMethodCallbackData; + + template + struct AccessorCallbackData { + TGetterCallback getterCallback; + TSetterCallback setterCallback; + void* data; + }; + typedef AccessorCallbackData + StaticAccessorCallbackData; + typedef AccessorCallbackData + InstanceAccessorCallbackData; + }; + + class HandleScope { + public: + HandleScope(napi_env env, napi_handle_scope scope); + explicit HandleScope(Napi::Env env); + ~HandleScope(); + + operator napi_handle_scope() const; + + Napi::Env Env() const; + + private: + napi_env _env; + napi_handle_scope _scope; + }; + + class EscapableHandleScope { + public: + EscapableHandleScope(napi_env env, napi_escapable_handle_scope scope); + explicit EscapableHandleScope(Napi::Env env); + ~EscapableHandleScope(); + + operator napi_escapable_handle_scope() const; + + Napi::Env Env() const; + Value Escape(napi_value escapee); + + private: + napi_env _env; + napi_escapable_handle_scope _scope; + }; + + //class AsyncContext { + //public: + // explicit AsyncContext(napi_env env, const char* resource_name); + // explicit AsyncContext(napi_env env, const char* resource_name, const Object& resource); + // virtual ~AsyncContext(); + + // AsyncContext(AsyncContext&& other); + // AsyncContext& operator =(AsyncContext&& other); + // AsyncContext(const AsyncContext&) = delete; + // AsyncContext& operator =(AsyncContext&) = delete; + + // operator napi_async_context() const; + + //private: + // napi_env _env; + // napi_async_context _context; + //}; + + //class AsyncWorker { + //public: + // virtual ~AsyncWorker(); + + // // An async worker can be moved but cannot be copied. + // AsyncWorker(AsyncWorker&& other); + // AsyncWorker& operator =(AsyncWorker&& other); + // AsyncWorker(const AsyncWorker&) = delete; + // AsyncWorker& operator =(AsyncWorker&) = delete; + + // operator napi_async_work() const; + + // Napi::Env Env() const; + + // void Queue(); + // void Cancel(); + + // ObjectReference& Receiver(); + // FunctionReference& Callback(); + + //protected: + // explicit AsyncWorker(const Function& callback); + // explicit AsyncWorker(const Function& callback, + // const char* resource_name); + // explicit AsyncWorker(const Function& callback, + // const char* resource_name, + // const Object& resource); + // explicit AsyncWorker(const Object& receiver, + // const Function& callback); + // explicit AsyncWorker(const Object& receiver, + // const Function& callback, + // const char* resource_name); + // explicit AsyncWorker(const Object& receiver, + // const Function& callback, + // const char* resource_name, + // const Object& resource); + + // virtual void Execute() = 0; + // virtual void OnOK(); + // virtual void OnError(const Error& e); + + // void SetError(const std::string& error); + + //private: + // static void OnExecute(napi_env env, void* this_pointer); + // static void OnWorkComplete(napi_env env, + // napi_status status, + // void* this_pointer); + + // napi_env _env; + // napi_async_work _work; + // ObjectReference _receiver; + // FunctionReference _callback; + // std::string _error; + //}; + + //// Memory management. + //class MemoryManagement { + // public: + // static int64_t AdjustExternalMemory(Env env, int64_t change_in_bytes); + //}; + + //// Version management + //class VersionManagement { + // public: + // static uint32_t GetNapiVersion(Env env); + // static const napi_node_version* GetNodeVersion(Env env); + //}; + +} // namespace Napi + +// Inline implementations of all the above class methods are included here. +#include "napi-inl.h" + +#endif // SRC_NAPI_H_ diff --git a/Source/Runtime/Common.h b/Source/Runtime/Common.h new file mode 100644 index 000000000..da0d89120 --- /dev/null +++ b/Source/Runtime/Common.h @@ -0,0 +1,12 @@ +#pragma once + +#include +#include + +namespace babylon +{ + using babylon_dispatcher = arcana::dispatcher<128>; + + const std::string& GetExecutablePath(); + std::string GetAbsolutePath(const char* relativePath); +} diff --git a/Source/Runtime/CommonUWP.cpp b/Source/Runtime/CommonUWP.cpp new file mode 100644 index 000000000..ac0cfbad9 --- /dev/null +++ b/Source/Runtime/CommonUWP.cpp @@ -0,0 +1,28 @@ +#include "CommonUWP.h" +#include + +namespace +{ + std::string executablePath; +} + +namespace babylon +{ + const std::string& GetExecutablePath() + { + if (executablePath.empty()) + { + char path[1024]; + ::GetModuleFileNameA(nullptr, path, ARRAYSIZE(path)); + executablePath.assign(path); + } + + return executablePath; + } + + std::string GetAbsolutePath(const char* relativePath) + { + const std::string& path = GetExecutablePath(); + return path.substr(0, path.find_last_of('\\') + 1) + relativePath; + } +} diff --git a/Source/Runtime/CommonUWP.h b/Source/Runtime/CommonUWP.h new file mode 100644 index 000000000..4fd403207 --- /dev/null +++ b/Source/Runtime/CommonUWP.h @@ -0,0 +1,3 @@ +#pragma once + +#include "Common.h" diff --git a/Source/Runtime/CommonWin32.cpp b/Source/Runtime/CommonWin32.cpp new file mode 100644 index 000000000..9bd2ed777 --- /dev/null +++ b/Source/Runtime/CommonWin32.cpp @@ -0,0 +1,28 @@ +#include "CommonWin32.h" +#include + +namespace +{ + std::string executablePath; +} + +namespace babylon +{ + const std::string& GetExecutablePath() + { + if (executablePath.empty()) + { + char path[1024]; + ::GetModuleFileNameA(nullptr, path, ARRAYSIZE(path)); + executablePath.assign(path); + } + + return executablePath; + } + + std::string GetAbsolutePath(const char* relativePath) + { + const std::string& path = GetExecutablePath(); + return path.substr(0, path.find_last_of('\\') + 1) + relativePath; + } +} diff --git a/Source/Runtime/CommonWin32.h b/Source/Runtime/CommonWin32.h new file mode 100644 index 000000000..4fd403207 --- /dev/null +++ b/Source/Runtime/CommonWin32.h @@ -0,0 +1,3 @@ +#pragma once + +#include "Common.h" diff --git a/Source/Runtime/Runtime.cpp b/Source/Runtime/Runtime.cpp new file mode 100644 index 000000000..02303be44 --- /dev/null +++ b/Source/Runtime/Runtime.cpp @@ -0,0 +1,57 @@ +#include "Runtime.h" + +#include "RuntimeImpl.h" +#include + +namespace babylon +{ + Runtime::Runtime(std::unique_ptr impl) + : m_impl{ std::move(impl) } + {} + + Runtime::~Runtime() + {} + + void Runtime::UpdateSize(float width, float height) + { + m_impl->UpdateSize(width, height); + } + + void Runtime::UpdateRenderTarget() + { + m_impl->UpdateRenderTarget(); + } + + void Runtime::Suspend() + { + m_impl->Suspend(); + } + + void Runtime::RunScript(const std::string& url) + { + m_impl->RunScript(url); + } + + void Runtime::RunScript(const std::string& script, const std::string& url) + { + m_impl->RunScript(script, url); + } + + void Runtime::Execute(std::function func) + { + m_impl->Execute([this, func = std::move(func)](auto&) + { + func(*this); + }); + } + + Napi::Env& Runtime::Env() const + { + return m_impl->ScriptHost().Env(); + } + + const std::string& Runtime::RootUrl() const + { + return m_impl->RootUrl(); + } +} diff --git a/Source/Runtime/Runtime.h b/Source/Runtime/Runtime.h new file mode 100644 index 000000000..d9bee6f95 --- /dev/null +++ b/Source/Runtime/Runtime.h @@ -0,0 +1,37 @@ +#pragma once + +#include + +#include +#include +#include + +namespace babylon +{ + class RuntimeImpl; + + class Runtime + { + public: + Runtime(std::unique_ptr); + Runtime(const Runtime&) = delete; + Runtime& operator=(const Runtime&) = delete; + virtual ~Runtime(); + + void UpdateSize(float width, float height); + void UpdateRenderTarget(); + void Suspend(); + + void RunScript(const std::string& url); + void RunScript(const std::string& script, const std::string& url); + + void Execute(std::function); + + Napi::Env& Env() const; + const std::string& RootUrl() const; + + protected: + Runtime() = default; + std::unique_ptr m_impl; + }; +} diff --git a/Source/Runtime/RuntimeImpl.cpp b/Source/Runtime/RuntimeImpl.cpp new file mode 100644 index 000000000..abd751df9 --- /dev/null +++ b/Source/Runtime/RuntimeImpl.cpp @@ -0,0 +1,107 @@ +#include "RuntimeImpl.h" + +#include +#include +#include +#include +#include + +namespace babylon +{ + RuntimeImpl::RuntimeImpl(void* nativeWindowPtr, const std::string& rootUrl, std::function threadProcedure) + : m_engine{ std::make_unique(nativeWindowPtr, *this) } + , m_thread{ [threadProcedure = std::move(threadProcedure)] { threadProcedure(); } } + , m_rootUrl{ rootUrl } + {} + + RuntimeImpl::RuntimeImpl(void* nativeWindowPtr, const std::string& rootUrl) + : RuntimeImpl{ nativeWindowPtr, rootUrl, [this] { DefaultThreadProcedure(); } } + {} + + RuntimeImpl::~RuntimeImpl() + { + m_cancelSource.cancel(); + m_thread.join(); + } + + void RuntimeImpl::UpdateSize(float width, float height) + { + m_dispatcher.queue([width, height, this] { m_engine->UpdateSize(width, height); }); + } + + void RuntimeImpl::UpdateRenderTarget() + { + m_dispatcher.queue([this] { m_engine->UpdateRenderTarget(); }); + } + + void RuntimeImpl::Suspend() + { + m_engine->Suspend(); + } + + void RuntimeImpl::Execute(std::function func) + { + auto lock = AcquireTaskLock(); + Task = Task.then(m_dispatcher, m_cancelSource, [func = std::move(func), this]() + { + func(*this); + }); + } + + ScriptHost& RuntimeImpl::ScriptHost() + { + return *this->m_scriptHost; + } + + const std::string& RuntimeImpl::RootUrl() const + { + return m_rootUrl; + } + + arcana::manual_dispatcher& RuntimeImpl::Dispatcher() + { + return m_dispatcher; + } + + arcana::cancellation& RuntimeImpl::Cancellation() + { + return m_cancelSource; + } + + std::scoped_lock RuntimeImpl::AcquireTaskLock() + { + return std::scoped_lock{ m_taskMutex }; + } + + void RuntimeImpl::DefaultThreadProcedure() + { + m_dispatcher.set_affinity(std::this_thread::get_id()); + + babylon::ScriptHost host{ *this }; + m_scriptHost = &host; + auto hostScopeGuard = gsl::finally([this] { m_scriptHost = nullptr; }); + + Console::Initialize(m_scriptHost->Env()); + + XMLHttpRequest::Initialize(m_scriptHost->Env(), *this); + + Window window{ *this }; + + m_engine->Initialize(host.Env()); + + // TODO: Handle device lost/restored. + + while (!m_cancelSource.cancelled()) + { + m_dispatcher.blocking_tick(m_cancelSource); + } + } + + void RuntimeImpl::RunScriptWithNapi(const std::string& script, const std::string& url) + { + auto& env = ScriptHost().Env(); + auto scriptString = Napi::String::New(env, script); + napi_value result; + napi_run_script(env, scriptString, url.c_str(), &result); // TODO throw error if failed? Probably should move this functionality into napi + } +} diff --git a/Source/Runtime/RuntimeImpl.h b/Source/Runtime/RuntimeImpl.h new file mode 100644 index 000000000..7950446ae --- /dev/null +++ b/Source/Runtime/RuntimeImpl.h @@ -0,0 +1,70 @@ +#pragma once + +#include "Common.h" + +#include + +#include +#include + +namespace babylon +{ + class BgfxEngine; + class ScriptHost; + + class RuntimeImpl + { + public: + using GraphicsEngine = BgfxEngine; + + RuntimeImpl(void* nativeWindowPtr, const std::string& rootUrl, std::function threadProcedure); + RuntimeImpl(void* nativeWindowPtr, const std::string& rootUrl); + virtual ~RuntimeImpl(); + + void UpdateSize(float width, float height); + void UpdateRenderTarget(); + void Suspend(); + + virtual void RunScript(const std::string& url) = 0; + virtual void RunScript(const std::string& script, const std::string& url) = 0; + + void Execute(std::function); + + ScriptHost& ScriptHost(); + const std::string& RootUrl() const; + arcana::manual_dispatcher& Dispatcher(); + arcana::cancellation& Cancellation(); + + // TODO: Reduce exposure of Task and mutex once we decide on an effective alternative. + /// Appending to the task chain is NOT thread-safe. Before setting the RuntimeImpl's Task + /// to a new value, AcquireTaskLock MUST be called. Correct usage is something like the + /// following: + /// + /// auto lock = runtimeImpl.AcquireTaskLock(); + /// runtimeImpl.Task = runtimeImpl.Task.then(...); + /// + arcana::task Task = arcana::task_from_result(); + std::scoped_lock AcquireTaskLock(); + + protected: + void DefaultThreadProcedure(); + void RunScriptWithNapi(const std::string& script, const std::string& url); + + private: + arcana::manual_dispatcher m_dispatcher{}; + arcana::cancellation_source m_cancelSource{}; + std::mutex m_taskMutex{}; + + std::unique_ptr m_engine{}; + + std::thread m_thread{}; + + // The script host is technically owned by the thread on which it runs, and so + // the actually object is maintained as a local variable within the method which + // represents that thread. However, external calls occasionally need access to + // the script host as well; m_host provides this access when the script host is + // available, reverting to nullptr once the script host is destroyed. + babylon::ScriptHost* m_scriptHost{}; + const std::string m_rootUrl{}; + }; +} diff --git a/Source/Runtime/RuntimeUWP.cpp b/Source/Runtime/RuntimeUWP.cpp new file mode 100644 index 000000000..cb2506861 --- /dev/null +++ b/Source/Runtime/RuntimeUWP.cpp @@ -0,0 +1,191 @@ +#include "RuntimeUWP.h" +#include "CommonUWP.h" +#include "RuntimeImpl.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + arcana::task read_text_async(std::string filename) + { + auto folder = winrt::Windows::ApplicationModel::Package::Current().InstalledLocation(); + return arcana::create_task(folder.GetFileAsync(winrt::to_hstring(filename))) + .then(arcana::inline_scheduler, arcana::cancellation::none(), [filename](const winrt::Windows::Storage::StorageFile& file) + { + return arcana::create_task(winrt::Windows::Storage::FileIO::ReadTextAsync(file)); + }).then(arcana::inline_scheduler, arcana::cancellation::none(), [filename](const winrt::hstring& hstring) + { + return winrt::to_string(hstring); + }); + } + + // Converts a length in device-independent pixels (DIPs) to a length in physical pixels. + float dips_to_pixels(float dips, float dpi) + { + static const float dipsPerInch = 96.0f; + return floorf(dips * dpi / dipsPerInch + 0.5f); // Round to nearest integer. + } + + template + T from_abi(void* from) + { + T to{ nullptr }; + winrt::copy_from_abi(to, from); + return std::move(to); + } + + // TODO: fix for bgfx + //Spectre::Engine::EngineDescription GetEngineDescription(winrt::agile_ref& window) + //{ + // Spectre::Engine::EngineDescription engineDesc{}; + + // Spectre::Engine::GeneralDescription& general = engineDesc.General; + // general.ThreadingMode = Spectre::Engine::Lockable::ThreadingMode::Single; + + // Spectre::Engine::DeviceDescription& device = engineDesc.Device; + // device.Platform = Spectre::Engine::DevicePlatform::DirectX11; + + // Spectre::Engine::OutputDescription& output = engineDesc.Output; + // output.Mode = Spectre::Engine::RenderOutputMode::CoreWindow; + // output.NativeWindow = winrt::get_abi(reinterpret_cast&>(window)); + // output.PerformanceLogging = Spectre::Engine::RenderOutputPerformanceLogging::Enable; + + // return std::move(engineDesc); + //} + + //void SPECTRESDK_CALL OnSwapChainCreatedCallback(void* dxgiSwapChain, void* pUserData) + //{ + // auto panel = from_abi(pUserData); + // panel.Dispatcher().RunAsync(winrt::Windows::UI::Core::CoreDispatcherPriority::Normal, [=] + // { + // winrt::check_hresult(panel.as()->SetSwapChain(static_cast(dxgiSwapChain))); + // }); + //} + + //Spectre::Engine::EngineDescription GetEngineDescription(winrt::Windows::UI::Xaml::Controls::SwapChainPanel& panel) + //{ + // Spectre::Engine::EngineDescription engineDesc{}; + + // Spectre::Engine::GeneralDescription& general = engineDesc.General; + // general.ThreadingMode = Spectre::Engine::Lockable::ThreadingMode::Single; + + // Spectre::Engine::DeviceDescription& device = engineDesc.Device; + // device.Platform = Spectre::Engine::DevicePlatform::DirectX11; + + // Spectre::Engine::OutputDescription& output = engineDesc.Output; + // output.Mode = Spectre::Engine::RenderOutputMode::XAML; + // output.NativeWindow = winrt::get_abi(panel); + // output.OnSwapChainCreatedCallback = OnSwapChainCreatedCallback; + // output.PerformanceLogging = Spectre::Engine::RenderOutputPerformanceLogging::Enable; + + // return std::move(engineDesc); + //} +} + +namespace babylon +{ + class RuntimeUWP::Impl final : public RuntimeImpl + { + public: + // TODO: fix RenderPAL to take a CoreWindow directly instead of an agile ref to a CoreWindow once we switch to RenderPAL. + explicit Impl(winrt::agile_ref window, const std::string& rootUrl); + explicit Impl(winrt::Windows::UI::Xaml::Controls::SwapChainPanel panel, const std::string& rootUrl); + ~Impl() override = default; + + virtual void RunScript(const std::string& url) override; + virtual void RunScript(const std::string& script, const std::string& url) override; + + private: + std::variant, winrt::Windows::UI::Xaml::Controls::SwapChainPanel> m_windowsUiContext; + }; + + RuntimeUWP::DefaultInitializationScriptsArray RuntimeUWP::DEFAULT_INITIALIZATION_SCRIPTS = arcana::make_array + ( +#ifdef _DEBUG + "Scripts\\babylon.max.js", + "Scripts\\babylon.glTF2FileLoader.js" +#else + "Scripts\\babylon.js", + "Scripts\\babylon.glTF2FileLoader.min.js" +#endif + ); + + RuntimeUWP::RuntimeUWP(ABI::Windows::UI::Core::ICoreWindow* window, const std::string& rootUrl) + : Runtime{ std::make_unique(from_abi(window), rootUrl) } + { + } + + RuntimeUWP::RuntimeUWP(ABI::Windows::UI::Xaml::Controls::ISwapChainPanel* panel, const std::string& rootUrl) + : Runtime{ std::make_unique(from_abi(panel), rootUrl) } + { + } + + RuntimeUWP::Impl::Impl(winrt::agile_ref window, const std::string& rootUrl) + : RuntimeImpl{ /*std::make_unique(GetEngineDescription(window), *this)*/nullptr, rootUrl } + , m_windowsUiContext{ window } + { + // Set initial render output size. + const auto windowBounds = window.get().Bounds(); + const auto currentDisplayInformation = winrt::Windows::Graphics::Display::DisplayInformation::GetForCurrentView(); + const float dpi = currentDisplayInformation.LogicalDpi(); + UpdateSize(dips_to_pixels(windowBounds.Width, dpi), dips_to_pixels(windowBounds.Height, dpi)); + + for (const auto& url : RuntimeUWP::DEFAULT_INITIALIZATION_SCRIPTS) + { + RunScript(url); + } + } + + RuntimeUWP::Impl::Impl(winrt::Windows::UI::Xaml::Controls::SwapChainPanel panel, const std::string& rootUrl) + : RuntimeImpl{ /*std::make_unique(GetEngineDescription(panel), *this)*/nullptr, rootUrl } + , m_windowsUiContext{ panel } + { + // Set initial render output size. + const auto currentDisplayInformation = winrt::Windows::Graphics::Display::DisplayInformation::GetForCurrentView(); + const float dpi = currentDisplayInformation.LogicalDpi(); + UpdateSize(dips_to_pixels(static_cast(panel.ActualWidth()), dpi), dips_to_pixels(static_cast(panel.ActualHeight()), dpi)); + + for (const auto& url : RuntimeUWP::DEFAULT_INITIALIZATION_SCRIPTS) + { + RunScript(url); + } + } + + void RuntimeUWP::Impl::RunScript(const std::string& url) + { + auto lock = AcquireTaskLock(); + Task = Task.then(arcana::inline_scheduler, Cancellation(), [url] + { + return read_text_async(url); + }).then(Dispatcher(), Cancellation(), [this, url](const std::string& script) + { + RunScriptWithNapi(script, url); + }); + } + + void RuntimeUWP::Impl::RunScript(const std::string& script, const std::string& url) + { + Execute([this, script, url](auto&) + { + RunScriptWithNapi(script, url); + }); + } +} diff --git a/Source/Runtime/RuntimeUWP.h b/Source/Runtime/RuntimeUWP.h new file mode 100644 index 000000000..23aa1af87 --- /dev/null +++ b/Source/Runtime/RuntimeUWP.h @@ -0,0 +1,26 @@ +#pragma once + +#include "Runtime.h" + +#include +#include + +#include + +namespace babylon +{ + class RuntimeUWP final : public Runtime + { + public: + using DefaultInitializationScriptsArray = const std::array; + static DefaultInitializationScriptsArray DEFAULT_INITIALIZATION_SCRIPTS; + + explicit RuntimeUWP(ABI::Windows::UI::Core::ICoreWindow* window, const std::string& rootUrl = {}); + explicit RuntimeUWP(ABI::Windows::UI::Xaml::Controls::ISwapChainPanel* panel, const std::string& rootUrl = {}); + RuntimeUWP(const Runtime&) = delete; + ~RuntimeUWP() = default; + + private: + class Impl; + }; +} diff --git a/Source/Runtime/RuntimeWin32.cpp b/Source/Runtime/RuntimeWin32.cpp new file mode 100644 index 000000000..646dc517b --- /dev/null +++ b/Source/Runtime/RuntimeWin32.cpp @@ -0,0 +1,118 @@ +#include "RuntimeWin32.h" +#include "RuntimeImpl.h" +#include "CommonWin32.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + std::string ReadAllText(const char* fileName) + { + // TODO: This hack-ish way to load files from local and system-wide locations should be + // replaced once we figure out how we want to do file access in general. + + std::ifstream t; + t.open(fileName); + if (!t.good()) + { + t.open(babylon::GetAbsolutePath(fileName)); + } + return std::string({ std::istreambuf_iterator(t) }, std::istreambuf_iterator()); + } +} + +namespace babylon +{ + class RuntimeWin32::Impl final : public RuntimeImpl + { + public: + explicit Impl(HWND hWnd, const std::string& rootUrl); + ~Impl() override; + + virtual void RunScript(const std::string& url) override; + virtual void RunScript(const std::string& script, const std::string& url) override; + + private: + void ThreadProcedure(); + }; + + RuntimeWin32::DefaultInitializationScriptsArray RuntimeWin32::DEFAULT_INITIALIZATION_SCRIPTS = arcana::make_array + ( +#ifdef _DEBUG + "Scripts\\babylon.max.js", + "Scripts\\babylon.glTF2FileLoader.js" +#else + "Scripts\\babylon.js", + "Scripts\\babylon.glTF2FileLoader.min.js" +#endif + ); + + RuntimeWin32::RuntimeWin32(HWND hWnd, const std::string& rootUrl) + : Runtime{ std::make_unique(hWnd, rootUrl) } + { + } + + RuntimeWin32::~RuntimeWin32() + { + } + + // Loads and initializes application assets when the application is loaded. + RuntimeWin32::Impl::Impl(HWND hWnd, const std::string& rootUrl) + : RuntimeImpl{ hWnd, rootUrl, [this] { ThreadProcedure(); } } + { + RECT rect; + if (GetWindowRect(hWnd, &rect)) + { + float width = static_cast(rect.right - rect.left); + float height = static_cast(rect.bottom - rect.top); + UpdateSize(width, height); + } + + for (const auto& url : RuntimeWin32::DEFAULT_INITIALIZATION_SCRIPTS) + { + RunScript(url); + } + } + + RuntimeWin32::Impl::~Impl() + { + Dispatcher().clear(); // TODO: fix arcana instead of doing this + } + + void RuntimeWin32::Impl::ThreadProcedure() + { + HRESULT hresult = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); + assert(SUCCEEDED(hresult)); + auto coInitializeScopeGuard = gsl::finally([] { CoUninitialize(); }); + + RuntimeImpl::DefaultThreadProcedure(); + } + + void RuntimeWin32::Impl::RunScript(const std::string& url) + { + auto lock = AcquireTaskLock(); + Task = Task.then(Dispatcher(), Cancellation(), [this, url] + { + return ReadAllText(url.c_str()); + }).then(Dispatcher(), Cancellation(), [this, url](const std::string& script) + { + RunScriptWithNapi(script, url); + }); + } + + void RuntimeWin32::Impl::RunScript(const std::string& script, const std::string& url) + { + Execute([this, script, url](auto&) + { + RunScriptWithNapi(script, url); + }); + } +} diff --git a/Source/Runtime/RuntimeWin32.h b/Source/Runtime/RuntimeWin32.h new file mode 100644 index 000000000..ad0b55e89 --- /dev/null +++ b/Source/Runtime/RuntimeWin32.h @@ -0,0 +1,26 @@ +#pragma once + +#include "Runtime.h" + +#include + +#include +#include +#include + +namespace babylon +{ + class RuntimeWin32 final : public Runtime + { + public: + using DefaultInitializationScriptsArray = const std::array; + static DefaultInitializationScriptsArray DEFAULT_INITIALIZATION_SCRIPTS; + + explicit RuntimeWin32(HWND hWnd, const std::string& rootUrl = {}); + RuntimeWin32(const RuntimeWin32&) = delete; + ~RuntimeWin32(); + + private: + class Impl; + }; +} diff --git a/Source/ScriptHost/Console.cpp b/Source/ScriptHost/Console.cpp new file mode 100644 index 000000000..aeda75eec --- /dev/null +++ b/Source/ScriptHost/Console.cpp @@ -0,0 +1,54 @@ +#include "Console.h" +#include + +namespace babylon +{ + void Console::Initialize(Napi::Env env) + { + Napi::HandleScope scope{ env }; + + Napi::Function func = DefineClass( + env, + "Console", + { + InstanceMethod("log", &Console::Log), + InstanceMethod("warn", &Console::Warn), + InstanceMethod("error", &Console::Error), + }); + + env.Global().Set("console", func.New({})); + } + + Console::Console(const Napi::CallbackInfo& info) + : Napi::ObjectWrap{ info } + { + } + + void Console::Log(const Napi::CallbackInfo& info) + { + // TODO: Log output to ETW/telemetry rather than debugger output. + // TODO: Handle version of this method that takes a format string as the first parameter. + + for (unsigned int index = 0; index < info.Length(); index++) + { + if (index > 0) + { + OutputDebugStringA(" "); + } + OutputDebugStringA(info[index].ToString().Utf8Value().c_str()); + } + OutputDebugStringA("\r\n"); + } + + void Console::Warn(const Napi::CallbackInfo& info) + { + // TODO + Log(info); + } + + void Console::Error(const Napi::CallbackInfo& info) + { + // TODO + Log(info); + } +} diff --git a/Source/ScriptHost/Console.h b/Source/ScriptHost/Console.h new file mode 100644 index 000000000..f18b41b3c --- /dev/null +++ b/Source/ScriptHost/Console.h @@ -0,0 +1,19 @@ +#pragma once + +#include + +namespace babylon +{ + class Console final : public Napi::ObjectWrap + { + public: + static void Initialize(Napi::Env env); + + explicit Console(const Napi::CallbackInfo& info); + + private: + void Log(const Napi::CallbackInfo& info); + void Warn(const Napi::CallbackInfo& info); + void Error(const Napi::CallbackInfo& info); + }; +} diff --git a/Source/ScriptHost/ScriptHost.h b/Source/ScriptHost/ScriptHost.h new file mode 100644 index 000000000..d2c32c51b --- /dev/null +++ b/Source/ScriptHost/ScriptHost.h @@ -0,0 +1,25 @@ +#pragma once + +#include +#include +#include +#include + +namespace babylon +{ + class ScriptHost final + { + public: + explicit ScriptHost(RuntimeImpl&); + ScriptHost(const ScriptHost&) = delete; + ~ScriptHost(); + + void RunScript(gsl::czstring<> script, gsl::czstring<> url); + + Napi::Env& Env(); + + private: + class Impl; + std::unique_ptr m_impl; + }; +} diff --git a/Source/ScriptHost/ScriptHostChakra.cpp b/Source/ScriptHost/ScriptHostChakra.cpp new file mode 100644 index 000000000..4939187d7 --- /dev/null +++ b/Source/ScriptHost/ScriptHostChakra.cpp @@ -0,0 +1,102 @@ +#include "ScriptHost.h" +#include +#include +#include +#include +#include +#include + +namespace babylon +{ + class ScriptHost::Impl final + { + public: + explicit Impl(RuntimeImpl& runtimeImpl); + ~Impl(); + + void RunScript(gsl::czstring<> script, gsl::czstring<> url); + + Napi::Env& Env(); + + private: + static void CALLBACK PromiseContinuationCallback(JsValueRef task, void* callbackState); + + Napi::Env m_env; + RuntimeImpl& m_runtimeImpl; + JsRuntimeHandle m_jsRuntime; + }; + + ScriptHost::ScriptHost(RuntimeImpl& runtimeImpl) + : m_impl{ std::make_unique(runtimeImpl) } + { + } + + ScriptHost::~ScriptHost() + { + } + + void ScriptHost::RunScript(gsl::czstring<> script, gsl::czstring<> url) + { + m_impl->RunScript(script, url); + } + + Napi::Env& ScriptHost::Env() + { + return m_impl->Env(); + } + + ScriptHost::Impl::Impl(RuntimeImpl& runtimeImpl) + : m_env{ napi_create_env() } + , m_runtimeImpl{ runtimeImpl } + { + // Create the runtime. We're only going to use one runtime for this host. + JsCreateRuntime(JsRuntimeAttributeNone, nullptr, &m_jsRuntime); + + // Create a single execution context. + JsContextRef context; + JsCreateContext(m_jsRuntime, &context); + + // Now set the execution context as being the current one on this thread. + JsSetCurrentContext(context); + + // Set up ES6 Promise. + JsSetPromiseContinuationCallback(&Impl::PromiseContinuationCallback, this); + + // UWP namespace projection; all UWP under Windows namespace should work. + JsProjectWinRTNamespace(L"Windows"); + +#ifdef _DEBUG + // Put Chakra in debug mode. + JsStartDebugging(); +#endif + } + + ScriptHost::Impl::~Impl() + { + JsDisposeRuntime(m_jsRuntime); + } + + void ScriptHost::Impl::RunScript(gsl::czstring<> script, gsl::czstring<> url) + { + auto scriptString = Napi::String::New(m_env, script); + napi_value result; + napi_run_script(m_env, scriptString, url, &result); // TODO throw error if failed? Probably should move this functionality into napi + } + + Napi::Env& ScriptHost::Impl::Env() + { + return m_env; + } + + void CALLBACK ScriptHost::Impl::PromiseContinuationCallback(JsValueRef task, void* callbackState) + { + JsAddRef(task, nullptr); + reinterpret_cast(callbackState)->m_runtimeImpl.Execute([task](auto&) + { + JsValueRef undefined; + JsGetUndefinedValue(&undefined); + JsCallFunction(task, &undefined, 1, nullptr); + JsRelease(task, nullptr); + }); + } +} diff --git a/Source/ScriptHost/ScriptHostV8.cpp b/Source/ScriptHost/ScriptHostV8.cpp new file mode 100644 index 000000000..94ffb21a2 --- /dev/null +++ b/Source/ScriptHost/ScriptHostV8.cpp @@ -0,0 +1,116 @@ +#include "ScriptHost.h" +#include +#include +#include +#include + +namespace +{ + class Module final + { + public: + Module() + { + const std::string& executablePath = babylon::GetExecutablePath(); + v8::V8::InitializeICUDefaultLocation(executablePath.data()); + v8::V8::InitializeExternalStartupData(executablePath.data()); + m_platform = v8::platform::NewDefaultPlatform(); + v8::V8::InitializePlatform(m_platform.get()); + v8::V8::Initialize(); + } + + ~Module() + { + v8::V8::Dispose(); + v8::V8::ShutdownPlatform(); + } + + static void Initialize() + { + if (s_module == nullptr) + { + s_module = std::make_unique(); + } + } + + private: + std::unique_ptr m_platform; + + static std::unique_ptr s_module; + }; + + std::unique_ptr Module::s_module; + + v8::Isolate* CreateIsolate(v8::ArrayBuffer::Allocator* arrayBufferAllocator) + { + Module::Initialize(); + + v8::Isolate::CreateParams create_params; + create_params.array_buffer_allocator = arrayBufferAllocator; + return v8::Isolate::New(create_params); + } +} + +namespace babylon +{ + class ScriptHost::Impl final + { + public: + Impl(); + ~Impl(); + + void RunScript(gsl::czstring<> script, gsl::czstring<> url); + + Napi::Env& Env(); + + private: + std::unique_ptr m_arrayBufferAllocator; + v8::Isolate* m_isolate; + Napi::Env m_env; + }; + + ScriptHost::ScriptHost(RuntimeImpl&) + : m_impl{ std::make_unique() } + { + } + + ScriptHost::~ScriptHost() + { + } + + void ScriptHost::RunScript(gsl::czstring<> script, gsl::czstring<> url) + { + m_impl->RunScript(script, url); + } + + Napi::Env& ScriptHost::Env() + { + return m_impl->Env(); + } + + ScriptHost::Impl::Impl() + : m_arrayBufferAllocator{ v8::ArrayBuffer::Allocator::NewDefaultAllocator() } + , m_isolate{ ::CreateIsolate(m_arrayBufferAllocator.get()) } + , m_env{ ::napi_create_env(m_isolate) } + { + } + + ScriptHost::Impl::~Impl() + { + ::napi_destroy_env(m_env); + + m_isolate->Dispose(); + } + + void ScriptHost::Impl::RunScript(gsl::czstring<> script, gsl::czstring<> url) + { + auto scriptString = Napi::String::New(m_env, script); + napi_value result; + napi_run_script(m_env, scriptString, url, &result); // TODO throw error if failed? Probably should move this functionality into napi + } + + Napi::Env& ScriptHost::Impl::Env() + { + return m_env; + } +} diff --git a/Source/ScriptHost/Window.cpp b/Source/ScriptHost/Window.cpp new file mode 100644 index 000000000..25f94b17c --- /dev/null +++ b/Source/ScriptHost/Window.cpp @@ -0,0 +1,55 @@ +#include "Window.h" + +#include + +#include + +namespace babylon +{ + Window::Window(RuntimeImpl& runtimeImpl) + : m_runtimeImpl{ runtimeImpl } + { + auto& env = m_runtimeImpl.ScriptHost().Env(); + Napi::HandleScope scope{ env }; + + Napi::Object global = env.Global(); + global.Set("setTimeout", Napi::Function::New(env, &Window::SetTimeout, "setTimeout", this)); + global.Set("atob", Napi::Function::New(env, &Window::DecodeBase64, "atob", this)); + + global.Set("window", global); + } + + void Window::SetTimeout(const Napi::CallbackInfo& info) + { + auto function = Napi::Persistent(info[0].As()); + auto milliseconds = std::chrono::milliseconds{ info[1].As().Int32Value() }; + + Window* window = reinterpret_cast(info.Data()); + window->RecursiveWaitOrCall(std::make_shared(std::move(function)), std::chrono::system_clock::now() + milliseconds); + } + + Napi::Value Window::DecodeBase64(const Napi::CallbackInfo& info) + { + std::string encodedData = info[0].As().Utf8Value(); + std::u16string decodedData; + bn::decode_b64(encodedData.begin(), encodedData.end(), std::back_inserter(decodedData)); + return Napi::Value::From(info.Env(), decodedData); + } + + void Window::RecursiveWaitOrCall( + std::shared_ptr function, + std::chrono::system_clock::time_point whenToRun) + { + if (std::chrono::system_clock::now() >= whenToRun) + { + function->Call({}); + } + else + { + m_runtimeImpl.Execute([this, function = std::move(function), whenToRun](auto&) + { + RecursiveWaitOrCall(std::move(function), whenToRun); + }); + } + } +} diff --git a/Source/ScriptHost/Window.h b/Source/ScriptHost/Window.h new file mode 100644 index 000000000..597a4e37e --- /dev/null +++ b/Source/ScriptHost/Window.h @@ -0,0 +1,22 @@ +#pragma once + +#include +#include +#include + +namespace babylon +{ + class Window final + { + public: + Window(RuntimeImpl& runtime); + + private: + static void SetTimeout(const Napi::CallbackInfo& info); + static Napi::Value DecodeBase64(const Napi::CallbackInfo& info); + + void RecursiveWaitOrCall(std::shared_ptr, std::chrono::system_clock::time_point); + + RuntimeImpl& m_runtimeImpl; + }; +} diff --git a/Source/ScriptHost/XMLHttpRequest.cpp b/Source/ScriptHost/XMLHttpRequest.cpp new file mode 100644 index 000000000..703540f59 --- /dev/null +++ b/Source/ScriptHost/XMLHttpRequest.cpp @@ -0,0 +1,248 @@ +#include "XMLHttpRequest.h" + +#define CURL_STATICLIB +#include + +#include + +namespace babylon +{ + namespace + { + arcana::task, std::exception_ptr> HttpRequestWithCurl( + const std::string& url, + babylon_dispatcher& dispatcher, + arcana::cancellation& cancelSource) + { + return arcana::make_task(dispatcher, cancelSource, [url]() + { + std::vector data{}; + + auto curl = curl_easy_init(); + if (curl) + { + curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); + curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); + + curl_write_callback callback = [](char *buffer, size_t size, size_t nitems, void *userData) + { + auto& data = *static_cast*>(userData); + data.insert(data.end(), buffer, buffer + nitems); + return nitems; + }; + + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, callback); + curl_easy_setopt(curl, CURLOPT_WRITEDATA, &data); + + auto result = curl_easy_perform(curl); + if (result != CURLE_OK) + { + throw std::exception("HTTP request failed."); + } + + curl_easy_cleanup(curl); + } + + return data; + }); + } + + std::string GetAbsoluteUrl(const std::string& input, const std::string& locationUrl) + { + auto url = curl_url(); + + auto code = curl_url_set(url, CURLUPART_URL, input.c_str(), 0); + + // If input could not be turned into a valid URL, try using it as a regular URL. + if (code == CURLUE_MALFORMED_INPUT) + { + std::stringstream ss; + ss << locationUrl << "/" << input; + code = curl_url_set(url, CURLUPART_URL, ss.str().c_str(), 0); + } + + if (code != CURLUE_OK) + { + throw std::exception{ "Invalid URL, neither absolute nor relative." }; + } + + char* buf; + code = curl_url_get(url, CURLUPART_URL, &buf, 0); + + if (code != CURLUE_OK) + { + throw std::exception{ "Invalid URL, unable to create final URL." }; + } + + std::string absoluteUrl{ buf }; + + curl_free(buf); + curl_url_cleanup(url); + + return absoluteUrl; + } + } + + Napi::FunctionReference XMLHttpRequest::constructor; + + void XMLHttpRequest::Initialize(Napi::Env& env, RuntimeImpl& runtimeImpl) + { + Napi::HandleScope scope{ env }; + + Napi::Function func = DefineClass( + env, + "XMLHttpRequest", + { + StaticValue("UNSENT", Napi::Value::From(env, 0)), + StaticValue("OPENED", Napi::Value::From(env, 1)), + StaticValue("HEADERS_RECEIVED", Napi::Value::From(env, 2)), + StaticValue("LOADING", Napi::Value::From(env, 3)), + StaticValue("DONE", Napi::Value::From(env, 4)), + InstanceAccessor("readyState", &XMLHttpRequest::GetReadyState, nullptr), + InstanceAccessor("response", &XMLHttpRequest::GetResponse, nullptr), + InstanceAccessor("responseText", &XMLHttpRequest::GetResponseText, nullptr), + InstanceAccessor("responseType", &XMLHttpRequest::GetResponseType, &XMLHttpRequest::SetResponseType), + InstanceAccessor("responseURL", &XMLHttpRequest::GetResponseURL, nullptr), + InstanceAccessor("status", &XMLHttpRequest::GetStatus, nullptr), + InstanceMethod("addEventListener", &XMLHttpRequest::AddEventListener), + InstanceMethod("removeEventListener", &XMLHttpRequest::RemoveEventListener), + InstanceMethod("open", &XMLHttpRequest::Open), + InstanceMethod("send", &XMLHttpRequest::Send), + }, + &runtimeImpl); + + constructor = Napi::Persistent(func); + constructor.SuppressDestruct(); + + env.Global().Set("XMLHttpRequest", func); + } + + XMLHttpRequest::XMLHttpRequest(const Napi::CallbackInfo& info) + : Napi::ObjectWrap{ info } + , m_runtimeImpl{ *static_cast(info.Data()) } + { + } + + Napi::Value XMLHttpRequest::GetReadyState(const Napi::CallbackInfo&) + { + return Napi::Value::From(Env(), arcana::underlying_cast(m_readyState)); + } + + Napi::Value XMLHttpRequest::GetResponse(const Napi::CallbackInfo&) + { + return m_response.Value(); + } + + Napi::Value XMLHttpRequest::GetResponseText(const Napi::CallbackInfo&) + { + return Napi::Value::From(Env(), m_responseText); + } + + Napi::Value XMLHttpRequest::GetResponseType(const Napi::CallbackInfo&) + { + return Napi::Value::From(Env(), m_responseType); + } + + void XMLHttpRequest::SetResponseType(const Napi::CallbackInfo&, const Napi::Value& value) + { + m_responseType = value.As().Utf8Value(); + } + + Napi::Value XMLHttpRequest::GetResponseURL(const Napi::CallbackInfo&) + { + return Napi::Value::From(Env(), m_responseURL); + } + + Napi::Value XMLHttpRequest::GetStatus(const Napi::CallbackInfo&) + { + return Napi::Value::From(Env(), arcana::underlying_cast(m_status)); + } + + void XMLHttpRequest::AddEventListener(const Napi::CallbackInfo& info) + { + std::string eventType = info[0].As().Utf8Value(); + Napi::Function eventHandler = info[1].As(); + + const auto& eventHandlerRefs = m_eventHandlerRefs[eventType]; + for (auto it = eventHandlerRefs.begin(); it != eventHandlerRefs.end(); ++it) + { + if (it->Value() == eventHandler) + { + throw Napi::Error::New(info.Env(), "Cannot add the same event handler twice"); + } + } + + m_eventHandlerRefs[eventType].push_back(Napi::Persistent(eventHandler)); + } + + void XMLHttpRequest::RemoveEventListener(const Napi::CallbackInfo& info) + { + std::string eventType = info[0].As().Utf8Value(); + Napi::Function eventHandler = info[1].As(); + auto itType = m_eventHandlerRefs.find(eventType); + if (itType != m_eventHandlerRefs.end()) + { + auto& eventHandlerRefs = itType->second; + for (auto it = eventHandlerRefs.begin(); it != eventHandlerRefs.end(); ++it) + { + if (it->Value() == eventHandler) + { + eventHandlerRefs.erase(it); + break; + } + } + } + } + + void XMLHttpRequest::Open(const Napi::CallbackInfo& info) + { + m_method = info[0].As().Utf8Value(); + m_url = GetAbsoluteUrl(info[1].As().Utf8Value(), m_runtimeImpl.RootUrl()); + SetReadyState(ReadyState::Opened); + } + + void XMLHttpRequest::Send(const Napi::CallbackInfo& info) + { + auto lock = m_runtimeImpl.AcquireTaskLock(); + m_runtimeImpl.Task = m_runtimeImpl.Task.then(arcana::inline_scheduler, arcana::cancellation::none(), [this] + { + return SendAsync(); + }); + } + + // TODO: Make this just be SendAsync() once the UWP file access bug is fixed. + arcana::task XMLHttpRequest::SendAsyncImpl() + { + return HttpRequestWithCurl(m_url, m_runtimeImpl.Dispatcher(), m_runtimeImpl.Cancellation()) + .then(arcana::inline_scheduler, m_runtimeImpl.Cancellation(), [this](const std::vector& data) + { + if (m_responseType.empty() || m_responseType == XMLHttpRequestTypes::ResponseType::Text) + { + m_responseText = std::string{ data.data(), data.size() }; + } + else if (m_responseType == XMLHttpRequestTypes::ResponseType::ArrayBuffer) + { + m_response = Napi::Persistent(Napi::ArrayBuffer::New(Env(), data.size())); + memcpy(m_response.Value().Data(), data.data(), data.size()); + } + + m_status = winrt::Windows::Web::Http::HttpStatusCode::Ok; + SetReadyState(ReadyState::Done); + }); + } + + void XMLHttpRequest::SetReadyState(ReadyState readyState) + { + m_readyState = readyState; + + auto it = m_eventHandlerRefs.find(XMLHttpRequestTypes::EventType::ReadyStateChange); + if (it != m_eventHandlerRefs.end()) + { + const auto& eventHandlerRefs = it->second; + for (const auto& eventHandlerRef : eventHandlerRefs) + { + eventHandlerRef.Call({}); + } + } + } +} diff --git a/Source/ScriptHost/XMLHttpRequest.h b/Source/ScriptHost/XMLHttpRequest.h new file mode 100644 index 000000000..4831ad6a7 --- /dev/null +++ b/Source/ScriptHost/XMLHttpRequest.h @@ -0,0 +1,77 @@ +#pragma once + +#include +#include +#include +#include +#include + +// Should only be in cpp implementation for UWP version +#include + +namespace babylon +{ + // TODO: Move these down into the CPP file once the UWP file access bug is fixed. + namespace XMLHttpRequestTypes + { + namespace ResponseType + { + constexpr const char* Text = "text"; + constexpr const char* ArrayBuffer = "arraybuffer"; + } + + namespace EventType + { + constexpr const char* ReadyStateChange = "readystatechange"; + constexpr const char* Progress = "progress"; + constexpr const char* LoadEnd = "loadend"; + } + } + + class XMLHttpRequest final : public Napi::ObjectWrap + { + public: + static void Initialize(Napi::Env& env, RuntimeImpl& runtimeImpl); + + explicit XMLHttpRequest(const Napi::CallbackInfo& info); + + private: + static Napi::FunctionReference constructor; + + enum class ReadyState + { + Unsent = 0, + Opened = 1, + Done = 4, + }; + + Napi::Value GetReadyState(const Napi::CallbackInfo& info); + Napi::Value GetResponse(const Napi::CallbackInfo& info); + Napi::Value GetResponseText(const Napi::CallbackInfo& info); + Napi::Value GetResponseType(const Napi::CallbackInfo& info); + void SetResponseType(const Napi::CallbackInfo& info, const Napi::Value& value); + Napi::Value GetResponseURL(const Napi::CallbackInfo& info); + Napi::Value GetStatus(const Napi::CallbackInfo& info); + void AddEventListener(const Napi::CallbackInfo& info); + void RemoveEventListener(const Napi::CallbackInfo& info); + void Open(const Napi::CallbackInfo& info); + void Send(const Napi::CallbackInfo& info); + + arcana::task SendAsync(); + arcana::task SendAsyncImpl(); // TODO: Eliminate this function once the UWP file access bug is fixed. + void SetReadyState(ReadyState readyState); + + RuntimeImpl& m_runtimeImpl; + + ReadyState m_readyState{ ReadyState::Unsent }; + Napi::Reference m_response; + std::string m_responseText; + std::string m_responseType; + winrt::Windows::Web::Http::HttpStatusCode m_status{ winrt::Windows::Web::Http::HttpStatusCode::None }; + std::string m_responseURL; + std::unordered_map> m_eventHandlerRefs; + + std::string m_method; + std::string m_url; + }; +} diff --git a/Source/ScriptHost/XMLHttpRequestUWP.cpp b/Source/ScriptHost/XMLHttpRequestUWP.cpp new file mode 100644 index 000000000..b5e559926 --- /dev/null +++ b/Source/ScriptHost/XMLHttpRequestUWP.cpp @@ -0,0 +1,73 @@ +#include "XMLHttpRequest.h" + +#include + +#include +#include +#include + +namespace babylon +{ + arcana::task XMLHttpRequest::SendAsync() + { + return SendAsyncImpl() + .then(arcana::inline_scheduler, m_runtimeImpl.Cancellation(), [url = m_url, responseType = m_responseType, this](arcana::expected result) + { + if (result.has_error()) + { + winrt::Windows::Foundation::Uri uri{ winrt::to_hstring(url) }; + + std::wstring_view path{ uri.Path() }; + if (path[0] != L'/') + { + throw std::runtime_error("Invalid file url"); + } + + std::wstring localPath{ path.substr(1) }; + std::replace(localPath.begin(), localPath.end(), '/', '\\'); + // TODO: decode escaped url characters + + // TODO: handle errors + return arcana::create_task(winrt::Windows::Storage::StorageFile::GetFileFromPathAsync(localPath)) + .then(arcana::inline_scheduler, m_runtimeImpl.Cancellation(), [responseType = std::move(responseType), this](const winrt::Windows::Storage::StorageFile& file) + { + if (responseType.empty() || responseType == XMLHttpRequestTypes::ResponseType::Text) + { + return arcana::create_task(winrt::Windows::Storage::FileIO::ReadTextAsync(file)) + .then(m_runtimeImpl.Dispatcher(), m_runtimeImpl.Cancellation(), [this](const winrt::hstring& text) + { + m_responseText = winrt::to_string(text); + }); + } + else if (responseType == XMLHttpRequestTypes::ResponseType::ArrayBuffer) + { + return arcana::create_task(winrt::Windows::Storage::FileIO::ReadBufferAsync(file)) + .then(m_runtimeImpl.Dispatcher(), m_runtimeImpl.Cancellation(), [this](const winrt::Windows::Storage::Streams::IBuffer& buffer) + { + std::byte* bytes; + auto bufferByteAccess = buffer.as<::Windows::Storage::Streams::IBufferByteAccess>(); + winrt::check_hresult(bufferByteAccess->Buffer(reinterpret_cast(&bytes))); + + m_response = Napi::Persistent(Napi::ArrayBuffer::New(Env(), buffer.Length())); + memcpy(m_response.Value().Data(), bytes, buffer.Length()); + }); + } + else + { + throw std::logic_error("Unexpected response type."); + } + }).then(m_runtimeImpl.Dispatcher(), m_runtimeImpl.Cancellation(), [this, url = std::move(url)] + { + m_responseURL = url; + m_status = winrt::Windows::Web::Http::HttpStatusCode::Ok; + + SetReadyState(ReadyState::Done); + }); + } + else + { + return arcana::task_from_result(); + } + }); + } +} diff --git a/Source/ScriptHost/XMLHttpRequestWin32.cpp b/Source/ScriptHost/XMLHttpRequestWin32.cpp new file mode 100644 index 000000000..c47a2dcb9 --- /dev/null +++ b/Source/ScriptHost/XMLHttpRequestWin32.cpp @@ -0,0 +1,9 @@ +#include "XMLHttpRequest.h" + +namespace babylon +{ + arcana::task XMLHttpRequest::SendAsync() + { + return SendAsyncImpl(); + } +} diff --git a/Source/Scripts/babylon.glTF2FileLoader.js b/Source/Scripts/babylon.glTF2FileLoader.js new file mode 100644 index 000000000..72fe0d3bf --- /dev/null +++ b/Source/Scripts/babylon.glTF2FileLoader.js @@ -0,0 +1,4298 @@ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(require("babylonjs")); + else if(typeof define === 'function' && define.amd) + define("babylonjs-loaders", ["babylonjs"], factory); + else if(typeof exports === 'object') + exports["babylonjs-loaders"] = factory(require("babylonjs")); + else + root["LOADERS"] = factory(root["BABYLON"]); +})((typeof self !== "undefined" ? self : typeof global !== "undefined" ? global : this), function(__WEBPACK_EXTERNAL_MODULE_babylonjs_Misc_observable__) { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) { +/******/ return installedModules[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ i: moduleId, +/******/ l: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.l = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // define getter function for harmony exports +/******/ __webpack_require__.d = function(exports, name, getter) { +/******/ if(!__webpack_require__.o(exports, name)) { +/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); +/******/ } +/******/ }; +/******/ +/******/ // define __esModule on exports +/******/ __webpack_require__.r = function(exports) { +/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { +/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); +/******/ } +/******/ Object.defineProperty(exports, '__esModule', { value: true }); +/******/ }; +/******/ +/******/ // create a fake namespace object +/******/ // mode & 1: value is a module id, require it +/******/ // mode & 2: merge all properties of value into the ns +/******/ // mode & 4: return value when already ns object +/******/ // mode & 8|1: behave like require +/******/ __webpack_require__.t = function(value, mode) { +/******/ if(mode & 1) value = __webpack_require__(value); +/******/ if(mode & 8) return value; +/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; +/******/ var ns = Object.create(null); +/******/ __webpack_require__.r(ns); +/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); +/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); +/******/ return ns; +/******/ }; +/******/ +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __webpack_require__.d(getter, 'a', getter); +/******/ return getter; +/******/ }; +/******/ +/******/ // Object.prototype.hasOwnProperty.call +/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; +/******/ +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(__webpack_require__.s = "./legacy/legacy-glTF2FileLoader.ts"); +/******/ }) +/************************************************************************/ +/******/ ({ + +/***/ "../../node_modules/webpack/buildin/global.js": +/*!***********************************!*\ + !*** (webpack)/buildin/global.js ***! + \***********************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +var g; + +// This works in non-strict mode +g = (function() { + return this; +})(); + +try { + // This works if eval is allowed (see CSP) + g = g || new Function("return this")(); +} catch (e) { + // This works if the window reference is available + if (typeof window === "object") g = window; +} + +// g can still be undefined, but nothing to do about it... +// We return undefined, instead of nothing here, so it's +// easier to handle this case. if(!global) { ...} + +module.exports = g; + + +/***/ }), + +/***/ "./glTF/2.0/Extensions/EXT_lights_image_based.ts": +/*!*******************************************************!*\ + !*** ./glTF/2.0/Extensions/EXT_lights_image_based.ts ***! + \*******************************************************/ +/*! exports provided: EXT_lights_image_based */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EXT_lights_image_based", function() { return EXT_lights_image_based; }); +/* harmony import */ var babylonjs_Maths_math_scalar__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! babylonjs/Maths/math.scalar */ "babylonjs/Misc/observable"); +/* harmony import */ var babylonjs_Maths_math_scalar__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Maths_math_scalar__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _glTFLoader__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../glTFLoader */ "./glTF/2.0/glTFLoader.ts"); + + + + + +var NAME = "EXT_lights_image_based"; +/** + * [Specification](https://github.com/KhronosGroup/glTF/blob/eb3e32332042e04691a5f35103f8c261e50d8f1e/extensions/2.0/Khronos/EXT_lights_image_based/README.md) (Experimental) + */ +var EXT_lights_image_based = /** @class */ (function () { + /** @hidden */ + function EXT_lights_image_based(loader) { + /** The name of this extension. */ + this.name = NAME; + /** Defines whether this extension is enabled. */ + this.enabled = true; + this._loader = loader; + } + /** @hidden */ + EXT_lights_image_based.prototype.dispose = function () { + delete this._loader; + delete this._lights; + }; + /** @hidden */ + EXT_lights_image_based.prototype.onLoading = function () { + var extensions = this._loader.gltf.extensions; + if (extensions && extensions[this.name]) { + var extension = extensions[this.name]; + this._lights = extension.lights; + } + }; + /** @hidden */ + EXT_lights_image_based.prototype.loadSceneAsync = function (context, scene) { + var _this = this; + return _glTFLoader__WEBPACK_IMPORTED_MODULE_1__["GLTFLoader"].LoadExtensionAsync(context, scene, this.name, function (extensionContext, extension) { + var promises = new Array(); + promises.push(_this._loader.loadSceneAsync(context, scene)); + _this._loader.logOpen("" + extensionContext); + var light = _glTFLoader__WEBPACK_IMPORTED_MODULE_1__["ArrayItem"].Get(extensionContext + "/light", _this._lights, extension.light); + promises.push(_this._loadLightAsync("#/extensions/" + _this.name + "/lights/" + extension.light, light).then(function (texture) { + _this._loader.babylonScene.environmentTexture = texture; + })); + _this._loader.logClose(); + return Promise.all(promises).then(function () { }); + }); + }; + EXT_lights_image_based.prototype._loadLightAsync = function (context, light) { + var _this = this; + if (!light._loaded) { + var promises = new Array(); + this._loader.logOpen("" + context); + var imageData_1 = new Array(light.specularImages.length); + var _loop_1 = function (mipmap) { + var faces = light.specularImages[mipmap]; + imageData_1[mipmap] = new Array(faces.length); + var _loop_2 = function (face) { + var specularImageContext = context + "/specularImages/" + mipmap + "/" + face; + this_1._loader.logOpen("" + specularImageContext); + var index = faces[face]; + var image = _glTFLoader__WEBPACK_IMPORTED_MODULE_1__["ArrayItem"].Get(specularImageContext, this_1._loader.gltf.images, index); + promises.push(this_1._loader.loadImageAsync("#/images/" + index, image).then(function (data) { + imageData_1[mipmap][face] = data; + })); + this_1._loader.logClose(); + }; + for (var face = 0; face < faces.length; face++) { + _loop_2(face); + } + }; + var this_1 = this; + for (var mipmap = 0; mipmap < light.specularImages.length; mipmap++) { + _loop_1(mipmap); + } + this._loader.logClose(); + light._loaded = Promise.all(promises).then(function () { + var babylonTexture = new babylonjs_Maths_math_scalar__WEBPACK_IMPORTED_MODULE_0__["RawCubeTexture"](_this._loader.babylonScene, null, light.specularImageSize); + light._babylonTexture = babylonTexture; + if (light.intensity != undefined) { + babylonTexture.level = light.intensity; + } + if (light.rotation) { + var rotation = babylonjs_Maths_math_scalar__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].FromArray(light.rotation); + // Invert the rotation so that positive rotation is counter-clockwise. + if (!_this._loader.babylonScene.useRightHandedSystem) { + rotation = babylonjs_Maths_math_scalar__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].Inverse(rotation); + } + babylonjs_Maths_math_scalar__WEBPACK_IMPORTED_MODULE_0__["Matrix"].FromQuaternionToRef(rotation, babylonTexture.getReflectionTextureMatrix()); + } + var sphericalHarmonics = babylonjs_Maths_math_scalar__WEBPACK_IMPORTED_MODULE_0__["SphericalHarmonics"].FromArray(light.irradianceCoefficients); + sphericalHarmonics.scaleInPlace(light.intensity); + sphericalHarmonics.convertIrradianceToLambertianRadiance(); + var sphericalPolynomial = babylonjs_Maths_math_scalar__WEBPACK_IMPORTED_MODULE_0__["SphericalPolynomial"].FromHarmonics(sphericalHarmonics); + // Compute the lod generation scale to fit exactly to the number of levels available. + var lodGenerationScale = (imageData_1.length - 1) / babylonjs_Maths_math_scalar__WEBPACK_IMPORTED_MODULE_0__["Scalar"].Log2(light.specularImageSize); + return babylonTexture.updateRGBDAsync(imageData_1, sphericalPolynomial, lodGenerationScale); + }); + } + return light._loaded.then(function () { + return light._babylonTexture; + }); + }; + return EXT_lights_image_based; +}()); + +_glTFLoader__WEBPACK_IMPORTED_MODULE_1__["GLTFLoader"].RegisterExtension(NAME, function (loader) { return new EXT_lights_image_based(loader); }); + + +/***/ }), + +/***/ "./glTF/2.0/Extensions/KHR_draco_mesh_compression.ts": +/*!***********************************************************!*\ + !*** ./glTF/2.0/Extensions/KHR_draco_mesh_compression.ts ***! + \***********************************************************/ +/*! exports provided: KHR_draco_mesh_compression */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KHR_draco_mesh_compression", function() { return KHR_draco_mesh_compression; }); +/* harmony import */ var babylonjs_Meshes_Compression_dracoCompression__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! babylonjs/Meshes/Compression/dracoCompression */ "babylonjs/Misc/observable"); +/* harmony import */ var babylonjs_Meshes_Compression_dracoCompression__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Meshes_Compression_dracoCompression__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _glTFLoader__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../glTFLoader */ "./glTF/2.0/glTFLoader.ts"); + + + + +var NAME = "KHR_draco_mesh_compression"; +/** + * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression) + */ +var KHR_draco_mesh_compression = /** @class */ (function () { + /** @hidden */ + function KHR_draco_mesh_compression(loader) { + /** The name of this extension. */ + this.name = NAME; + /** Defines whether this extension is enabled. */ + this.enabled = babylonjs_Meshes_Compression_dracoCompression__WEBPACK_IMPORTED_MODULE_0__["DracoCompression"].DecoderAvailable; + this._loader = loader; + } + /** @hidden */ + KHR_draco_mesh_compression.prototype.dispose = function () { + delete this.dracoCompression; + delete this._loader; + }; + /** @hidden */ + KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { + var _this = this; + return _glTFLoader__WEBPACK_IMPORTED_MODULE_1__["GLTFLoader"].LoadExtensionAsync(context, primitive, this.name, function (extensionContext, extension) { + if (primitive.mode != undefined) { + if (primitive.mode !== 5 /* TRIANGLE_STRIP */ && + primitive.mode !== 4 /* TRIANGLES */) { + throw new Error(context + ": Unsupported mode " + primitive.mode); + } + // TODO: handle triangle strips + if (primitive.mode === 5 /* TRIANGLE_STRIP */) { + throw new Error(context + ": Mode " + primitive.mode + " is not currently supported"); + } + } + var attributes = {}; + var loadAttribute = function (name, kind) { + var uniqueId = extension.attributes[name]; + if (uniqueId == undefined) { + return; + } + babylonMesh._delayInfo = babylonMesh._delayInfo || []; + if (babylonMesh._delayInfo.indexOf(kind) === -1) { + babylonMesh._delayInfo.push(kind); + } + attributes[kind] = uniqueId; + }; + loadAttribute("POSITION", babylonjs_Meshes_Compression_dracoCompression__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].PositionKind); + loadAttribute("NORMAL", babylonjs_Meshes_Compression_dracoCompression__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].NormalKind); + loadAttribute("TANGENT", babylonjs_Meshes_Compression_dracoCompression__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].TangentKind); + loadAttribute("TEXCOORD_0", babylonjs_Meshes_Compression_dracoCompression__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].UVKind); + loadAttribute("TEXCOORD_1", babylonjs_Meshes_Compression_dracoCompression__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].UV2Kind); + loadAttribute("JOINTS_0", babylonjs_Meshes_Compression_dracoCompression__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].MatricesIndicesKind); + loadAttribute("WEIGHTS_0", babylonjs_Meshes_Compression_dracoCompression__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].MatricesWeightsKind); + loadAttribute("COLOR_0", babylonjs_Meshes_Compression_dracoCompression__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].ColorKind); + var bufferView = _glTFLoader__WEBPACK_IMPORTED_MODULE_1__["ArrayItem"].Get(extensionContext, _this._loader.gltf.bufferViews, extension.bufferView); + if (!bufferView._dracoBabylonGeometry) { + bufferView._dracoBabylonGeometry = _this._loader.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView).then(function (data) { + var dracoCompression = _this.dracoCompression || babylonjs_Meshes_Compression_dracoCompression__WEBPACK_IMPORTED_MODULE_0__["DracoCompression"].Default; + return dracoCompression.decodeMeshAsync(data, attributes).then(function (babylonVertexData) { + var babylonGeometry = new babylonjs_Meshes_Compression_dracoCompression__WEBPACK_IMPORTED_MODULE_0__["Geometry"](babylonMesh.name, _this._loader.babylonScene); + babylonVertexData.applyToGeometry(babylonGeometry); + return babylonGeometry; + }).catch(function (error) { + throw new Error(context + ": " + error.message); + }); + }); + } + return bufferView._dracoBabylonGeometry; + }); + }; + return KHR_draco_mesh_compression; +}()); + +_glTFLoader__WEBPACK_IMPORTED_MODULE_1__["GLTFLoader"].RegisterExtension(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); }); + + +/***/ }), + +/***/ "./glTF/2.0/Extensions/KHR_lights_punctual.ts": +/*!****************************************************!*\ + !*** ./glTF/2.0/Extensions/KHR_lights_punctual.ts ***! + \****************************************************/ +/*! exports provided: KHR_lights */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KHR_lights", function() { return KHR_lights; }); +/* harmony import */ var babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! babylonjs/Maths/math */ "babylonjs/Misc/observable"); +/* harmony import */ var babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _glTFLoader__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../glTFLoader */ "./glTF/2.0/glTFLoader.ts"); + + + + + + +var NAME = "KHR_lights_punctual"; +var LightType; +(function (LightType) { + LightType["DIRECTIONAL"] = "directional"; + LightType["POINT"] = "point"; + LightType["SPOT"] = "spot"; +})(LightType || (LightType = {})); +/** + * [Specification](https://github.com/KhronosGroup/glTF/blob/1048d162a44dbcb05aefc1874bfd423cf60135a6/extensions/2.0/Khronos/KHR_lights_punctual/README.md) (Experimental) + */ +var KHR_lights = /** @class */ (function () { + /** @hidden */ + function KHR_lights(loader) { + /** The name of this extension. */ + this.name = NAME; + /** Defines whether this extension is enabled. */ + this.enabled = true; + this._loader = loader; + } + /** @hidden */ + KHR_lights.prototype.dispose = function () { + delete this._loader; + delete this._lights; + }; + /** @hidden */ + KHR_lights.prototype.onLoading = function () { + var extensions = this._loader.gltf.extensions; + if (extensions && extensions[this.name]) { + var extension = extensions[this.name]; + this._lights = extension.lights; + } + }; + /** @hidden */ + KHR_lights.prototype.loadNodeAsync = function (context, node, assign) { + var _this = this; + return _glTFLoader__WEBPACK_IMPORTED_MODULE_1__["GLTFLoader"].LoadExtensionAsync(context, node, this.name, function (extensionContext, extension) { + return _this._loader.loadNodeAsync(context, node, function (babylonMesh) { + var babylonLight; + var light = _glTFLoader__WEBPACK_IMPORTED_MODULE_1__["ArrayItem"].Get(extensionContext, _this._lights, extension.light); + var name = light.name || babylonMesh.name; + switch (light.type) { + case LightType.DIRECTIONAL: { + babylonLight = new babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["DirectionalLight"](name, babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Backward(), _this._loader.babylonScene); + break; + } + case LightType.POINT: { + babylonLight = new babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["PointLight"](name, babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(), _this._loader.babylonScene); + break; + } + case LightType.SPOT: { + var babylonSpotLight = new babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["SpotLight"](name, babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(), babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Backward(), 0, 1, _this._loader.babylonScene); + babylonSpotLight.angle = ((light.spot && light.spot.outerConeAngle) || Math.PI / 4) * 2; + babylonSpotLight.innerAngle = ((light.spot && light.spot.innerConeAngle) || 0) * 2; + babylonLight = babylonSpotLight; + break; + } + default: { + throw new Error(extensionContext + ": Invalid light type (" + light.type + ")"); + } + } + babylonLight.falloffType = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Light"].FALLOFF_GLTF; + babylonLight.diffuse = light.color ? babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Color3"].FromArray(light.color) : babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Color3"].White(); + babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity; + babylonLight.range = light.range == undefined ? Number.MAX_VALUE : light.range; + babylonLight.parent = babylonMesh; + _glTFLoader__WEBPACK_IMPORTED_MODULE_1__["GLTFLoader"].AddPointerMetadata(babylonLight, extensionContext); + assign(babylonMesh); + }); + }); + }; + return KHR_lights; +}()); + +_glTFLoader__WEBPACK_IMPORTED_MODULE_1__["GLTFLoader"].RegisterExtension(NAME, function (loader) { return new KHR_lights(loader); }); + + +/***/ }), + +/***/ "./glTF/2.0/Extensions/KHR_materials_pbrSpecularGlossiness.ts": +/*!********************************************************************!*\ + !*** ./glTF/2.0/Extensions/KHR_materials_pbrSpecularGlossiness.ts ***! + \********************************************************************/ +/*! exports provided: KHR_materials_pbrSpecularGlossiness */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KHR_materials_pbrSpecularGlossiness", function() { return KHR_materials_pbrSpecularGlossiness; }); +/* harmony import */ var babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! babylonjs/Maths/math */ "babylonjs/Misc/observable"); +/* harmony import */ var babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _glTFLoader__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../glTFLoader */ "./glTF/2.0/glTFLoader.ts"); + + + +var NAME = "KHR_materials_pbrSpecularGlossiness"; +/** + * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness) + */ +var KHR_materials_pbrSpecularGlossiness = /** @class */ (function () { + /** @hidden */ + function KHR_materials_pbrSpecularGlossiness(loader) { + /** The name of this extension. */ + this.name = NAME; + /** Defines whether this extension is enabled. */ + this.enabled = true; + this._loader = loader; + } + /** @hidden */ + KHR_materials_pbrSpecularGlossiness.prototype.dispose = function () { + delete this._loader; + }; + /** @hidden */ + KHR_materials_pbrSpecularGlossiness.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) { + var _this = this; + return _glTFLoader__WEBPACK_IMPORTED_MODULE_1__["GLTFLoader"].LoadExtensionAsync(context, material, this.name, function (extensionContext, extension) { + var promises = new Array(); + promises.push(_this._loader.loadMaterialBasePropertiesAsync(context, material, babylonMaterial)); + promises.push(_this._loadSpecularGlossinessPropertiesAsync(extensionContext, material, extension, babylonMaterial)); + _this._loader.loadMaterialAlphaProperties(context, material, babylonMaterial); + return Promise.all(promises).then(function () { }); + }); + }; + KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) { + if (!(babylonMaterial instanceof babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["PBRMaterial"])) { + throw new Error(context + ": Material type not supported"); + } + var promises = new Array(); + babylonMaterial.metallic = null; + babylonMaterial.roughness = null; + if (properties.diffuseFactor) { + babylonMaterial.albedoColor = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Color3"].FromArray(properties.diffuseFactor); + babylonMaterial.alpha = properties.diffuseFactor[3]; + } + else { + babylonMaterial.albedoColor = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Color3"].White(); + } + babylonMaterial.reflectivityColor = properties.specularFactor ? babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Color3"].FromArray(properties.specularFactor) : babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Color3"].White(); + babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor; + if (properties.diffuseTexture) { + promises.push(this._loader.loadTextureInfoAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) { + texture.name = babylonMaterial.name + " (Diffuse)"; + babylonMaterial.albedoTexture = texture; + })); + } + if (properties.specularGlossinessTexture) { + promises.push(this._loader.loadTextureInfoAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) { + texture.name = babylonMaterial.name + " (Specular Glossiness)"; + babylonMaterial.reflectivityTexture = texture; + })); + babylonMaterial.reflectivityTexture.hasAlpha = true; + babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true; + } + return Promise.all(promises).then(function () { }); + }; + return KHR_materials_pbrSpecularGlossiness; +}()); + +_glTFLoader__WEBPACK_IMPORTED_MODULE_1__["GLTFLoader"].RegisterExtension(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); }); + + +/***/ }), + +/***/ "./glTF/2.0/Extensions/KHR_materials_unlit.ts": +/*!****************************************************!*\ + !*** ./glTF/2.0/Extensions/KHR_materials_unlit.ts ***! + \****************************************************/ +/*! exports provided: KHR_materials_unlit */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KHR_materials_unlit", function() { return KHR_materials_unlit; }); +/* harmony import */ var babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! babylonjs/Maths/math */ "babylonjs/Misc/observable"); +/* harmony import */ var babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _glTFLoader__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../glTFLoader */ "./glTF/2.0/glTFLoader.ts"); + + + +var NAME = "KHR_materials_unlit"; +/** + * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit) + */ +var KHR_materials_unlit = /** @class */ (function () { + /** @hidden */ + function KHR_materials_unlit(loader) { + /** The name of this extension. */ + this.name = NAME; + /** Defines whether this extension is enabled. */ + this.enabled = true; + this._loader = loader; + } + /** @hidden */ + KHR_materials_unlit.prototype.dispose = function () { + delete this._loader; + }; + /** @hidden */ + KHR_materials_unlit.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) { + var _this = this; + return _glTFLoader__WEBPACK_IMPORTED_MODULE_1__["GLTFLoader"].LoadExtensionAsync(context, material, this.name, function () { + return _this._loadUnlitPropertiesAsync(context, material, babylonMaterial); + }); + }; + KHR_materials_unlit.prototype._loadUnlitPropertiesAsync = function (context, material, babylonMaterial) { + if (!(babylonMaterial instanceof babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["PBRMaterial"])) { + throw new Error(context + ": Material type not supported"); + } + var promises = new Array(); + babylonMaterial.unlit = true; + var properties = material.pbrMetallicRoughness; + if (properties) { + if (properties.baseColorFactor) { + babylonMaterial.albedoColor = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Color3"].FromArray(properties.baseColorFactor); + babylonMaterial.alpha = properties.baseColorFactor[3]; + } + else { + babylonMaterial.albedoColor = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Color3"].White(); + } + if (properties.baseColorTexture) { + promises.push(this._loader.loadTextureInfoAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) { + texture.name = babylonMaterial.name + " (Base Color)"; + babylonMaterial.albedoTexture = texture; + })); + } + } + if (material.doubleSided) { + babylonMaterial.backFaceCulling = false; + babylonMaterial.twoSidedLighting = true; + } + this._loader.loadMaterialAlphaProperties(context, material, babylonMaterial); + return Promise.all(promises).then(function () { }); + }; + return KHR_materials_unlit; +}()); + +_glTFLoader__WEBPACK_IMPORTED_MODULE_1__["GLTFLoader"].RegisterExtension(NAME, function (loader) { return new KHR_materials_unlit(loader); }); + + +/***/ }), + +/***/ "./glTF/2.0/Extensions/KHR_texture_transform.ts": +/*!******************************************************!*\ + !*** ./glTF/2.0/Extensions/KHR_texture_transform.ts ***! + \******************************************************/ +/*! exports provided: KHR_texture_transform */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KHR_texture_transform", function() { return KHR_texture_transform; }); +/* harmony import */ var babylonjs_Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! babylonjs/Materials/Textures/texture */ "babylonjs/Misc/observable"); +/* harmony import */ var babylonjs_Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _glTFLoader__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../glTFLoader */ "./glTF/2.0/glTFLoader.ts"); + + +var NAME = "KHR_texture_transform"; +/** + * [Specification](https://github.com/KhronosGroup/glTF/blob/master/extensions/2.0/Khronos/KHR_texture_transform/README.md) + */ +var KHR_texture_transform = /** @class */ (function () { + /** @hidden */ + function KHR_texture_transform(loader) { + /** The name of this extension. */ + this.name = NAME; + /** Defines whether this extension is enabled. */ + this.enabled = true; + this._loader = loader; + } + /** @hidden */ + KHR_texture_transform.prototype.dispose = function () { + delete this._loader; + }; + /** @hidden */ + KHR_texture_transform.prototype.loadTextureInfoAsync = function (context, textureInfo, assign) { + var _this = this; + return _glTFLoader__WEBPACK_IMPORTED_MODULE_1__["GLTFLoader"].LoadExtensionAsync(context, textureInfo, this.name, function (extensionContext, extension) { + return _this._loader.loadTextureInfoAsync(context, textureInfo, function (babylonTexture) { + if (!(babylonTexture instanceof babylonjs_Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_0__["Texture"])) { + throw new Error(extensionContext + ": Texture type not supported"); + } + if (extension.offset) { + babylonTexture.uOffset = extension.offset[0]; + babylonTexture.vOffset = extension.offset[1]; + } + // Always rotate around the origin. + babylonTexture.uRotationCenter = 0; + babylonTexture.vRotationCenter = 0; + if (extension.rotation) { + babylonTexture.wAng = -extension.rotation; + } + if (extension.scale) { + babylonTexture.uScale = extension.scale[0]; + babylonTexture.vScale = extension.scale[1]; + } + if (extension.texCoord != undefined) { + babylonTexture.coordinatesIndex = extension.texCoord; + } + assign(babylonTexture); + }); + }); + }; + return KHR_texture_transform; +}()); + +_glTFLoader__WEBPACK_IMPORTED_MODULE_1__["GLTFLoader"].RegisterExtension(NAME, function (loader) { return new KHR_texture_transform(loader); }); + + +/***/ }), + +/***/ "./glTF/2.0/Extensions/MSFT_audio_emitter.ts": +/*!***************************************************!*\ + !*** ./glTF/2.0/Extensions/MSFT_audio_emitter.ts ***! + \***************************************************/ +/*! exports provided: MSFT_audio_emitter */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MSFT_audio_emitter", function() { return MSFT_audio_emitter; }); +/* harmony import */ var babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! babylonjs/Maths/math */ "babylonjs/Misc/observable"); +/* harmony import */ var babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _glTFLoader__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../glTFLoader */ "./glTF/2.0/glTFLoader.ts"); + + + + + + +var NAME = "MSFT_audio_emitter"; +/** + * [Specification](https://github.com/najadojo/glTF/tree/MSFT_audio_emitter/extensions/2.0/Vendor/MSFT_audio_emitter) + */ +var MSFT_audio_emitter = /** @class */ (function () { + /** @hidden */ + function MSFT_audio_emitter(loader) { + /** The name of this extension. */ + this.name = NAME; + /** Defines whether this extension is enabled. */ + this.enabled = true; + this._loader = loader; + } + /** @hidden */ + MSFT_audio_emitter.prototype.dispose = function () { + delete this._loader; + delete this._clips; + delete this._emitters; + }; + /** @hidden */ + MSFT_audio_emitter.prototype.onLoading = function () { + var extensions = this._loader.gltf.extensions; + if (extensions && extensions[this.name]) { + var extension = extensions[this.name]; + this._clips = extension.clips; + this._emitters = extension.emitters; + _glTFLoader__WEBPACK_IMPORTED_MODULE_1__["ArrayItem"].Assign(this._clips); + _glTFLoader__WEBPACK_IMPORTED_MODULE_1__["ArrayItem"].Assign(this._emitters); + } + }; + /** @hidden */ + MSFT_audio_emitter.prototype.loadSceneAsync = function (context, scene) { + var _this = this; + return _glTFLoader__WEBPACK_IMPORTED_MODULE_1__["GLTFLoader"].LoadExtensionAsync(context, scene, this.name, function (extensionContext, extension) { + var promises = new Array(); + promises.push(_this._loader.loadSceneAsync(context, scene)); + for (var _i = 0, _a = extension.emitters; _i < _a.length; _i++) { + var emitterIndex = _a[_i]; + var emitter = _glTFLoader__WEBPACK_IMPORTED_MODULE_1__["ArrayItem"].Get(extensionContext + "/emitters", _this._emitters, emitterIndex); + if (emitter.refDistance != undefined || emitter.maxDistance != undefined || emitter.rolloffFactor != undefined || + emitter.distanceModel != undefined || emitter.innerAngle != undefined || emitter.outerAngle != undefined) { + throw new Error(extensionContext + ": Direction or Distance properties are not allowed on emitters attached to a scene"); + } + promises.push(_this._loadEmitterAsync(extensionContext + "/emitters/" + emitter.index, emitter)); + } + return Promise.all(promises).then(function () { }); + }); + }; + /** @hidden */ + MSFT_audio_emitter.prototype.loadNodeAsync = function (context, node, assign) { + var _this = this; + return _glTFLoader__WEBPACK_IMPORTED_MODULE_1__["GLTFLoader"].LoadExtensionAsync(context, node, this.name, function (extensionContext, extension) { + var promises = new Array(); + return _this._loader.loadNodeAsync(extensionContext, node, function (babylonMesh) { + var _loop_1 = function (emitterIndex) { + var emitter = _glTFLoader__WEBPACK_IMPORTED_MODULE_1__["ArrayItem"].Get(extensionContext + "/emitters", _this._emitters, emitterIndex); + promises.push(_this._loadEmitterAsync(extensionContext + "/emitters/" + emitter.index, emitter).then(function () { + for (var _i = 0, _a = emitter._babylonSounds; _i < _a.length; _i++) { + var sound = _a[_i]; + sound.attachToMesh(babylonMesh); + if (emitter.innerAngle != undefined || emitter.outerAngle != undefined) { + sound.setLocalDirectionToMesh(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Forward()); + sound.setDirectionalCone(2 * babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].ToDegrees(emitter.innerAngle == undefined ? Math.PI : emitter.innerAngle), 2 * babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].ToDegrees(emitter.outerAngle == undefined ? Math.PI : emitter.outerAngle), 0); + } + } + })); + }; + for (var _i = 0, _a = extension.emitters; _i < _a.length; _i++) { + var emitterIndex = _a[_i]; + _loop_1(emitterIndex); + } + assign(babylonMesh); + }).then(function (babylonMesh) { + return Promise.all(promises).then(function () { + return babylonMesh; + }); + }); + }); + }; + /** @hidden */ + MSFT_audio_emitter.prototype.loadAnimationAsync = function (context, animation) { + var _this = this; + return _glTFLoader__WEBPACK_IMPORTED_MODULE_1__["GLTFLoader"].LoadExtensionAsync(context, animation, this.name, function (extensionContext, extension) { + return _this._loader.loadAnimationAsync(context, animation).then(function (babylonAnimationGroup) { + var promises = new Array(); + _glTFLoader__WEBPACK_IMPORTED_MODULE_1__["ArrayItem"].Assign(extension.events); + for (var _i = 0, _a = extension.events; _i < _a.length; _i++) { + var event_1 = _a[_i]; + promises.push(_this._loadAnimationEventAsync(extensionContext + "/events/" + event_1.index, context, animation, event_1, babylonAnimationGroup)); + } + return Promise.all(promises).then(function () { + return babylonAnimationGroup; + }); + }); + }); + }; + MSFT_audio_emitter.prototype._loadClipAsync = function (context, clip) { + if (clip._objectURL) { + return clip._objectURL; + } + var promise; + if (clip.uri) { + promise = this._loader.loadUriAsync(context, clip, clip.uri); + } + else { + var bufferView = _glTFLoader__WEBPACK_IMPORTED_MODULE_1__["ArrayItem"].Get(context + "/bufferView", this._loader.gltf.bufferViews, clip.bufferView); + promise = this._loader.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView); + } + clip._objectURL = promise.then(function (data) { + return URL.createObjectURL(new Blob([data], { type: clip.mimeType })); + }); + return clip._objectURL; + }; + MSFT_audio_emitter.prototype._loadEmitterAsync = function (context, emitter) { + var _this = this; + emitter._babylonSounds = emitter._babylonSounds || []; + if (!emitter._babylonData) { + var clipPromises = new Array(); + var name_1 = emitter.name || "emitter" + emitter.index; + var options_1 = { + loop: false, + autoplay: false, + volume: emitter.volume == undefined ? 1 : emitter.volume, + }; + var _loop_2 = function (i) { + var clipContext = "#/extensions/" + this_1.name + "/clips"; + var clip = _glTFLoader__WEBPACK_IMPORTED_MODULE_1__["ArrayItem"].Get(clipContext, this_1._clips, emitter.clips[i].clip); + clipPromises.push(this_1._loadClipAsync(clipContext + "/" + emitter.clips[i].clip, clip).then(function (objectURL) { + var sound = emitter._babylonSounds[i] = new babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Sound"](name_1, objectURL, _this._loader.babylonScene, null, options_1); + sound.refDistance = emitter.refDistance || 1; + sound.maxDistance = emitter.maxDistance || 256; + sound.rolloffFactor = emitter.rolloffFactor || 1; + sound.distanceModel = emitter.distanceModel || 'exponential'; + sound._positionInEmitterSpace = true; + })); + }; + var this_1 = this; + for (var i = 0; i < emitter.clips.length; i++) { + _loop_2(i); + } + var promise = Promise.all(clipPromises).then(function () { + var weights = emitter.clips.map(function (clip) { return clip.weight || 1; }); + var weightedSound = new babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["WeightedSound"](emitter.loop || false, emitter._babylonSounds, weights); + if (emitter.innerAngle) { + weightedSound.directionalConeInnerAngle = 2 * babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].ToDegrees(emitter.innerAngle); + } + if (emitter.outerAngle) { + weightedSound.directionalConeOuterAngle = 2 * babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].ToDegrees(emitter.outerAngle); + } + if (emitter.volume) { + weightedSound.volume = emitter.volume; + } + emitter._babylonData.sound = weightedSound; + }); + emitter._babylonData = { + loaded: promise + }; + } + return emitter._babylonData.loaded; + }; + MSFT_audio_emitter.prototype._getEventAction = function (context, sound, action, time, startOffset) { + switch (action) { + case "play" /* play */: { + return function (currentFrame) { + var frameOffset = (startOffset || 0) + (currentFrame - time); + sound.play(frameOffset); + }; + } + case "stop" /* stop */: { + return function (currentFrame) { + sound.stop(); + }; + } + case "pause" /* pause */: { + return function (currentFrame) { + sound.pause(); + }; + } + default: { + throw new Error(context + ": Unsupported action " + action); + } + } + }; + MSFT_audio_emitter.prototype._loadAnimationEventAsync = function (context, animationContext, animation, event, babylonAnimationGroup) { + var _this = this; + if (babylonAnimationGroup.targetedAnimations.length == 0) { + return Promise.resolve(); + } + var babylonAnimation = babylonAnimationGroup.targetedAnimations[0]; + var emitterIndex = event.emitter; + var emitter = _glTFLoader__WEBPACK_IMPORTED_MODULE_1__["ArrayItem"].Get("#/extensions/" + this.name + "/emitters", this._emitters, emitterIndex); + return this._loadEmitterAsync(context, emitter).then(function () { + var sound = emitter._babylonData.sound; + if (sound) { + var babylonAnimationEvent = new babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["AnimationEvent"](event.time, _this._getEventAction(context, sound, event.action, event.time, event.startOffset)); + babylonAnimation.animation.addEvent(babylonAnimationEvent); + // Make sure all started audio stops when this animation is terminated. + babylonAnimationGroup.onAnimationGroupEndObservable.add(function () { + sound.stop(); + }); + babylonAnimationGroup.onAnimationGroupPauseObservable.add(function () { + sound.pause(); + }); + } + }); + }; + return MSFT_audio_emitter; +}()); + +_glTFLoader__WEBPACK_IMPORTED_MODULE_1__["GLTFLoader"].RegisterExtension(NAME, function (loader) { return new MSFT_audio_emitter(loader); }); + + +/***/ }), + +/***/ "./glTF/2.0/Extensions/MSFT_lod.ts": +/*!*****************************************!*\ + !*** ./glTF/2.0/Extensions/MSFT_lod.ts ***! + \*****************************************/ +/*! exports provided: MSFT_lod */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MSFT_lod", function() { return MSFT_lod; }); +/* harmony import */ var babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! babylonjs/Misc/observable */ "babylonjs/Misc/observable"); +/* harmony import */ var babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _glTFLoader__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../glTFLoader */ "./glTF/2.0/glTFLoader.ts"); + + + +var NAME = "MSFT_lod"; +/** + * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_lod) + */ +var MSFT_lod = /** @class */ (function () { + /** @hidden */ + function MSFT_lod(loader) { + /** The name of this extension. */ + this.name = NAME; + /** Defines whether this extension is enabled. */ + this.enabled = true; + /** + * Maximum number of LODs to load, starting from the lowest LOD. + */ + this.maxLODsToLoad = Number.MAX_VALUE; + /** + * Observable raised when all node LODs of one level are loaded. + * The event data is the index of the loaded LOD starting from zero. + * Dispose the loader to cancel the loading of the next level of LODs. + */ + this.onNodeLODsLoadedObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](); + /** + * Observable raised when all material LODs of one level are loaded. + * The event data is the index of the loaded LOD starting from zero. + * Dispose the loader to cancel the loading of the next level of LODs. + */ + this.onMaterialLODsLoadedObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](); + this._nodeIndexLOD = null; + this._nodeSignalLODs = new Array(); + this._nodePromiseLODs = new Array(); + this._materialIndexLOD = null; + this._materialSignalLODs = new Array(); + this._materialPromiseLODs = new Array(); + this._loader = loader; + } + /** @hidden */ + MSFT_lod.prototype.dispose = function () { + delete this._loader; + this._nodeIndexLOD = null; + this._nodeSignalLODs.length = 0; + this._nodePromiseLODs.length = 0; + this._materialIndexLOD = null; + this._materialSignalLODs.length = 0; + this._materialPromiseLODs.length = 0; + this.onMaterialLODsLoadedObservable.clear(); + this.onNodeLODsLoadedObservable.clear(); + }; + /** @hidden */ + MSFT_lod.prototype.onReady = function () { + var _this = this; + var _loop_1 = function (indexLOD) { + var promise = Promise.all(this_1._nodePromiseLODs[indexLOD]).then(function () { + if (indexLOD !== 0) { + _this._loader.endPerformanceCounter("Node LOD " + indexLOD); + } + _this._loader.log("Loaded node LOD " + indexLOD); + _this.onNodeLODsLoadedObservable.notifyObservers(indexLOD); + if (indexLOD !== _this._nodePromiseLODs.length - 1) { + _this._loader.startPerformanceCounter("Node LOD " + (indexLOD + 1)); + if (_this._nodeSignalLODs[indexLOD]) { + _this._nodeSignalLODs[indexLOD].resolve(); + } + } + }); + this_1._loader._completePromises.push(promise); + }; + var this_1 = this; + for (var indexLOD = 0; indexLOD < this._nodePromiseLODs.length; indexLOD++) { + _loop_1(indexLOD); + } + var _loop_2 = function (indexLOD) { + var promise = Promise.all(this_2._materialPromiseLODs[indexLOD]).then(function () { + if (indexLOD !== 0) { + _this._loader.endPerformanceCounter("Material LOD " + indexLOD); + } + _this._loader.log("Loaded material LOD " + indexLOD); + _this.onMaterialLODsLoadedObservable.notifyObservers(indexLOD); + if (indexLOD !== _this._materialPromiseLODs.length - 1) { + _this._loader.startPerformanceCounter("Material LOD " + (indexLOD + 1)); + if (_this._materialSignalLODs[indexLOD]) { + _this._materialSignalLODs[indexLOD].resolve(); + } + } + }); + this_2._loader._completePromises.push(promise); + }; + var this_2 = this; + for (var indexLOD = 0; indexLOD < this._materialPromiseLODs.length; indexLOD++) { + _loop_2(indexLOD); + } + }; + /** @hidden */ + MSFT_lod.prototype.loadNodeAsync = function (context, node, assign) { + var _this = this; + return _glTFLoader__WEBPACK_IMPORTED_MODULE_1__["GLTFLoader"].LoadExtensionAsync(context, node, this.name, function (extensionContext, extension) { + var firstPromise; + var nodeLODs = _this._getLODs(extensionContext, node, _this._loader.gltf.nodes, extension.ids); + _this._loader.logOpen("" + extensionContext); + var _loop_3 = function (indexLOD) { + var nodeLOD = nodeLODs[indexLOD]; + if (indexLOD !== 0) { + _this._nodeIndexLOD = indexLOD; + _this._nodeSignalLODs[indexLOD] = _this._nodeSignalLODs[indexLOD] || new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Deferred"](); + } + var assign_1 = function (babylonTransformNode) { babylonTransformNode.setEnabled(false); }; + var promise = _this._loader.loadNodeAsync("#/nodes/" + nodeLOD.index, nodeLOD, assign_1).then(function (babylonMesh) { + if (indexLOD !== 0) { + // TODO: should not rely on _babylonMesh + var previousNodeLOD = nodeLODs[indexLOD - 1]; + if (previousNodeLOD._babylonTransformNode) { + previousNodeLOD._babylonTransformNode.dispose(); + delete previousNodeLOD._babylonTransformNode; + _this._disposeUnusedMaterials(); + } + } + babylonMesh.setEnabled(true); + return babylonMesh; + }); + if (indexLOD === 0) { + firstPromise = promise; + } + else { + _this._nodeIndexLOD = null; + } + _this._nodePromiseLODs[indexLOD] = _this._nodePromiseLODs[indexLOD] || []; + _this._nodePromiseLODs[indexLOD].push(promise); + }; + for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) { + _loop_3(indexLOD); + } + _this._loader.logClose(); + return firstPromise; + }); + }; + /** @hidden */ + MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) { + var _this = this; + // Don't load material LODs if already loading a node LOD. + if (this._nodeIndexLOD) { + return null; + } + return _glTFLoader__WEBPACK_IMPORTED_MODULE_1__["GLTFLoader"].LoadExtensionAsync(context, material, this.name, function (extensionContext, extension) { + var firstPromise; + var materialLODs = _this._getLODs(extensionContext, material, _this._loader.gltf.materials, extension.ids); + _this._loader.logOpen("" + extensionContext); + var _loop_4 = function (indexLOD) { + var materialLOD = materialLODs[indexLOD]; + if (indexLOD !== 0) { + _this._materialIndexLOD = indexLOD; + } + var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD.index, materialLOD, babylonMesh, babylonDrawMode, function (babylonMaterial) { + if (indexLOD === 0) { + assign(babylonMaterial); + } + }).then(function (babylonMaterial) { + if (indexLOD !== 0) { + assign(babylonMaterial); + // TODO: should not rely on _data + var previousDataLOD = materialLODs[indexLOD - 1]._data; + if (previousDataLOD[babylonDrawMode]) { + previousDataLOD[babylonDrawMode].babylonMaterial.dispose(); + delete previousDataLOD[babylonDrawMode]; + } + } + return babylonMaterial; + }); + if (indexLOD === 0) { + firstPromise = promise; + } + else { + _this._materialIndexLOD = null; + } + _this._materialPromiseLODs[indexLOD] = _this._materialPromiseLODs[indexLOD] || []; + _this._materialPromiseLODs[indexLOD].push(promise); + }; + for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) { + _loop_4(indexLOD); + } + _this._loader.logClose(); + return firstPromise; + }); + }; + /** @hidden */ + MSFT_lod.prototype._loadUriAsync = function (context, property, uri) { + var _this = this; + // Defer the loading of uris if loading a material or node LOD. + if (this._materialIndexLOD !== null) { + this._loader.log("deferred"); + var previousIndexLOD = this._materialIndexLOD - 1; + this._materialSignalLODs[previousIndexLOD] = this._materialSignalLODs[previousIndexLOD] || new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Deferred"](); + return this._materialSignalLODs[previousIndexLOD].promise.then(function () { + return _this._loader.loadUriAsync(context, property, uri); + }); + } + else if (this._nodeIndexLOD !== null) { + this._loader.log("deferred"); + var previousIndexLOD = this._nodeIndexLOD - 1; + this._nodeSignalLODs[previousIndexLOD] = this._nodeSignalLODs[previousIndexLOD] || new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Deferred"](); + return this._nodeSignalLODs[this._nodeIndexLOD - 1].promise.then(function () { + return _this._loader.loadUriAsync(context, property, uri); + }); + } + return null; + }; + /** + * Gets an array of LOD properties from lowest to highest. + */ + MSFT_lod.prototype._getLODs = function (context, property, array, ids) { + if (this.maxLODsToLoad <= 0) { + throw new Error("maxLODsToLoad must be greater than zero"); + } + var properties = new Array(); + for (var i = ids.length - 1; i >= 0; i--) { + properties.push(_glTFLoader__WEBPACK_IMPORTED_MODULE_1__["ArrayItem"].Get(context + "/ids/" + ids[i], array, ids[i])); + if (properties.length === this.maxLODsToLoad) { + return properties; + } + } + properties.push(property); + return properties; + }; + MSFT_lod.prototype._disposeUnusedMaterials = function () { + // TODO: should not rely on _data + var materials = this._loader.gltf.materials; + if (materials) { + for (var _i = 0, materials_1 = materials; _i < materials_1.length; _i++) { + var material = materials_1[_i]; + if (material._data) { + for (var drawMode in material._data) { + var data = material._data[drawMode]; + if (data.babylonMeshes.length === 0) { + data.babylonMaterial.dispose(false, true); + delete material._data[drawMode]; + } + } + } + } + } + }; + return MSFT_lod; +}()); + +_glTFLoader__WEBPACK_IMPORTED_MODULE_1__["GLTFLoader"].RegisterExtension(NAME, function (loader) { return new MSFT_lod(loader); }); + + +/***/ }), + +/***/ "./glTF/2.0/Extensions/MSFT_minecraftMesh.ts": +/*!***************************************************!*\ + !*** ./glTF/2.0/Extensions/MSFT_minecraftMesh.ts ***! + \***************************************************/ +/*! exports provided: MSFT_minecraftMesh */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MSFT_minecraftMesh", function() { return MSFT_minecraftMesh; }); +/* harmony import */ var babylonjs_Materials_PBR_pbrMaterial__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! babylonjs/Materials/PBR/pbrMaterial */ "babylonjs/Misc/observable"); +/* harmony import */ var babylonjs_Materials_PBR_pbrMaterial__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Materials_PBR_pbrMaterial__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _glTFLoader__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../glTFLoader */ "./glTF/2.0/glTFLoader.ts"); + + +var NAME = "MSFT_minecraftMesh"; +/** @hidden */ +var MSFT_minecraftMesh = /** @class */ (function () { + function MSFT_minecraftMesh(loader) { + this.name = NAME; + this.enabled = true; + this._loader = loader; + } + MSFT_minecraftMesh.prototype.dispose = function () { + delete this._loader; + }; + MSFT_minecraftMesh.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) { + var _this = this; + return _glTFLoader__WEBPACK_IMPORTED_MODULE_1__["GLTFLoader"].LoadExtraAsync(context, material, this.name, function (extraContext, extra) { + if (extra) { + if (!(babylonMaterial instanceof babylonjs_Materials_PBR_pbrMaterial__WEBPACK_IMPORTED_MODULE_0__["PBRMaterial"])) { + throw new Error(extraContext + ": Material type not supported"); + } + var promise = _this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial); + if (babylonMaterial.needAlphaBlending()) { + babylonMaterial.forceDepthWrite = true; + babylonMaterial.separateCullingPass = true; + } + babylonMaterial.backFaceCulling = babylonMaterial.forceDepthWrite; + babylonMaterial.twoSidedLighting = true; + return promise; + } + return null; + }); + }; + return MSFT_minecraftMesh; +}()); + +_glTFLoader__WEBPACK_IMPORTED_MODULE_1__["GLTFLoader"].RegisterExtension(NAME, function (loader) { return new MSFT_minecraftMesh(loader); }); + + +/***/ }), + +/***/ "./glTF/2.0/Extensions/MSFT_sRGBFactors.ts": +/*!*************************************************!*\ + !*** ./glTF/2.0/Extensions/MSFT_sRGBFactors.ts ***! + \*************************************************/ +/*! exports provided: MSFT_sRGBFactors */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MSFT_sRGBFactors", function() { return MSFT_sRGBFactors; }); +/* harmony import */ var babylonjs_Materials_PBR_pbrMaterial__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! babylonjs/Materials/PBR/pbrMaterial */ "babylonjs/Misc/observable"); +/* harmony import */ var babylonjs_Materials_PBR_pbrMaterial__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Materials_PBR_pbrMaterial__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _glTFLoader__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../glTFLoader */ "./glTF/2.0/glTFLoader.ts"); + + +var NAME = "MSFT_sRGBFactors"; +/** @hidden */ +var MSFT_sRGBFactors = /** @class */ (function () { + function MSFT_sRGBFactors(loader) { + this.name = NAME; + this.enabled = true; + this._loader = loader; + } + MSFT_sRGBFactors.prototype.dispose = function () { + delete this._loader; + }; + MSFT_sRGBFactors.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) { + var _this = this; + return _glTFLoader__WEBPACK_IMPORTED_MODULE_1__["GLTFLoader"].LoadExtraAsync(context, material, this.name, function (extraContext, extra) { + if (extra) { + if (!(babylonMaterial instanceof babylonjs_Materials_PBR_pbrMaterial__WEBPACK_IMPORTED_MODULE_0__["PBRMaterial"])) { + throw new Error(extraContext + ": Material type not supported"); + } + var promise = _this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial); + if (!babylonMaterial.albedoTexture) { + babylonMaterial.albedoColor.toLinearSpaceToRef(babylonMaterial.albedoColor); + } + if (!babylonMaterial.reflectivityTexture) { + babylonMaterial.reflectivityColor.toLinearSpaceToRef(babylonMaterial.reflectivityColor); + } + return promise; + } + return null; + }); + }; + return MSFT_sRGBFactors; +}()); + +_glTFLoader__WEBPACK_IMPORTED_MODULE_1__["GLTFLoader"].RegisterExtension(NAME, function (loader) { return new MSFT_sRGBFactors(loader); }); + + +/***/ }), + +/***/ "./glTF/2.0/Extensions/index.ts": +/*!**************************************!*\ + !*** ./glTF/2.0/Extensions/index.ts ***! + \**************************************/ +/*! exports provided: EXT_lights_image_based, KHR_draco_mesh_compression, KHR_lights, KHR_materials_pbrSpecularGlossiness, KHR_materials_unlit, KHR_texture_transform, MSFT_audio_emitter, MSFT_lod, MSFT_minecraftMesh, MSFT_sRGBFactors */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _EXT_lights_image_based__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./EXT_lights_image_based */ "./glTF/2.0/Extensions/EXT_lights_image_based.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EXT_lights_image_based", function() { return _EXT_lights_image_based__WEBPACK_IMPORTED_MODULE_0__["EXT_lights_image_based"]; }); + +/* harmony import */ var _KHR_draco_mesh_compression__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./KHR_draco_mesh_compression */ "./glTF/2.0/Extensions/KHR_draco_mesh_compression.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KHR_draco_mesh_compression", function() { return _KHR_draco_mesh_compression__WEBPACK_IMPORTED_MODULE_1__["KHR_draco_mesh_compression"]; }); + +/* harmony import */ var _KHR_lights_punctual__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./KHR_lights_punctual */ "./glTF/2.0/Extensions/KHR_lights_punctual.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KHR_lights", function() { return _KHR_lights_punctual__WEBPACK_IMPORTED_MODULE_2__["KHR_lights"]; }); + +/* harmony import */ var _KHR_materials_pbrSpecularGlossiness__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./KHR_materials_pbrSpecularGlossiness */ "./glTF/2.0/Extensions/KHR_materials_pbrSpecularGlossiness.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KHR_materials_pbrSpecularGlossiness", function() { return _KHR_materials_pbrSpecularGlossiness__WEBPACK_IMPORTED_MODULE_3__["KHR_materials_pbrSpecularGlossiness"]; }); + +/* harmony import */ var _KHR_materials_unlit__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./KHR_materials_unlit */ "./glTF/2.0/Extensions/KHR_materials_unlit.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KHR_materials_unlit", function() { return _KHR_materials_unlit__WEBPACK_IMPORTED_MODULE_4__["KHR_materials_unlit"]; }); + +/* harmony import */ var _KHR_texture_transform__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./KHR_texture_transform */ "./glTF/2.0/Extensions/KHR_texture_transform.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KHR_texture_transform", function() { return _KHR_texture_transform__WEBPACK_IMPORTED_MODULE_5__["KHR_texture_transform"]; }); + +/* harmony import */ var _MSFT_audio_emitter__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./MSFT_audio_emitter */ "./glTF/2.0/Extensions/MSFT_audio_emitter.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MSFT_audio_emitter", function() { return _MSFT_audio_emitter__WEBPACK_IMPORTED_MODULE_6__["MSFT_audio_emitter"]; }); + +/* harmony import */ var _MSFT_lod__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./MSFT_lod */ "./glTF/2.0/Extensions/MSFT_lod.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MSFT_lod", function() { return _MSFT_lod__WEBPACK_IMPORTED_MODULE_7__["MSFT_lod"]; }); + +/* harmony import */ var _MSFT_minecraftMesh__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./MSFT_minecraftMesh */ "./glTF/2.0/Extensions/MSFT_minecraftMesh.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MSFT_minecraftMesh", function() { return _MSFT_minecraftMesh__WEBPACK_IMPORTED_MODULE_8__["MSFT_minecraftMesh"]; }); + +/* harmony import */ var _MSFT_sRGBFactors__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./MSFT_sRGBFactors */ "./glTF/2.0/Extensions/MSFT_sRGBFactors.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MSFT_sRGBFactors", function() { return _MSFT_sRGBFactors__WEBPACK_IMPORTED_MODULE_9__["MSFT_sRGBFactors"]; }); + + + + + + + + + + + + + +/***/ }), + +/***/ "./glTF/2.0/glTFLoader.ts": +/*!********************************!*\ + !*** ./glTF/2.0/glTFLoader.ts ***! + \********************************/ +/*! exports provided: ArrayItem, GLTFLoader */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ArrayItem", function() { return ArrayItem; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GLTFLoader", function() { return GLTFLoader; }); +/* harmony import */ var babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! babylonjs/Misc/deferred */ "babylonjs/Misc/observable"); +/* harmony import */ var babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _glTFFileLoader__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../glTFFileLoader */ "./glTF/glTFFileLoader.ts"); + + + + + + + + + + + + + + + + + + + + + +/** + * Helper class for working with arrays when loading the glTF asset + */ +var ArrayItem = /** @class */ (function () { + function ArrayItem() { + } + /** + * Gets an item from the given array. + * @param context The context when loading the asset + * @param array The array to get the item from + * @param index The index to the array + * @returns The array item + */ + ArrayItem.Get = function (context, array, index) { + if (!array || index == undefined || !array[index]) { + throw new Error(context + ": Failed to find index (" + index + ")"); + } + return array[index]; + }; + /** + * Assign an `index` field to each item of the given array. + * @param array The array of items + */ + ArrayItem.Assign = function (array) { + if (array) { + for (var index = 0; index < array.length; index++) { + array[index].index = index; + } + } + }; + return ArrayItem; +}()); + +/** + * The glTF 2.0 loader + */ +var GLTFLoader = /** @class */ (function () { + /** @hidden */ + function GLTFLoader(parent) { + /** @hidden */ + this._completePromises = new Array(); + this._disposed = false; + this._state = null; + this._extensions = {}; + this._defaultBabylonMaterialData = {}; + this._requests = new Array(); + this._parent = parent; + } + /** + * Registers a loader extension. + * @param name The name of the loader extension. + * @param factory The factory function that creates the loader extension. + */ + GLTFLoader.RegisterExtension = function (name, factory) { + if (GLTFLoader.UnregisterExtension(name)) { + babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Tools"].Warn("Extension with the name '" + name + "' already exists"); + } + GLTFLoader._ExtensionFactories[name] = factory; + // Keep the order of registration so that extensions registered first are called first. + GLTFLoader._ExtensionNames.push(name); + }; + /** + * Unregisters a loader extension. + * @param name The name of the loader extenion. + * @returns A boolean indicating whether the extension has been unregistered + */ + GLTFLoader.UnregisterExtension = function (name) { + if (!GLTFLoader._ExtensionFactories[name]) { + return false; + } + delete GLTFLoader._ExtensionFactories[name]; + var index = GLTFLoader._ExtensionNames.indexOf(name); + if (index !== -1) { + GLTFLoader._ExtensionNames.splice(index, 1); + } + return true; + }; + Object.defineProperty(GLTFLoader.prototype, "state", { + /** + * Gets the loader state. + */ + get: function () { + return this._state; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(GLTFLoader.prototype, "gltf", { + /** + * The glTF object parsed from the JSON. + */ + get: function () { + return this._gltf; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(GLTFLoader.prototype, "babylonScene", { + /** + * The Babylon scene when loading the asset. + */ + get: function () { + return this._babylonScene; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(GLTFLoader.prototype, "rootBabylonMesh", { + /** + * The root Babylon mesh when loading the asset. + */ + get: function () { + return this._rootBabylonMesh; + }, + enumerable: true, + configurable: true + }); + /** @hidden */ + GLTFLoader.prototype.dispose = function () { + if (this._disposed) { + return; + } + this._disposed = true; + for (var _i = 0, _a = this._requests; _i < _a.length; _i++) { + var request = _a[_i]; + request.abort(); + } + this._requests.length = 0; + this._completePromises.length = 0; + for (var name_1 in this._extensions) { + var extension = this._extensions[name_1]; + if (extension.dispose) { + this._extensions[name_1].dispose(); + } + } + this._extensions = {}; + delete this._gltf; + delete this._babylonScene; + delete this._rootBabylonMesh; + delete this._progressCallback; + this._parent._clear(); + }; + /** @hidden */ + GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress, fileName) { + var _this = this; + return Promise.resolve().then(function () { + _this._babylonScene = scene; + _this._rootUrl = rootUrl; + _this._fileName = fileName || "scene"; + _this._progressCallback = onProgress; + _this._loadData(data); + var nodes = null; + if (meshesNames) { + var nodeMap_1 = {}; + if (_this._gltf.nodes) { + for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) { + var node = _a[_i]; + if (node.name) { + nodeMap_1[node.name] = node.index; + } + } + } + var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames]; + nodes = names.map(function (name) { + var node = nodeMap_1[name]; + if (node === undefined) { + throw new Error("Failed to find node '" + name + "'"); + } + return node; + }); + } + return _this._loadAsync(nodes, function () { + return { + meshes: _this._getMeshes(), + particleSystems: [], + skeletons: _this._getSkeletons(), + animationGroups: _this._getAnimationGroups() + }; + }); + }); + }; + /** @hidden */ + GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress, fileName) { + var _this = this; + return Promise.resolve().then(function () { + _this._babylonScene = scene; + _this._rootUrl = rootUrl; + _this._fileName = fileName || "scene"; + _this._progressCallback = onProgress; + _this._loadData(data); + return _this._loadAsync(null, function () { return undefined; }); + }); + }; + GLTFLoader.prototype._loadAsync = function (nodes, resultFunc) { + var _this = this; + return Promise.resolve().then(function () { + _this._uniqueRootUrl = (_this._rootUrl.indexOf("file:") === -1 && _this._fileName) ? _this._rootUrl : "" + _this._rootUrl + Date.now() + "/"; + _this._loadExtensions(); + _this._checkExtensions(); + var loadingToReadyCounterName = _glTFFileLoader__WEBPACK_IMPORTED_MODULE_1__["GLTFLoaderState"][_glTFFileLoader__WEBPACK_IMPORTED_MODULE_1__["GLTFLoaderState"].LOADING] + " => " + _glTFFileLoader__WEBPACK_IMPORTED_MODULE_1__["GLTFLoaderState"][_glTFFileLoader__WEBPACK_IMPORTED_MODULE_1__["GLTFLoaderState"].READY]; + var loadingToCompleteCounterName = _glTFFileLoader__WEBPACK_IMPORTED_MODULE_1__["GLTFLoaderState"][_glTFFileLoader__WEBPACK_IMPORTED_MODULE_1__["GLTFLoaderState"].LOADING] + " => " + _glTFFileLoader__WEBPACK_IMPORTED_MODULE_1__["GLTFLoaderState"][_glTFFileLoader__WEBPACK_IMPORTED_MODULE_1__["GLTFLoaderState"].COMPLETE]; + _this._parent._startPerformanceCounter(loadingToReadyCounterName); + _this._parent._startPerformanceCounter(loadingToCompleteCounterName); + _this._setState(_glTFFileLoader__WEBPACK_IMPORTED_MODULE_1__["GLTFLoaderState"].LOADING); + _this._extensionsOnLoading(); + var promises = new Array(); + // Block the marking of materials dirty until the scene is loaded. + var oldBlockMaterialDirtyMechanism = _this._babylonScene.blockMaterialDirtyMechanism; + _this._babylonScene.blockMaterialDirtyMechanism = true; + if (nodes) { + promises.push(_this.loadSceneAsync("/nodes", { nodes: nodes, index: -1 })); + } + else if (_this._gltf.scene != undefined || (_this._gltf.scenes && _this._gltf.scenes[0])) { + var scene = ArrayItem.Get("/scene", _this._gltf.scenes, _this._gltf.scene || 0); + promises.push(_this.loadSceneAsync("/scenes/" + scene.index, scene)); + } + // Restore the blocking of material dirty. + _this._babylonScene.blockMaterialDirtyMechanism = oldBlockMaterialDirtyMechanism; + if (_this._parent.compileMaterials) { + promises.push(_this._compileMaterialsAsync()); + } + if (_this._parent.compileShadowGenerators) { + promises.push(_this._compileShadowGeneratorsAsync()); + } + var resultPromise = Promise.all(promises).then(function () { + if (_this._rootBabylonMesh) { + _this._rootBabylonMesh.setEnabled(true); + } + _this._setState(_glTFFileLoader__WEBPACK_IMPORTED_MODULE_1__["GLTFLoaderState"].READY); + _this._extensionsOnReady(); + _this._startAnimations(); + return resultFunc(); + }); + resultPromise.then(function () { + _this._parent._endPerformanceCounter(loadingToReadyCounterName); + babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Tools"].SetImmediate(function () { + if (!_this._disposed) { + Promise.all(_this._completePromises).then(function () { + _this._parent._endPerformanceCounter(loadingToCompleteCounterName); + _this._setState(_glTFFileLoader__WEBPACK_IMPORTED_MODULE_1__["GLTFLoaderState"].COMPLETE); + _this._parent.onCompleteObservable.notifyObservers(undefined); + _this._parent.onCompleteObservable.clear(); + _this.dispose(); + }, function (error) { + _this._parent.onErrorObservable.notifyObservers(error); + _this._parent.onErrorObservable.clear(); + _this.dispose(); + }); + } + }); + }); + return resultPromise; + }, function (error) { + if (!_this._disposed) { + _this._parent.onErrorObservable.notifyObservers(error); + _this._parent.onErrorObservable.clear(); + _this.dispose(); + } + throw error; + }); + }; + GLTFLoader.prototype._loadData = function (data) { + this._gltf = data.json; + this._setupData(); + if (data.bin) { + var buffers = this._gltf.buffers; + if (buffers && buffers[0] && !buffers[0].uri) { + var binaryBuffer = buffers[0]; + if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) { + babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Tools"].Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")"); + } + binaryBuffer._data = Promise.resolve(data.bin); + } + else { + babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Tools"].Warn("Unexpected BIN chunk"); + } + } + }; + GLTFLoader.prototype._setupData = function () { + ArrayItem.Assign(this._gltf.accessors); + ArrayItem.Assign(this._gltf.animations); + ArrayItem.Assign(this._gltf.buffers); + ArrayItem.Assign(this._gltf.bufferViews); + ArrayItem.Assign(this._gltf.cameras); + ArrayItem.Assign(this._gltf.images); + ArrayItem.Assign(this._gltf.materials); + ArrayItem.Assign(this._gltf.meshes); + ArrayItem.Assign(this._gltf.nodes); + ArrayItem.Assign(this._gltf.samplers); + ArrayItem.Assign(this._gltf.scenes); + ArrayItem.Assign(this._gltf.skins); + ArrayItem.Assign(this._gltf.textures); + if (this._gltf.nodes) { + var nodeParents = {}; + for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) { + var node = _a[_i]; + if (node.children) { + for (var _b = 0, _c = node.children; _b < _c.length; _b++) { + var index = _c[_b]; + nodeParents[index] = node.index; + } + } + } + var rootNode = this._createRootNode(); + for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) { + var node = _e[_d]; + var parentIndex = nodeParents[node.index]; + node.parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex]; + } + } + }; + GLTFLoader.prototype._loadExtensions = function () { + for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) { + var name_2 = _a[_i]; + var extension = GLTFLoader._ExtensionFactories[name_2](this); + this._extensions[name_2] = extension; + this._parent.onExtensionLoadedObservable.notifyObservers(extension); + } + this._parent.onExtensionLoadedObservable.clear(); + }; + GLTFLoader.prototype._checkExtensions = function () { + if (this._gltf.extensionsRequired) { + for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) { + var name_3 = _a[_i]; + var extension = this._extensions[name_3]; + if (!extension || !extension.enabled) { + throw new Error("Require extension " + name_3 + " is not available"); + } + } + } + }; + GLTFLoader.prototype._setState = function (state) { + this._state = state; + this.log(_glTFFileLoader__WEBPACK_IMPORTED_MODULE_1__["GLTFLoaderState"][this._state]); + }; + GLTFLoader.prototype._createRootNode = function () { + this._rootBabylonMesh = new babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Mesh"]("__root__", this._babylonScene); + this._rootBabylonMesh.setEnabled(false); + var rootNode = { + _babylonTransformNode: this._rootBabylonMesh, + index: -1 + }; + switch (this._parent.coordinateSystemMode) { + case _glTFFileLoader__WEBPACK_IMPORTED_MODULE_1__["GLTFLoaderCoordinateSystemMode"].AUTO: { + if (!this._babylonScene.useRightHandedSystem) { + rootNode.rotation = [0, 1, 0, 0]; + rootNode.scale = [1, 1, -1]; + GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh); + } + break; + } + case _glTFFileLoader__WEBPACK_IMPORTED_MODULE_1__["GLTFLoaderCoordinateSystemMode"].FORCE_RIGHT_HANDED: { + this._babylonScene.useRightHandedSystem = true; + break; + } + default: { + throw new Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")"); + } + } + this._parent.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh); + return rootNode; + }; + /** + * Loads a glTF scene. + * @param context The context when loading the asset + * @param scene The glTF scene property + * @returns A promise that resolves when the load is complete + */ + GLTFLoader.prototype.loadSceneAsync = function (context, scene) { + var _this = this; + var extensionPromise = this._extensionsLoadSceneAsync(context, scene); + if (extensionPromise) { + return extensionPromise; + } + var promises = new Array(); + this.logOpen(context + " " + (scene.name || "")); + if (scene.nodes) { + for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) { + var index = _a[_i]; + var node = ArrayItem.Get(context + "/nodes/" + index, this._gltf.nodes, index); + promises.push(this.loadNodeAsync("/nodes/" + node.index, node, function (babylonMesh) { + babylonMesh.parent = _this._rootBabylonMesh; + })); + } + } + // Link all Babylon bones for each glTF node with the corresponding Babylon transform node. + // A glTF joint is a pointer to a glTF node in the glTF node hierarchy similar to Unity3D. + if (this._gltf.nodes) { + for (var _b = 0, _c = this._gltf.nodes; _b < _c.length; _b++) { + var node = _c[_b]; + if (node._babylonTransformNode && node._babylonBones) { + for (var _d = 0, _e = node._babylonBones; _d < _e.length; _d++) { + var babylonBone = _e[_d]; + babylonBone.linkTransformNode(node._babylonTransformNode); + } + } + } + } + promises.push(this._loadAnimationsAsync()); + this.logClose(); + return Promise.all(promises).then(function () { }); + }; + GLTFLoader.prototype._forEachPrimitive = function (node, callback) { + if (node._primitiveBabylonMeshes) { + for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) { + var babylonMesh = _a[_i]; + callback(babylonMesh); + } + } + }; + GLTFLoader.prototype._getMeshes = function () { + var meshes = new Array(); + // Root mesh is always first. + meshes.push(this._rootBabylonMesh); + var nodes = this._gltf.nodes; + if (nodes) { + for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { + var node = nodes_1[_i]; + this._forEachPrimitive(node, function (babylonMesh) { + meshes.push(babylonMesh); + }); + } + } + return meshes; + }; + GLTFLoader.prototype._getSkeletons = function () { + var skeletons = new Array(); + var skins = this._gltf.skins; + if (skins) { + for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) { + var skin = skins_1[_i]; + if (skin._data) { + skeletons.push(skin._data.babylonSkeleton); + } + } + } + return skeletons; + }; + GLTFLoader.prototype._getAnimationGroups = function () { + var animationGroups = new Array(); + var animations = this._gltf.animations; + if (animations) { + for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) { + var animation = animations_1[_i]; + if (animation._babylonAnimationGroup) { + animationGroups.push(animation._babylonAnimationGroup); + } + } + } + return animationGroups; + }; + GLTFLoader.prototype._startAnimations = function () { + switch (this._parent.animationStartMode) { + case _glTFFileLoader__WEBPACK_IMPORTED_MODULE_1__["GLTFLoaderAnimationStartMode"].NONE: { + // do nothing + break; + } + case _glTFFileLoader__WEBPACK_IMPORTED_MODULE_1__["GLTFLoaderAnimationStartMode"].FIRST: { + var babylonAnimationGroups = this._getAnimationGroups(); + if (babylonAnimationGroups.length !== 0) { + babylonAnimationGroups[0].start(true); + } + break; + } + case _glTFFileLoader__WEBPACK_IMPORTED_MODULE_1__["GLTFLoaderAnimationStartMode"].ALL: { + var babylonAnimationGroups = this._getAnimationGroups(); + for (var _i = 0, babylonAnimationGroups_1 = babylonAnimationGroups; _i < babylonAnimationGroups_1.length; _i++) { + var babylonAnimationGroup = babylonAnimationGroups_1[_i]; + babylonAnimationGroup.start(true); + } + break; + } + default: { + babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Tools"].Error("Invalid animation start mode (" + this._parent.animationStartMode + ")"); + return; + } + } + }; + /** + * Loads a glTF node. + * @param context The context when loading the asset + * @param node The glTF node property + * @param assign A function called synchronously after parsing the glTF properties + * @returns A promise that resolves with the loaded Babylon mesh when the load is complete + */ + GLTFLoader.prototype.loadNodeAsync = function (context, node, assign) { + var _this = this; + if (assign === void 0) { assign = function () { }; } + var extensionPromise = this._extensionsLoadNodeAsync(context, node, assign); + if (extensionPromise) { + return extensionPromise; + } + if (node._babylonTransformNode) { + throw new Error(context + ": Invalid recursive node hierarchy"); + } + var promises = new Array(); + this.logOpen(context + " " + (node.name || "")); + var loadNode = function (babylonTransformNode) { + GLTFLoader.AddPointerMetadata(babylonTransformNode, context); + GLTFLoader._LoadTransform(node, babylonTransformNode); + if (node.camera != undefined) { + var camera = ArrayItem.Get(context + "/camera", _this._gltf.cameras, node.camera); + promises.push(_this.loadCameraAsync("/cameras/" + camera.index, camera, function (babylonCamera) { + babylonCamera.parent = babylonTransformNode; + })); + } + if (node.children) { + for (var _i = 0, _a = node.children; _i < _a.length; _i++) { + var index = _a[_i]; + var childNode = ArrayItem.Get(context + "/children/" + index, _this._gltf.nodes, index); + promises.push(_this.loadNodeAsync("/nodes/" + childNode.index, childNode, function (childBabylonMesh) { + childBabylonMesh.parent = babylonTransformNode; + })); + } + } + assign(babylonTransformNode); + }; + if (node.mesh == undefined) { + var nodeName = node.name || "node" + node.index; + node._babylonTransformNode = new babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["TransformNode"](nodeName, this._babylonScene); + loadNode(node._babylonTransformNode); + } + else { + var mesh = ArrayItem.Get(context + "/mesh", this._gltf.meshes, node.mesh); + promises.push(this._loadMeshAsync("/meshes/" + mesh.index, node, mesh, loadNode)); + } + this.logClose(); + return Promise.all(promises).then(function () { + _this._forEachPrimitive(node, function (babylonMesh) { + babylonMesh.refreshBoundingInfo(true); + }); + return node._babylonTransformNode; + }); + }; + GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, assign) { + var primitives = mesh.primitives; + if (!primitives || !primitives.length) { + throw new Error(context + ": Primitives are missing"); + } + if (primitives[0].index == undefined) { + ArrayItem.Assign(primitives); + } + var promises = new Array(); + this.logOpen(context + " " + (mesh.name || "")); + var name = node.name || "node" + node.index; + if (primitives.length === 1) { + var primitive = mesh.primitives[0]; + promises.push(this._loadMeshPrimitiveAsync(context + "/primitives/" + primitive.index, name, node, mesh, primitive, function (babylonMesh) { + node._babylonTransformNode = babylonMesh; + node._primitiveBabylonMeshes = [babylonMesh]; + })); + } + else { + node._babylonTransformNode = new babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["TransformNode"](name, this._babylonScene); + node._primitiveBabylonMeshes = []; + for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) { + var primitive = primitives_1[_i]; + promises.push(this._loadMeshPrimitiveAsync(context + "/primitives/" + primitive.index, name + "_primitive" + primitive.index, node, mesh, primitive, function (babylonMesh) { + babylonMesh.parent = node._babylonTransformNode; + node._primitiveBabylonMeshes.push(babylonMesh); + })); + } + } + if (node.skin != undefined) { + var skin = ArrayItem.Get(context + "/skin", this._gltf.skins, node.skin); + promises.push(this._loadSkinAsync("/skins/" + skin.index, node, skin)); + } + assign(node._babylonTransformNode); + this.logClose(); + return Promise.all(promises).then(function () { + return node._babylonTransformNode; + }); + }; + /** + * @hidden Define this method to modify the default behavior when loading data for mesh primitives. + * @param context The context when loading the asset + * @param name The mesh name when loading the asset + * @param node The glTF node when loading the asset + * @param mesh The glTF mesh when loading the asset + * @param primitive The glTF mesh primitive property + * @param assign A function called synchronously after parsing the glTF properties + * @returns A promise that resolves with the loaded mesh when the load is complete or null if not handled + */ + GLTFLoader.prototype._loadMeshPrimitiveAsync = function (context, name, node, mesh, primitive, assign) { + var _this = this; + var extensionPromise = this._extensionsLoadMeshPrimitiveAsync(context, name, node, mesh, primitive, assign); + if (extensionPromise) { + return extensionPromise; + } + this.logOpen("" + context); + var canInstance = (node.skin == undefined && !mesh.primitives[0].targets); + var babylonAbstractMesh; + var promise; + var instanceData = primitive._instanceData; + if (canInstance && instanceData) { + babylonAbstractMesh = instanceData.babylonSourceMesh.createInstance(name); + promise = instanceData.promise; + } + else { + var promises = new Array(); + var babylonMesh_1 = new babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Mesh"](name, this._babylonScene); + this._createMorphTargets(context, node, mesh, primitive, babylonMesh_1); + promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh_1).then(function (babylonGeometry) { + return _this._loadMorphTargetsAsync(context, primitive, babylonMesh_1, babylonGeometry).then(function () { + babylonGeometry.applyToMesh(babylonMesh_1); + }); + })); + var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode); + if (primitive.material == undefined) { + var babylonMaterial = this._defaultBabylonMaterialData[babylonDrawMode]; + if (!babylonMaterial) { + babylonMaterial = this._createDefaultMaterial("__GLTFLoader._default", babylonDrawMode); + this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial); + this._defaultBabylonMaterialData[babylonDrawMode] = babylonMaterial; + } + babylonMesh_1.material = babylonMaterial; + } + else { + var material = ArrayItem.Get(context + "/material", this._gltf.materials, primitive.material); + promises.push(this._loadMaterialAsync("/materials/" + material.index, material, babylonMesh_1, babylonDrawMode, function (babylonMaterial) { + babylonMesh_1.material = babylonMaterial; + })); + } + promise = Promise.all(promises); + if (canInstance) { + primitive._instanceData = { + babylonSourceMesh: babylonMesh_1, + promise: promise + }; + } + babylonAbstractMesh = babylonMesh_1; + } + GLTFLoader.AddPointerMetadata(babylonAbstractMesh, context); + this._parent.onMeshLoadedObservable.notifyObservers(babylonAbstractMesh); + assign(babylonAbstractMesh); + this.logClose(); + return promise.then(function () { + return babylonAbstractMesh; + }); + }; + GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { + var _this = this; + var extensionPromise = this._extensionsLoadVertexDataAsync(context, primitive, babylonMesh); + if (extensionPromise) { + return extensionPromise; + } + var attributes = primitive.attributes; + if (!attributes) { + throw new Error(context + ": Attributes are missing"); + } + var promises = new Array(); + var babylonGeometry = new babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Geometry"](babylonMesh.name, this._babylonScene); + if (primitive.indices == undefined) { + babylonMesh.isUnIndexed = true; + } + else { + var accessor = ArrayItem.Get(context + "/indices", this._gltf.accessors, primitive.indices); + promises.push(this._loadIndicesAccessorAsync("/accessors/" + accessor.index, accessor).then(function (data) { + babylonGeometry.setIndices(data); + })); + } + var loadAttribute = function (attribute, kind, callback) { + if (attributes[attribute] == undefined) { + return; + } + babylonMesh._delayInfo = babylonMesh._delayInfo || []; + if (babylonMesh._delayInfo.indexOf(kind) === -1) { + babylonMesh._delayInfo.push(kind); + } + var accessor = ArrayItem.Get(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]); + promises.push(_this._loadVertexAccessorAsync("/accessors/" + accessor.index, accessor, kind).then(function (babylonVertexBuffer) { + babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count); + })); + if (callback) { + callback(accessor); + } + }; + loadAttribute("POSITION", babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].PositionKind); + loadAttribute("NORMAL", babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].NormalKind); + loadAttribute("TANGENT", babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].TangentKind); + loadAttribute("TEXCOORD_0", babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].UVKind); + loadAttribute("TEXCOORD_1", babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].UV2Kind); + loadAttribute("JOINTS_0", babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].MatricesIndicesKind); + loadAttribute("WEIGHTS_0", babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].MatricesWeightsKind); + loadAttribute("COLOR_0", babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].ColorKind, function (accessor) { + if (accessor.type === "VEC4" /* VEC4 */) { + babylonMesh.hasVertexAlpha = true; + } + }); + return Promise.all(promises).then(function () { + return babylonGeometry; + }); + }; + GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) { + if (!primitive.targets) { + return; + } + if (node._numMorphTargets == undefined) { + node._numMorphTargets = primitive.targets.length; + } + else if (primitive.targets.length !== node._numMorphTargets) { + throw new Error(context + ": Primitives do not have the same number of targets"); + } + babylonMesh.morphTargetManager = new babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["MorphTargetManager"](babylonMesh.getScene()); + for (var index = 0; index < primitive.targets.length; index++) { + var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0; + babylonMesh.morphTargetManager.addTarget(new babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["MorphTarget"]("morphTarget" + index, weight, babylonMesh.getScene())); + // TODO: tell the target whether it has positions, normals, tangents + } + }; + GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonGeometry) { + if (!primitive.targets) { + return Promise.resolve(); + } + var promises = new Array(); + var morphTargetManager = babylonMesh.morphTargetManager; + for (var index = 0; index < morphTargetManager.numTargets; index++) { + var babylonMorphTarget = morphTargetManager.getTarget(index); + promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonGeometry, primitive.targets[index], babylonMorphTarget)); + } + return Promise.all(promises).then(function () { }); + }; + GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonGeometry, attributes, babylonMorphTarget) { + var _this = this; + var promises = new Array(); + var loadAttribute = function (attribute, kind, setData) { + if (attributes[attribute] == undefined) { + return; + } + var babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind); + if (!babylonVertexBuffer) { + return; + } + var accessor = ArrayItem.Get(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]); + promises.push(_this._loadFloatAccessorAsync("/accessors/" + accessor.index, accessor).then(function (data) { + setData(babylonVertexBuffer, data); + })); + }; + loadAttribute("POSITION", babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].PositionKind, function (babylonVertexBuffer, data) { + var positions = new Float32Array(data.length); + babylonVertexBuffer.forEach(data.length, function (value, index) { + positions[index] = data[index] + value; + }); + babylonMorphTarget.setPositions(positions); + }); + loadAttribute("NORMAL", babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].NormalKind, function (babylonVertexBuffer, data) { + var normals = new Float32Array(data.length); + babylonVertexBuffer.forEach(normals.length, function (value, index) { + normals[index] = data[index] + value; + }); + babylonMorphTarget.setNormals(normals); + }); + loadAttribute("TANGENT", babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].TangentKind, function (babylonVertexBuffer, data) { + var tangents = new Float32Array(data.length / 3 * 4); + var dataIndex = 0; + babylonVertexBuffer.forEach(data.length / 3 * 4, function (value, index) { + // Tangent data for morph targets is stored as xyz delta. + // The vertexData.tangent is stored as xyzw. + // So we need to skip every fourth vertexData.tangent. + if (((index + 1) % 4) !== 0) { + tangents[dataIndex] = data[dataIndex] + value; + dataIndex++; + } + }); + babylonMorphTarget.setTangents(tangents); + }); + return Promise.all(promises).then(function () { }); + }; + GLTFLoader._LoadTransform = function (node, babylonNode) { + // Ignore the TRS of skinned nodes. + // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note) + if (node.skin != undefined) { + return; + } + var position = babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(); + var rotation = babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].Identity(); + var scaling = babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Vector3"].One(); + if (node.matrix) { + var matrix = babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Matrix"].FromArray(node.matrix); + matrix.decompose(scaling, rotation, position); + } + else { + if (node.translation) { + position = babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Vector3"].FromArray(node.translation); + } + if (node.rotation) { + rotation = babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].FromArray(node.rotation); + } + if (node.scale) { + scaling = babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Vector3"].FromArray(node.scale); + } + } + babylonNode.position = position; + babylonNode.rotationQuaternion = rotation; + babylonNode.scaling = scaling; + }; + GLTFLoader.prototype._loadSkinAsync = function (context, node, skin) { + var _this = this; + var extensionPromise = this._extensionsLoadSkinAsync(context, node, skin); + if (extensionPromise) { + return extensionPromise; + } + var assignSkeleton = function (skeleton) { + _this._forEachPrimitive(node, function (babylonMesh) { + babylonMesh.skeleton = skeleton; + }); + }; + if (skin._data) { + assignSkeleton(skin._data.babylonSkeleton); + return skin._data.promise; + } + var skeletonId = "skeleton" + skin.index; + var babylonSkeleton = new babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Skeleton"](skin.name || skeletonId, skeletonId, this._babylonScene); + // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note) + babylonSkeleton.overrideMesh = this._rootBabylonMesh; + this._loadBones(context, skin, babylonSkeleton); + assignSkeleton(babylonSkeleton); + var promise = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) { + _this._updateBoneMatrices(babylonSkeleton, inverseBindMatricesData); + }); + skin._data = { + babylonSkeleton: babylonSkeleton, + promise: promise + }; + return promise; + }; + GLTFLoader.prototype._loadBones = function (context, skin, babylonSkeleton) { + var babylonBones = {}; + for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) { + var index = _a[_i]; + var node = ArrayItem.Get(context + "/joints/" + index, this._gltf.nodes, index); + this._loadBone(node, skin, babylonSkeleton, babylonBones); + } + }; + GLTFLoader.prototype._loadBone = function (node, skin, babylonSkeleton, babylonBones) { + var babylonBone = babylonBones[node.index]; + if (babylonBone) { + return babylonBone; + } + var babylonParentBone = null; + if (node.parent && node.parent._babylonTransformNode !== this._rootBabylonMesh) { + babylonParentBone = this._loadBone(node.parent, skin, babylonSkeleton, babylonBones); + } + var boneIndex = skin.joints.indexOf(node.index); + babylonBone = new babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Bone"](node.name || "joint" + node.index, babylonSkeleton, babylonParentBone, this._getNodeMatrix(node), null, null, boneIndex); + babylonBones[node.index] = babylonBone; + node._babylonBones = node._babylonBones || []; + node._babylonBones.push(babylonBone); + return babylonBone; + }; + GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) { + if (skin.inverseBindMatrices == undefined) { + return Promise.resolve(null); + } + var accessor = ArrayItem.Get(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices); + return this._loadFloatAccessorAsync("/accessors/" + accessor.index, accessor); + }; + GLTFLoader.prototype._updateBoneMatrices = function (babylonSkeleton, inverseBindMatricesData) { + for (var _i = 0, _a = babylonSkeleton.bones; _i < _a.length; _i++) { + var babylonBone = _a[_i]; + var baseMatrix = babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Matrix"].Identity(); + var boneIndex = babylonBone._index; + if (inverseBindMatricesData && boneIndex !== -1) { + babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Matrix"].FromArrayToRef(inverseBindMatricesData, boneIndex * 16, baseMatrix); + baseMatrix.invertToRef(baseMatrix); + } + var babylonParentBone = babylonBone.getParent(); + if (babylonParentBone) { + baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix); + } + babylonBone.updateMatrix(baseMatrix, false, false); + babylonBone._updateDifferenceMatrix(undefined, false); + } + }; + GLTFLoader.prototype._getNodeMatrix = function (node) { + return node.matrix ? + babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Matrix"].FromArray(node.matrix) : + babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Matrix"].Compose(node.scale ? babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Vector3"].FromArray(node.scale) : babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Vector3"].One(), node.rotation ? babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].FromArray(node.rotation) : babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].Identity(), node.translation ? babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Vector3"].FromArray(node.translation) : babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero()); + }; + /** + * Loads a glTF camera. + * @param context The context when loading the asset + * @param camera The glTF camera property + * @param assign A function called synchronously after parsing the glTF properties + * @returns A promise that resolves with the loaded Babylon camera when the load is complete + */ + GLTFLoader.prototype.loadCameraAsync = function (context, camera, assign) { + if (assign === void 0) { assign = function () { }; } + var extensionPromise = this._extensionsLoadCameraAsync(context, camera, assign); + if (extensionPromise) { + return extensionPromise; + } + var promises = new Array(); + this.logOpen(context + " " + (camera.name || "")); + var babylonCamera = new babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["FreeCamera"](camera.name || "camera" + camera.index, babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(), this._babylonScene, false); + babylonCamera.rotation = new babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Vector3"](0, Math.PI, 0); + switch (camera.type) { + case "perspective" /* PERSPECTIVE */: { + var perspective = camera.perspective; + if (!perspective) { + throw new Error(context + ": Camera perspective properties are missing"); + } + babylonCamera.fov = perspective.yfov; + babylonCamera.minZ = perspective.znear; + babylonCamera.maxZ = perspective.zfar || Number.MAX_VALUE; + break; + } + case "orthographic" /* ORTHOGRAPHIC */: { + if (!camera.orthographic) { + throw new Error(context + ": Camera orthographic properties are missing"); + } + babylonCamera.mode = babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Camera"].ORTHOGRAPHIC_CAMERA; + babylonCamera.orthoLeft = -camera.orthographic.xmag; + babylonCamera.orthoRight = camera.orthographic.xmag; + babylonCamera.orthoBottom = -camera.orthographic.ymag; + babylonCamera.orthoTop = camera.orthographic.ymag; + babylonCamera.minZ = camera.orthographic.znear; + babylonCamera.maxZ = camera.orthographic.zfar; + break; + } + default: { + throw new Error(context + ": Invalid camera type (" + camera.type + ")"); + } + } + GLTFLoader.AddPointerMetadata(babylonCamera, context); + this._parent.onCameraLoadedObservable.notifyObservers(babylonCamera); + assign(babylonCamera); + return Promise.all(promises).then(function () { + return babylonCamera; + }); + }; + GLTFLoader.prototype._loadAnimationsAsync = function () { + var animations = this._gltf.animations; + if (!animations) { + return Promise.resolve(); + } + var promises = new Array(); + for (var index = 0; index < animations.length; index++) { + var animation = animations[index]; + promises.push(this.loadAnimationAsync("/animations/" + animation.index, animation)); + } + return Promise.all(promises).then(function () { }); + }; + /** + * Loads a glTF animation. + * @param context The context when loading the asset + * @param animation The glTF animation property + * @returns A promise that resolves with the loaded Babylon animation group when the load is complete + */ + GLTFLoader.prototype.loadAnimationAsync = function (context, animation) { + var promise = this._extensionsLoadAnimationAsync(context, animation); + if (promise) { + return promise; + } + var babylonAnimationGroup = new babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["AnimationGroup"](animation.name || "animation" + animation.index, this._babylonScene); + animation._babylonAnimationGroup = babylonAnimationGroup; + var promises = new Array(); + ArrayItem.Assign(animation.channels); + ArrayItem.Assign(animation.samplers); + for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) { + var channel = _a[_i]; + promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel.index, context, animation, channel, babylonAnimationGroup)); + } + return Promise.all(promises).then(function () { + babylonAnimationGroup.normalize(0); + return babylonAnimationGroup; + }); + }; + /** + * @hidden Loads a glTF animation channel. + * @param context The context when loading the asset + * @param animationContext The context of the animation when loading the asset + * @param animation The glTF animation property + * @param channel The glTF animation channel property + * @param babylonAnimationGroup The babylon animation group property + * @param animationTargetOverride The babylon animation channel target override property. My be null. + * @returns A void promise when the channel load is complete + */ + GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup, animationTargetOverride) { + var _this = this; + if (animationTargetOverride === void 0) { animationTargetOverride = null; } + if (channel.target.node == undefined) { + return Promise.resolve(); + } + var targetNode = ArrayItem.Get(context + "/target/node", this._gltf.nodes, channel.target.node); + // Ignore animations that have no animation targets. + if ((channel.target.path === "weights" /* WEIGHTS */ && !targetNode._numMorphTargets) || + (channel.target.path !== "weights" /* WEIGHTS */ && !targetNode._babylonTransformNode)) { + return Promise.resolve(); + } + var sampler = ArrayItem.Get(context + "/sampler", animation.samplers, channel.sampler); + return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) { + var targetPath; + var animationType; + switch (channel.target.path) { + case "translation" /* TRANSLATION */: { + targetPath = "position"; + animationType = babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Animation"].ANIMATIONTYPE_VECTOR3; + break; + } + case "rotation" /* ROTATION */: { + targetPath = "rotationQuaternion"; + animationType = babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Animation"].ANIMATIONTYPE_QUATERNION; + break; + } + case "scale" /* SCALE */: { + targetPath = "scaling"; + animationType = babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Animation"].ANIMATIONTYPE_VECTOR3; + break; + } + case "weights" /* WEIGHTS */: { + targetPath = "influence"; + animationType = babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Animation"].ANIMATIONTYPE_FLOAT; + break; + } + default: { + throw new Error(context + "/target/path: Invalid value (" + channel.target.path + ")"); + } + } + var outputBufferOffset = 0; + var getNextOutputValue; + switch (targetPath) { + case "position": { + getNextOutputValue = function () { + var value = babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Vector3"].FromArray(data.output, outputBufferOffset); + outputBufferOffset += 3; + return value; + }; + break; + } + case "rotationQuaternion": { + getNextOutputValue = function () { + var value = babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].FromArray(data.output, outputBufferOffset); + outputBufferOffset += 4; + return value; + }; + break; + } + case "scaling": { + getNextOutputValue = function () { + var value = babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Vector3"].FromArray(data.output, outputBufferOffset); + outputBufferOffset += 3; + return value; + }; + break; + } + case "influence": { + getNextOutputValue = function () { + var value = new Array(targetNode._numMorphTargets); + for (var i = 0; i < targetNode._numMorphTargets; i++) { + value[i] = data.output[outputBufferOffset++]; + } + return value; + }; + break; + } + } + var getNextKey; + switch (data.interpolation) { + case "STEP" /* STEP */: { + getNextKey = function (frameIndex) { return ({ + frame: data.input[frameIndex], + value: getNextOutputValue(), + interpolation: babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["AnimationKeyInterpolation"].STEP + }); }; + break; + } + case "LINEAR" /* LINEAR */: { + getNextKey = function (frameIndex) { return ({ + frame: data.input[frameIndex], + value: getNextOutputValue() + }); }; + break; + } + case "CUBICSPLINE" /* CUBICSPLINE */: { + getNextKey = function (frameIndex) { return ({ + frame: data.input[frameIndex], + inTangent: getNextOutputValue(), + value: getNextOutputValue(), + outTangent: getNextOutputValue() + }); }; + break; + } + } + var keys = new Array(data.input.length); + for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) { + keys[frameIndex] = getNextKey(frameIndex); + } + if (targetPath === "influence") { + var _loop_1 = function (targetIndex) { + var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length; + var babylonAnimation = new babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Animation"](animationName, targetPath, 1, animationType); + babylonAnimation.setKeys(keys.map(function (key) { return ({ + frame: key.frame, + inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined, + value: key.value[targetIndex], + outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined + }); })); + _this._forEachPrimitive(targetNode, function (babylonAbstractMesh) { + var babylonMesh = babylonAbstractMesh; + var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex); + var babylonAnimationClone = babylonAnimation.clone(); + morphTarget.animations.push(babylonAnimationClone); + babylonAnimationGroup.addTargetedAnimation(babylonAnimationClone, morphTarget); + }); + }; + for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) { + _loop_1(targetIndex); + } + } + else { + var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length; + var babylonAnimation = new babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Animation"](animationName, targetPath, 1, animationType); + babylonAnimation.setKeys(keys); + if (animationTargetOverride != null && animationTargetOverride.animations != null) { + animationTargetOverride.animations.push(babylonAnimation); + babylonAnimationGroup.addTargetedAnimation(babylonAnimation, animationTargetOverride); + } + else { + targetNode._babylonTransformNode.animations.push(babylonAnimation); + babylonAnimationGroup.addTargetedAnimation(babylonAnimation, targetNode._babylonTransformNode); + } + } + }); + }; + GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) { + if (sampler._data) { + return sampler._data; + } + var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */; + switch (interpolation) { + case "STEP" /* STEP */: + case "LINEAR" /* LINEAR */: + case "CUBICSPLINE" /* CUBICSPLINE */: { + break; + } + default: { + throw new Error(context + "/interpolation: Invalid value (" + sampler.interpolation + ")"); + } + } + var inputAccessor = ArrayItem.Get(context + "/input", this._gltf.accessors, sampler.input); + var outputAccessor = ArrayItem.Get(context + "/output", this._gltf.accessors, sampler.output); + sampler._data = Promise.all([ + this._loadFloatAccessorAsync("/accessors/" + inputAccessor.index, inputAccessor), + this._loadFloatAccessorAsync("/accessors/" + outputAccessor.index, outputAccessor) + ]).then(function (_a) { + var inputData = _a[0], outputData = _a[1]; + return { + input: inputData, + interpolation: interpolation, + output: outputData, + }; + }); + return sampler._data; + }; + GLTFLoader.prototype._loadBufferAsync = function (context, buffer) { + if (buffer._data) { + return buffer._data; + } + if (!buffer.uri) { + throw new Error(context + "/uri: Value is missing"); + } + buffer._data = this.loadUriAsync(context + "/uri", buffer, buffer.uri); + return buffer._data; + }; + /** + * Loads a glTF buffer view. + * @param context The context when loading the asset + * @param bufferView The glTF buffer view property + * @returns A promise that resolves with the loaded data when the load is complete + */ + GLTFLoader.prototype.loadBufferViewAsync = function (context, bufferView) { + if (bufferView._data) { + return bufferView._data; + } + var buffer = ArrayItem.Get(context + "/buffer", this._gltf.buffers, bufferView.buffer); + bufferView._data = this._loadBufferAsync("/buffers/" + buffer.index, buffer).then(function (data) { + try { + return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength); + } + catch (e) { + throw new Error(context + ": " + e.message); + } + }); + return bufferView._data; + }; + GLTFLoader.prototype._loadIndicesAccessorAsync = function (context, accessor) { + if (accessor.type !== "SCALAR" /* SCALAR */) { + throw new Error(context + "/type: Invalid value " + accessor.type); + } + if (accessor.componentType !== 5121 /* UNSIGNED_BYTE */ && + accessor.componentType !== 5123 /* UNSIGNED_SHORT */ && + accessor.componentType !== 5125 /* UNSIGNED_INT */) { + throw new Error(context + "/componentType: Invalid value " + accessor.componentType); + } + if (accessor._data) { + return accessor._data; + } + var bufferView = ArrayItem.Get(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView); + accessor._data = this.loadBufferViewAsync("/bufferViews/" + bufferView.index, bufferView).then(function (data) { + return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, accessor.count); + }); + return accessor._data; + }; + GLTFLoader.prototype._loadFloatAccessorAsync = function (context, accessor) { + // TODO: support normalized and stride + var _this = this; + if (accessor.componentType !== 5126 /* FLOAT */) { + throw new Error("Invalid component type " + accessor.componentType); + } + if (accessor._data) { + return accessor._data; + } + var numComponents = GLTFLoader._GetNumComponents(context, accessor.type); + var length = numComponents * accessor.count; + if (accessor.bufferView == undefined) { + accessor._data = Promise.resolve(new Float32Array(length)); + } + else { + var bufferView = ArrayItem.Get(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView); + accessor._data = this.loadBufferViewAsync("/bufferViews/" + bufferView.index, bufferView).then(function (data) { + return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, length); + }); + } + if (accessor.sparse) { + var sparse_1 = accessor.sparse; + accessor._data = accessor._data.then(function (view) { + var data = view; + var indicesBufferView = ArrayItem.Get(context + "/sparse/indices/bufferView", _this._gltf.bufferViews, sparse_1.indices.bufferView); + var valuesBufferView = ArrayItem.Get(context + "/sparse/values/bufferView", _this._gltf.bufferViews, sparse_1.values.bufferView); + return Promise.all([ + _this.loadBufferViewAsync("/bufferViews/" + indicesBufferView.index, indicesBufferView), + _this.loadBufferViewAsync("/bufferViews/" + valuesBufferView.index, valuesBufferView) + ]).then(function (_a) { + var indicesData = _a[0], valuesData = _a[1]; + var indices = GLTFLoader._GetTypedArray(context + "/sparse/indices", sparse_1.indices.componentType, indicesData, sparse_1.indices.byteOffset, sparse_1.count); + var values = GLTFLoader._GetTypedArray(context + "/sparse/values", accessor.componentType, valuesData, sparse_1.values.byteOffset, numComponents * sparse_1.count); + var valuesIndex = 0; + for (var indicesIndex = 0; indicesIndex < indices.length; indicesIndex++) { + var dataIndex = indices[indicesIndex] * numComponents; + for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) { + data[dataIndex++] = values[valuesIndex++]; + } + } + return data; + }); + }); + } + return accessor._data; + }; + GLTFLoader.prototype._loadVertexBufferViewAsync = function (bufferView, kind) { + var _this = this; + if (bufferView._babylonBuffer) { + return bufferView._babylonBuffer; + } + bufferView._babylonBuffer = this.loadBufferViewAsync("/bufferViews/" + bufferView.index, bufferView).then(function (data) { + return new babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Buffer"](_this._babylonScene.getEngine(), data, false); + }); + return bufferView._babylonBuffer; + }; + GLTFLoader.prototype._loadVertexAccessorAsync = function (context, accessor, kind) { + var _this = this; + if (accessor._babylonVertexBuffer) { + return accessor._babylonVertexBuffer; + } + if (accessor.sparse) { + accessor._babylonVertexBuffer = this._loadFloatAccessorAsync("/accessors/" + accessor.index, accessor).then(function (data) { + return new babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"](_this._babylonScene.getEngine(), data, kind, false); + }); + } + // HACK: If byte offset is not a multiple of component type byte length then load as a float array instead of using Babylon buffers. + else if (accessor.byteOffset && accessor.byteOffset % babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].GetTypeByteLength(accessor.componentType) !== 0) { + babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Tools"].Warn("Accessor byte offset is not a multiple of component type byte length"); + accessor._babylonVertexBuffer = this._loadFloatAccessorAsync("/accessors/" + accessor.index, accessor).then(function (data) { + return new babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"](_this._babylonScene.getEngine(), data, kind, false); + }); + } + else { + var bufferView_1 = ArrayItem.Get(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView); + accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync(bufferView_1, kind).then(function (babylonBuffer) { + var size = GLTFLoader._GetNumComponents(context, accessor.type); + return new babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"](_this._babylonScene.getEngine(), babylonBuffer, kind, false, false, bufferView_1.byteStride, false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true); + }); + } + return accessor._babylonVertexBuffer; + }; + GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, properties, babylonMaterial) { + if (!(babylonMaterial instanceof babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["PBRMaterial"])) { + throw new Error(context + ": Material type not supported"); + } + var promises = new Array(); + if (properties) { + if (properties.baseColorFactor) { + babylonMaterial.albedoColor = babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Color3"].FromArray(properties.baseColorFactor); + babylonMaterial.alpha = properties.baseColorFactor[3]; + } + else { + babylonMaterial.albedoColor = babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Color3"].White(); + } + babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor; + babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor; + if (properties.baseColorTexture) { + promises.push(this.loadTextureInfoAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) { + texture.name = babylonMaterial.name + " (Base Color)"; + babylonMaterial.albedoTexture = texture; + })); + } + if (properties.metallicRoughnessTexture) { + promises.push(this.loadTextureInfoAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) { + texture.name = babylonMaterial.name + " (Metallic Roughness)"; + babylonMaterial.metallicTexture = texture; + })); + babylonMaterial.useMetallnessFromMetallicTextureBlue = true; + babylonMaterial.useRoughnessFromMetallicTextureGreen = true; + babylonMaterial.useRoughnessFromMetallicTextureAlpha = false; + } + } + return Promise.all(promises).then(function () { }); + }; + /** @hidden */ + GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) { + if (assign === void 0) { assign = function () { }; } + var extensionPromise = this._extensionsLoadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign); + if (extensionPromise) { + return extensionPromise; + } + material._data = material._data || {}; + var babylonData = material._data[babylonDrawMode]; + if (!babylonData) { + this.logOpen(context + " " + (material.name || "")); + var babylonMaterial = this.createMaterial(context, material, babylonDrawMode); + babylonData = { + babylonMaterial: babylonMaterial, + babylonMeshes: [], + promise: this.loadMaterialPropertiesAsync(context, material, babylonMaterial) + }; + material._data[babylonDrawMode] = babylonData; + GLTFLoader.AddPointerMetadata(babylonMaterial, context); + this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial); + this.logClose(); + } + babylonData.babylonMeshes.push(babylonMesh); + babylonMesh.onDisposeObservable.addOnce(function () { + var index = babylonData.babylonMeshes.indexOf(babylonMesh); + if (index !== -1) { + babylonData.babylonMeshes.splice(index, 1); + } + }); + assign(babylonData.babylonMaterial); + return babylonData.promise.then(function () { + return babylonData.babylonMaterial; + }); + }; + GLTFLoader.prototype._createDefaultMaterial = function (name, babylonDrawMode) { + var babylonMaterial = new babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["PBRMaterial"](name, this._babylonScene); + babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Material"].CounterClockWiseSideOrientation : babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Material"].ClockWiseSideOrientation; + babylonMaterial.fillMode = babylonDrawMode; + babylonMaterial.enableSpecularAntiAliasing = true; + babylonMaterial.useRadianceOverAlpha = !this._parent.transparencyAsCoverage; + babylonMaterial.useSpecularOverAlpha = !this._parent.transparencyAsCoverage; + babylonMaterial.transparencyMode = babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["PBRMaterial"].PBRMATERIAL_OPAQUE; + babylonMaterial.metallic = 1; + babylonMaterial.roughness = 1; + return babylonMaterial; + }; + /** + * Creates a Babylon material from a glTF material. + * @param context The context when loading the asset + * @param material The glTF material property + * @param babylonDrawMode The draw mode for the Babylon material + * @returns The Babylon material + */ + GLTFLoader.prototype.createMaterial = function (context, material, babylonDrawMode) { + var extensionPromise = this._extensionsCreateMaterial(context, material, babylonDrawMode); + if (extensionPromise) { + return extensionPromise; + } + var name = material.name || "material" + material.index; + var babylonMaterial = this._createDefaultMaterial(name, babylonDrawMode); + return babylonMaterial; + }; + /** + * Loads properties from a glTF material into a Babylon material. + * @param context The context when loading the asset + * @param material The glTF material property + * @param babylonMaterial The Babylon material + * @returns A promise that resolves when the load is complete + */ + GLTFLoader.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) { + var extensionPromise = this._extensionsLoadMaterialPropertiesAsync(context, material, babylonMaterial); + if (extensionPromise) { + return extensionPromise; + } + var promises = new Array(); + promises.push(this.loadMaterialBasePropertiesAsync(context, material, babylonMaterial)); + if (material.pbrMetallicRoughness) { + promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context + "/pbrMetallicRoughness", material.pbrMetallicRoughness, babylonMaterial)); + } + this.loadMaterialAlphaProperties(context, material, babylonMaterial); + return Promise.all(promises).then(function () { }); + }; + /** + * Loads the normal, occlusion, and emissive properties from a glTF material into a Babylon material. + * @param context The context when loading the asset + * @param material The glTF material property + * @param babylonMaterial The Babylon material + * @returns A promise that resolves when the load is complete + */ + GLTFLoader.prototype.loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) { + if (!(babylonMaterial instanceof babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["PBRMaterial"])) { + throw new Error(context + ": Material type not supported"); + } + var promises = new Array(); + babylonMaterial.emissiveColor = material.emissiveFactor ? babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Color3"].FromArray(material.emissiveFactor) : new babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Color3"](0, 0, 0); + if (material.doubleSided) { + babylonMaterial.backFaceCulling = false; + babylonMaterial.twoSidedLighting = true; + } + if (material.normalTexture) { + promises.push(this.loadTextureInfoAsync(context + "/normalTexture", material.normalTexture, function (texture) { + texture.name = babylonMaterial.name + " (Normal)"; + babylonMaterial.bumpTexture = texture; + })); + babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem; + babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem; + if (material.normalTexture.scale != undefined) { + babylonMaterial.bumpTexture.level = material.normalTexture.scale; + } + babylonMaterial.forceIrradianceInFragment = true; + } + if (material.occlusionTexture) { + promises.push(this.loadTextureInfoAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) { + texture.name = babylonMaterial.name + " (Occlusion)"; + babylonMaterial.ambientTexture = texture; + })); + babylonMaterial.useAmbientInGrayScale = true; + if (material.occlusionTexture.strength != undefined) { + babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength; + } + } + if (material.emissiveTexture) { + promises.push(this.loadTextureInfoAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) { + texture.name = babylonMaterial.name + " (Emissive)"; + babylonMaterial.emissiveTexture = texture; + })); + } + return Promise.all(promises).then(function () { }); + }; + /** + * Loads the alpha properties from a glTF material into a Babylon material. + * Must be called after the setting the albedo texture of the Babylon material when the material has an albedo texture. + * @param context The context when loading the asset + * @param material The glTF material property + * @param babylonMaterial The Babylon material + */ + GLTFLoader.prototype.loadMaterialAlphaProperties = function (context, material, babylonMaterial) { + if (!(babylonMaterial instanceof babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["PBRMaterial"])) { + throw new Error(context + ": Material type not supported"); + } + var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */; + switch (alphaMode) { + case "OPAQUE" /* OPAQUE */: { + babylonMaterial.transparencyMode = babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["PBRMaterial"].PBRMATERIAL_OPAQUE; + break; + } + case "MASK" /* MASK */: { + babylonMaterial.transparencyMode = babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["PBRMaterial"].PBRMATERIAL_ALPHATEST; + babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff); + if (babylonMaterial.albedoTexture) { + babylonMaterial.albedoTexture.hasAlpha = true; + } + break; + } + case "BLEND" /* BLEND */: { + babylonMaterial.transparencyMode = babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["PBRMaterial"].PBRMATERIAL_ALPHABLEND; + if (babylonMaterial.albedoTexture) { + babylonMaterial.albedoTexture.hasAlpha = true; + babylonMaterial.useAlphaFromAlbedoTexture = true; + } + break; + } + default: { + throw new Error(context + "/alphaMode: Invalid value (" + material.alphaMode + ")"); + } + } + }; + /** + * Loads a glTF texture info. + * @param context The context when loading the asset + * @param textureInfo The glTF texture info property + * @param assign A function called synchronously after parsing the glTF properties + * @returns A promise that resolves with the loaded Babylon texture when the load is complete + */ + GLTFLoader.prototype.loadTextureInfoAsync = function (context, textureInfo, assign) { + var _this = this; + if (assign === void 0) { assign = function () { }; } + var extensionPromise = this._extensionsLoadTextureInfoAsync(context, textureInfo, assign); + if (extensionPromise) { + return extensionPromise; + } + this.logOpen("" + context); + var texture = ArrayItem.Get(context + "/index", this._gltf.textures, textureInfo.index); + var promise = this._loadTextureAsync("/textures/" + textureInfo.index, texture, function (babylonTexture) { + babylonTexture.coordinatesIndex = textureInfo.texCoord || 0; + GLTFLoader.AddPointerMetadata(babylonTexture, context); + _this._parent.onTextureLoadedObservable.notifyObservers(babylonTexture); + assign(babylonTexture); + }); + this.logClose(); + return promise; + }; + GLTFLoader.prototype._loadTextureAsync = function (context, texture, assign) { + var _this = this; + if (assign === void 0) { assign = function () { }; } + var promises = new Array(); + this.logOpen(context + " " + (texture.name || "")); + var sampler = (texture.sampler == undefined ? GLTFLoader._DefaultSampler : ArrayItem.Get(context + "/sampler", this._gltf.samplers, texture.sampler)); + var samplerData = this._loadSampler("/samplers/" + sampler.index, sampler); + var image = ArrayItem.Get(context + "/source", this._gltf.images, texture.source); + var url = null; + if (image.uri) { + if (babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Tools"].IsBase64(image.uri)) { + url = image.uri; + } + else if (this._babylonScene.getEngine().textureFormatInUse) { + // If an image uri and a texture format is set like (eg. KTX) load from url instead of blob to support texture format and fallback + url = this._rootUrl + image.uri; + } + } + var deferred = new babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Deferred"](); + var babylonTexture = new babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Texture"](url, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () { + if (!_this._disposed) { + deferred.resolve(); + } + }, function (message, exception) { + if (!_this._disposed) { + deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture"))); + } + }); + promises.push(deferred.promise); + if (!url) { + promises.push(this.loadImageAsync("/images/" + image.index, image).then(function (data) { + var name = image.uri || _this._fileName + "#image" + image.index; + var dataUrl = "data:" + _this._uniqueRootUrl + name; + babylonTexture.updateURL(dataUrl, + // TODO: Remove this hack once we can load from Blob objects. + data.buffer); + })); + } + babylonTexture.wrapU = samplerData.wrapU; + babylonTexture.wrapV = samplerData.wrapV; + assign(babylonTexture); + this.logClose(); + return Promise.all(promises).then(function () { + return babylonTexture; + }); + }; + GLTFLoader.prototype._loadSampler = function (context, sampler) { + if (!sampler._data) { + sampler._data = { + noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */), + samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler), + wrapU: GLTFLoader._GetTextureWrapMode(context + "/wrapS", sampler.wrapS), + wrapV: GLTFLoader._GetTextureWrapMode(context + "/wrapT", sampler.wrapT) + }; + } + return sampler._data; + }; + /** + * Loads a glTF image. + * @param context The context when loading the asset + * @param image The glTF image property + * @returns A promise that resolves with the loaded data when the load is complete + */ + GLTFLoader.prototype.loadImageAsync = function (context, image) { + if (!image._data) { + this.logOpen(context + " " + (image.name || "")); + if (image.uri) { + image._data = this.loadUriAsync(context + "/uri", image, image.uri); + } + else { + var bufferView = ArrayItem.Get(context + "/bufferView", this._gltf.bufferViews, image.bufferView); + image._data = this.loadBufferViewAsync("/bufferViews/" + bufferView.index, bufferView); + } + this.logClose(); + } + return image._data; + }; + /** + * Loads a glTF uri. + * @param context The context when loading the asset + * @param property The glTF property associated with the uri + * @param uri The base64 or relative uri + * @returns A promise that resolves with the loaded data when the load is complete + */ + GLTFLoader.prototype.loadUriAsync = function (context, property, uri) { + var _this = this; + var extensionPromise = this._extensionsLoadUriAsync(context, property, uri); + if (extensionPromise) { + return extensionPromise; + } + if (!GLTFLoader._ValidateUri(uri)) { + throw new Error(context + ": '" + uri + "' is invalid"); + } + if (babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Tools"].IsBase64(uri)) { + var data = new Uint8Array(babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Tools"].DecodeBase64(uri)); + this.log("Decoded " + uri.substr(0, 64) + "... (" + data.length + " bytes)"); + return Promise.resolve(data); + } + this.log("Loading " + uri); + return this._parent.preprocessUrlAsync(this._rootUrl + uri).then(function (url) { + return new Promise(function (resolve, reject) { + if (!_this._disposed) { + var request_1 = babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Tools"].LoadFile(url, function (fileData) { + if (!_this._disposed) { + var data = new Uint8Array(fileData); + _this.log("Loaded " + uri + " (" + data.length + " bytes)"); + resolve(data); + } + }, function (event) { + if (!_this._disposed) { + if (request_1) { + request_1._lengthComputable = event.lengthComputable; + request_1._loaded = event.loaded; + request_1._total = event.total; + } + if (_this._state === _glTFFileLoader__WEBPACK_IMPORTED_MODULE_1__["GLTFLoaderState"].LOADING) { + try { + _this._onProgress(); + } + catch (e) { + reject(e); + } + } + } + }, _this._babylonScene.offlineProvider, true, function (request, exception) { + if (!_this._disposed) { + reject(new babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["LoadFileError"](context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request)); + } + }); + _this._requests.push(request_1); + } + }); + }); + }; + GLTFLoader.prototype._onProgress = function () { + if (!this._progressCallback) { + return; + } + var lengthComputable = true; + var loaded = 0; + var total = 0; + for (var _i = 0, _a = this._requests; _i < _a.length; _i++) { + var request = _a[_i]; + if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) { + return; + } + lengthComputable = lengthComputable && request._lengthComputable; + loaded += request._loaded; + total += request._total; + } + this._progressCallback(new babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["SceneLoaderProgressEvent"](lengthComputable, loaded, lengthComputable ? total : 0)); + }; + /** + * Adds a JSON pointer to the metadata of the Babylon object at `.metadata.gltf.pointers`. + * @param babylonObject the Babylon object with metadata + * @param pointer the JSON pointer + */ + GLTFLoader.AddPointerMetadata = function (babylonObject, pointer) { + var metadata = (babylonObject.metadata = babylonObject.metadata || {}); + var gltf = (metadata.gltf = metadata.gltf || {}); + var pointers = (gltf.pointers = gltf.pointers || []); + pointers.push(pointer); + }; + GLTFLoader._GetTextureWrapMode = function (context, mode) { + // Set defaults if undefined + mode = mode == undefined ? 10497 /* REPEAT */ : mode; + switch (mode) { + case 33071 /* CLAMP_TO_EDGE */: return babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Texture"].CLAMP_ADDRESSMODE; + case 33648 /* MIRRORED_REPEAT */: return babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Texture"].MIRROR_ADDRESSMODE; + case 10497 /* REPEAT */: return babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Texture"].WRAP_ADDRESSMODE; + default: + babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Tools"].Warn(context + ": Invalid value (" + mode + ")"); + return babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Texture"].WRAP_ADDRESSMODE; + } + }; + GLTFLoader._GetTextureSamplingMode = function (context, sampler) { + // Set defaults if undefined + var magFilter = sampler.magFilter == undefined ? 9729 /* LINEAR */ : sampler.magFilter; + var minFilter = sampler.minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : sampler.minFilter; + if (magFilter === 9729 /* LINEAR */) { + switch (minFilter) { + case 9728 /* NEAREST */: return babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Texture"].LINEAR_NEAREST; + case 9729 /* LINEAR */: return babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Texture"].LINEAR_LINEAR; + case 9984 /* NEAREST_MIPMAP_NEAREST */: return babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Texture"].LINEAR_NEAREST_MIPNEAREST; + case 9985 /* LINEAR_MIPMAP_NEAREST */: return babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Texture"].LINEAR_LINEAR_MIPNEAREST; + case 9986 /* NEAREST_MIPMAP_LINEAR */: return babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Texture"].LINEAR_NEAREST_MIPLINEAR; + case 9987 /* LINEAR_MIPMAP_LINEAR */: return babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Texture"].LINEAR_LINEAR_MIPLINEAR; + default: + babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Tools"].Warn(context + "/minFilter: Invalid value (" + minFilter + ")"); + return babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Texture"].LINEAR_LINEAR_MIPLINEAR; + } + } + else { + if (magFilter !== 9728 /* NEAREST */) { + babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Tools"].Warn(context + "/magFilter: Invalid value (" + magFilter + ")"); + } + switch (minFilter) { + case 9728 /* NEAREST */: return babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Texture"].NEAREST_NEAREST; + case 9729 /* LINEAR */: return babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Texture"].NEAREST_LINEAR; + case 9984 /* NEAREST_MIPMAP_NEAREST */: return babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Texture"].NEAREST_NEAREST_MIPNEAREST; + case 9985 /* LINEAR_MIPMAP_NEAREST */: return babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Texture"].NEAREST_LINEAR_MIPNEAREST; + case 9986 /* NEAREST_MIPMAP_LINEAR */: return babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Texture"].NEAREST_NEAREST_MIPLINEAR; + case 9987 /* LINEAR_MIPMAP_LINEAR */: return babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Texture"].NEAREST_LINEAR_MIPLINEAR; + default: + babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Tools"].Warn(context + "/minFilter: Invalid value (" + minFilter + ")"); + return babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Texture"].NEAREST_NEAREST_MIPNEAREST; + } + } + }; + GLTFLoader._GetTypedArray = function (context, componentType, bufferView, byteOffset, length) { + var buffer = bufferView.buffer; + byteOffset = bufferView.byteOffset + (byteOffset || 0); + try { + switch (componentType) { + case 5120 /* BYTE */: return new Int8Array(buffer, byteOffset, length); + case 5121 /* UNSIGNED_BYTE */: return new Uint8Array(buffer, byteOffset, length); + case 5122 /* SHORT */: return new Int16Array(buffer, byteOffset, length); + case 5123 /* UNSIGNED_SHORT */: return new Uint16Array(buffer, byteOffset, length); + case 5125 /* UNSIGNED_INT */: return new Uint32Array(buffer, byteOffset, length); + case 5126 /* FLOAT */: return new Float32Array(buffer, byteOffset, length); + default: throw new Error("Invalid component type " + componentType); + } + } + catch (e) { + throw new Error(context + ": " + e); + } + }; + GLTFLoader._GetNumComponents = function (context, type) { + switch (type) { + case "SCALAR": return 1; + case "VEC2": return 2; + case "VEC3": return 3; + case "VEC4": return 4; + case "MAT2": return 4; + case "MAT3": return 9; + case "MAT4": return 16; + } + throw new Error(context + ": Invalid type (" + type + ")"); + }; + GLTFLoader._ValidateUri = function (uri) { + return (babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Tools"].IsBase64(uri) || uri.indexOf("..") === -1); + }; + GLTFLoader._GetDrawMode = function (context, mode) { + if (mode == undefined) { + mode = 4 /* TRIANGLES */; + } + switch (mode) { + case 0 /* POINTS */: return babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Material"].PointListDrawMode; + case 1 /* LINES */: return babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Material"].LineListDrawMode; + case 2 /* LINE_LOOP */: return babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Material"].LineLoopDrawMode; + case 3 /* LINE_STRIP */: return babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Material"].LineStripDrawMode; + case 4 /* TRIANGLES */: return babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Material"].TriangleFillMode; + case 5 /* TRIANGLE_STRIP */: return babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Material"].TriangleStripDrawMode; + case 6 /* TRIANGLE_FAN */: return babylonjs_Misc_deferred__WEBPACK_IMPORTED_MODULE_0__["Material"].TriangleFanDrawMode; + } + throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")"); + }; + GLTFLoader.prototype._compileMaterialsAsync = function () { + var _this = this; + this._parent._startPerformanceCounter("Compile materials"); + var promises = new Array(); + if (this._gltf.materials) { + for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) { + var material = _a[_i]; + if (material._data) { + for (var babylonDrawMode in material._data) { + var babylonData = material._data[babylonDrawMode]; + for (var _b = 0, _c = babylonData.babylonMeshes; _b < _c.length; _b++) { + var babylonMesh = _c[_b]; + // Ensure nonUniformScaling is set if necessary. + babylonMesh.computeWorldMatrix(true); + var babylonMaterial = babylonData.babylonMaterial; + promises.push(babylonMaterial.forceCompilationAsync(babylonMesh)); + if (this._parent.useClipPlane) { + promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true })); + } + } + } + } + } + } + return Promise.all(promises).then(function () { + _this._parent._endPerformanceCounter("Compile materials"); + }); + }; + GLTFLoader.prototype._compileShadowGeneratorsAsync = function () { + var _this = this; + this._parent._startPerformanceCounter("Compile shadow generators"); + var promises = new Array(); + var lights = this._babylonScene.lights; + for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) { + var light = lights_1[_i]; + var generator = light.getShadowGenerator(); + if (generator) { + promises.push(generator.forceCompilationAsync()); + } + } + return Promise.all(promises).then(function () { + _this._parent._endPerformanceCounter("Compile shadow generators"); + }); + }; + GLTFLoader.prototype._forEachExtensions = function (action) { + for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) { + var name_4 = _a[_i]; + var extension = this._extensions[name_4]; + if (extension.enabled) { + action(extension); + } + } + }; + GLTFLoader.prototype._applyExtensions = function (property, functionName, actionAsync) { + for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) { + var name_5 = _a[_i]; + var extension = this._extensions[name_5]; + if (extension.enabled) { + var id = name_5 + "." + functionName; + var loaderProperty = property; + loaderProperty._activeLoaderExtensionFunctions = loaderProperty._activeLoaderExtensionFunctions || {}; + var activeLoaderExtensionFunctions = loaderProperty._activeLoaderExtensionFunctions; + if (!activeLoaderExtensionFunctions[id]) { + activeLoaderExtensionFunctions[id] = true; + try { + var result = actionAsync(extension); + if (result) { + return result; + } + } + finally { + delete activeLoaderExtensionFunctions[id]; + } + } + } + } + return null; + }; + GLTFLoader.prototype._extensionsOnLoading = function () { + this._forEachExtensions(function (extension) { return extension.onLoading && extension.onLoading(); }); + }; + GLTFLoader.prototype._extensionsOnReady = function () { + this._forEachExtensions(function (extension) { return extension.onReady && extension.onReady(); }); + }; + GLTFLoader.prototype._extensionsLoadSceneAsync = function (context, scene) { + return this._applyExtensions(scene, "loadScene", function (extension) { return extension.loadSceneAsync && extension.loadSceneAsync(context, scene); }); + }; + GLTFLoader.prototype._extensionsLoadNodeAsync = function (context, node, assign) { + return this._applyExtensions(node, "loadNode", function (extension) { return extension.loadNodeAsync && extension.loadNodeAsync(context, node, assign); }); + }; + GLTFLoader.prototype._extensionsLoadCameraAsync = function (context, camera, assign) { + return this._applyExtensions(camera, "loadCamera", function (extension) { return extension.loadCameraAsync && extension.loadCameraAsync(context, camera, assign); }); + }; + GLTFLoader.prototype._extensionsLoadVertexDataAsync = function (context, primitive, babylonMesh) { + return this._applyExtensions(primitive, "loadVertexData", function (extension) { return extension._loadVertexDataAsync && extension._loadVertexDataAsync(context, primitive, babylonMesh); }); + }; + GLTFLoader.prototype._extensionsLoadMeshPrimitiveAsync = function (context, name, node, mesh, primitive, assign) { + return this._applyExtensions(primitive, "loadMeshPrimitive", function (extension) { return extension._loadMeshPrimitiveAsync && extension._loadMeshPrimitiveAsync(context, name, node, mesh, primitive, assign); }); + }; + GLTFLoader.prototype._extensionsLoadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) { + return this._applyExtensions(material, "loadMaterial", function (extension) { return extension._loadMaterialAsync && extension._loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign); }); + }; + GLTFLoader.prototype._extensionsCreateMaterial = function (context, material, babylonDrawMode) { + return this._applyExtensions(material, "createMaterial", function (extension) { return extension.createMaterial && extension.createMaterial(context, material, babylonDrawMode); }); + }; + GLTFLoader.prototype._extensionsLoadMaterialPropertiesAsync = function (context, material, babylonMaterial) { + return this._applyExtensions(material, "loadMaterialProperties", function (extension) { return extension.loadMaterialPropertiesAsync && extension.loadMaterialPropertiesAsync(context, material, babylonMaterial); }); + }; + GLTFLoader.prototype._extensionsLoadTextureInfoAsync = function (context, textureInfo, assign) { + return this._applyExtensions(textureInfo, "loadTextureInfo", function (extension) { return extension.loadTextureInfoAsync && extension.loadTextureInfoAsync(context, textureInfo, assign); }); + }; + GLTFLoader.prototype._extensionsLoadAnimationAsync = function (context, animation) { + return this._applyExtensions(animation, "loadAnimation", function (extension) { return extension.loadAnimationAsync && extension.loadAnimationAsync(context, animation); }); + }; + GLTFLoader.prototype._extensionsLoadSkinAsync = function (context, node, skin) { + return this._applyExtensions(skin, "loadSkin", function (extension) { return extension._loadSkinAsync && extension._loadSkinAsync(context, node, skin); }); + }; + GLTFLoader.prototype._extensionsLoadUriAsync = function (context, property, uri) { + return this._applyExtensions(property, "loadUri", function (extension) { return extension._loadUriAsync && extension._loadUriAsync(context, property, uri); }); + }; + /** + * Helper method called by a loader extension to load an glTF extension. + * @param context The context when loading the asset + * @param property The glTF property to load the extension from + * @param extensionName The name of the extension to load + * @param actionAsync The action to run + * @returns The promise returned by actionAsync or null if the extension does not exist + */ + GLTFLoader.LoadExtensionAsync = function (context, property, extensionName, actionAsync) { + if (!property.extensions) { + return null; + } + var extensions = property.extensions; + var extension = extensions[extensionName]; + if (!extension) { + return null; + } + return actionAsync(context + "/extensions/" + extensionName, extension); + }; + /** + * Helper method called by a loader extension to load a glTF extra. + * @param context The context when loading the asset + * @param property The glTF property to load the extra from + * @param extensionName The name of the extension to load + * @param actionAsync The action to run + * @returns The promise returned by actionAsync or null if the extra does not exist + */ + GLTFLoader.LoadExtraAsync = function (context, property, extensionName, actionAsync) { + if (!property.extras) { + return null; + } + var extras = property.extras; + var extra = extras[extensionName]; + if (!extra) { + return null; + } + return actionAsync(context + "/extras/" + extensionName, extra); + }; + /** + * Increments the indentation level and logs a message. + * @param message The message to log + */ + GLTFLoader.prototype.logOpen = function (message) { + this._parent._logOpen(message); + }; + /** + * Decrements the indentation level. + */ + GLTFLoader.prototype.logClose = function () { + this._parent._logClose(); + }; + /** + * Logs a message + * @param message The message to log + */ + GLTFLoader.prototype.log = function (message) { + this._parent._log(message); + }; + /** + * Starts a performance counter. + * @param counterName The name of the performance counter + */ + GLTFLoader.prototype.startPerformanceCounter = function (counterName) { + this._parent._startPerformanceCounter(counterName); + }; + /** + * Ends a performance counter. + * @param counterName The name of the performance counter + */ + GLTFLoader.prototype.endPerformanceCounter = function (counterName) { + this._parent._endPerformanceCounter(counterName); + }; + GLTFLoader._DefaultSampler = { index: -1 }; + GLTFLoader._ExtensionNames = new Array(); + GLTFLoader._ExtensionFactories = {}; + return GLTFLoader; +}()); + +_glTFFileLoader__WEBPACK_IMPORTED_MODULE_1__["GLTFFileLoader"]._CreateGLTF2Loader = function (parent) { return new GLTFLoader(parent); }; + + +/***/ }), + +/***/ "./glTF/2.0/glTFLoaderInterfaces.ts": +/*!******************************************!*\ + !*** ./glTF/2.0/glTFLoaderInterfaces.ts ***! + \******************************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + + + +/***/ }), + +/***/ "./glTF/2.0/index.ts": +/*!***************************!*\ + !*** ./glTF/2.0/index.ts ***! + \***************************/ +/*! exports provided: ArrayItem, GLTFLoader, EXT_lights_image_based, KHR_draco_mesh_compression, KHR_lights, KHR_materials_pbrSpecularGlossiness, KHR_materials_unlit, KHR_texture_transform, MSFT_audio_emitter, MSFT_lod, MSFT_minecraftMesh, MSFT_sRGBFactors */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _glTFLoader__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./glTFLoader */ "./glTF/2.0/glTFLoader.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArrayItem", function() { return _glTFLoader__WEBPACK_IMPORTED_MODULE_0__["ArrayItem"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GLTFLoader", function() { return _glTFLoader__WEBPACK_IMPORTED_MODULE_0__["GLTFLoader"]; }); + +/* harmony import */ var _Extensions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Extensions */ "./glTF/2.0/Extensions/index.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EXT_lights_image_based", function() { return _Extensions__WEBPACK_IMPORTED_MODULE_1__["EXT_lights_image_based"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KHR_draco_mesh_compression", function() { return _Extensions__WEBPACK_IMPORTED_MODULE_1__["KHR_draco_mesh_compression"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KHR_lights", function() { return _Extensions__WEBPACK_IMPORTED_MODULE_1__["KHR_lights"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KHR_materials_pbrSpecularGlossiness", function() { return _Extensions__WEBPACK_IMPORTED_MODULE_1__["KHR_materials_pbrSpecularGlossiness"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KHR_materials_unlit", function() { return _Extensions__WEBPACK_IMPORTED_MODULE_1__["KHR_materials_unlit"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KHR_texture_transform", function() { return _Extensions__WEBPACK_IMPORTED_MODULE_1__["KHR_texture_transform"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MSFT_audio_emitter", function() { return _Extensions__WEBPACK_IMPORTED_MODULE_1__["MSFT_audio_emitter"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MSFT_lod", function() { return _Extensions__WEBPACK_IMPORTED_MODULE_1__["MSFT_lod"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MSFT_minecraftMesh", function() { return _Extensions__WEBPACK_IMPORTED_MODULE_1__["MSFT_minecraftMesh"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MSFT_sRGBFactors", function() { return _Extensions__WEBPACK_IMPORTED_MODULE_1__["MSFT_sRGBFactors"]; }); + + + + + +/***/ }), + +/***/ "./glTF/glTFFileLoader.ts": +/*!********************************!*\ + !*** ./glTF/glTFFileLoader.ts ***! + \********************************/ +/*! exports provided: GLTFLoaderCoordinateSystemMode, GLTFLoaderAnimationStartMode, GLTFLoaderState, GLTFFileLoader */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GLTFLoaderCoordinateSystemMode", function() { return GLTFLoaderCoordinateSystemMode; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GLTFLoaderAnimationStartMode", function() { return GLTFLoaderAnimationStartMode; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GLTFLoaderState", function() { return GLTFLoaderState; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GLTFFileLoader", function() { return GLTFFileLoader; }); +/* harmony import */ var babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! babylonjs/Misc/observable */ "babylonjs/Misc/observable"); +/* harmony import */ var babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__); + + + + +/** + * Mode that determines the coordinate system to use. + */ +var GLTFLoaderCoordinateSystemMode; +(function (GLTFLoaderCoordinateSystemMode) { + /** + * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene. + */ + GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO"; + /** + * Sets the useRightHandedSystem flag on the scene. + */ + GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED"; +})(GLTFLoaderCoordinateSystemMode || (GLTFLoaderCoordinateSystemMode = {})); +/** + * Mode that determines what animations will start. + */ +var GLTFLoaderAnimationStartMode; +(function (GLTFLoaderAnimationStartMode) { + /** + * No animation will start. + */ + GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE"; + /** + * The first animation will start. + */ + GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST"; + /** + * All animations will start. + */ + GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL"; +})(GLTFLoaderAnimationStartMode || (GLTFLoaderAnimationStartMode = {})); +/** + * Loader state. + */ +var GLTFLoaderState; +(function (GLTFLoaderState) { + /** + * The asset is loading. + */ + GLTFLoaderState[GLTFLoaderState["LOADING"] = 0] = "LOADING"; + /** + * The asset is ready for rendering. + */ + GLTFLoaderState[GLTFLoaderState["READY"] = 1] = "READY"; + /** + * The asset is completely loaded. + */ + GLTFLoaderState[GLTFLoaderState["COMPLETE"] = 2] = "COMPLETE"; +})(GLTFLoaderState || (GLTFLoaderState = {})); +/** + * File loader for loading glTF files into a scene. + */ +var GLTFFileLoader = /** @class */ (function () { + function GLTFFileLoader() { + // -------------- + // Common options + // -------------- + /** + * Raised when the asset has been parsed + */ + this.onParsedObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](); + // ---------- + // V2 options + // ---------- + /** + * The coordinate system mode. Defaults to AUTO. + */ + this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO; + /** + * The animation start mode. Defaults to FIRST. + */ + this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST; + /** + * Defines if the loader should compile materials before raising the success callback. Defaults to false. + */ + this.compileMaterials = false; + /** + * Defines if the loader should also compile materials with clip planes. Defaults to false. + */ + this.useClipPlane = false; + /** + * Defines if the loader should compile shadow generators before raising the success callback. Defaults to false. + */ + this.compileShadowGenerators = false; + /** + * Defines if the Alpha blended materials are only applied as coverage. + * If false, (default) The luminance of each pixel will reduce its opacity to simulate the behaviour of most physical materials. + * If true, no extra effects are applied to transparent pixels. + */ + this.transparencyAsCoverage = false; + /** + * Function called before loading a url referenced by the asset. + */ + this.preprocessUrlAsync = function (url) { return Promise.resolve(url); }; + /** + * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh. + */ + this.onMeshLoadedObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](); + /** + * Observable raised when the loader creates a texture after parsing the glTF properties of the texture. + */ + this.onTextureLoadedObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](); + /** + * Observable raised when the loader creates a material after parsing the glTF properties of the material. + */ + this.onMaterialLoadedObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](); + /** + * Observable raised when the loader creates a camera after parsing the glTF properties of the camera. + */ + this.onCameraLoadedObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](); + /** + * Observable raised when the asset is completely loaded, immediately before the loader is disposed. + * For assets with LODs, raised when all of the LODs are complete. + * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise. + */ + this.onCompleteObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](); + /** + * Observable raised when an error occurs. + */ + this.onErrorObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](); + /** + * Observable raised after the loader is disposed. + */ + this.onDisposeObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](); + /** + * Observable raised after a loader extension is created. + * Set additional options for a loader extension in this event. + */ + this.onExtensionLoadedObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](); + /** + * Defines if the loader should validate the asset. + */ + this.validate = false; + /** + * Observable raised after validation when validate is set to true. The event data is the result of the validation. + */ + this.onValidatedObservable = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](); + this._loader = null; + /** + * Name of the loader ("gltf") + */ + this.name = "gltf"; + /** + * Supported file extensions of the loader (.gltf, .glb) + */ + this.extensions = { + ".gltf": { isBinary: false }, + ".glb": { isBinary: true } + }; + this._logIndentLevel = 0; + this._loggingEnabled = false; + /** @hidden */ + this._log = this._logDisabled; + this._capturePerformanceCounters = false; + /** @hidden */ + this._startPerformanceCounter = this._startPerformanceCounterDisabled; + /** @hidden */ + this._endPerformanceCounter = this._endPerformanceCounterDisabled; + } + Object.defineProperty(GLTFFileLoader.prototype, "onParsed", { + /** + * Raised when the asset has been parsed + */ + set: function (callback) { + if (this._onParsedObserver) { + this.onParsedObservable.remove(this._onParsedObserver); + } + this._onParsedObserver = this.onParsedObservable.add(callback); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", { + /** + * Callback raised when the loader creates a mesh after parsing the glTF properties of the mesh. + */ + set: function (callback) { + if (this._onMeshLoadedObserver) { + this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver); + } + this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", { + /** + * Callback raised when the loader creates a texture after parsing the glTF properties of the texture. + */ + set: function (callback) { + if (this._onTextureLoadedObserver) { + this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver); + } + this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", { + /** + * Callback raised when the loader creates a material after parsing the glTF properties of the material. + */ + set: function (callback) { + if (this._onMaterialLoadedObserver) { + this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver); + } + this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(GLTFFileLoader.prototype, "onCameraLoaded", { + /** + * Callback raised when the loader creates a camera after parsing the glTF properties of the camera. + */ + set: function (callback) { + if (this._onCameraLoadedObserver) { + this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver); + } + this._onCameraLoadedObserver = this.onCameraLoadedObservable.add(callback); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(GLTFFileLoader.prototype, "onComplete", { + /** + * Callback raised when the asset is completely loaded, immediately before the loader is disposed. + * For assets with LODs, raised when all of the LODs are complete. + * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise. + */ + set: function (callback) { + if (this._onCompleteObserver) { + this.onCompleteObservable.remove(this._onCompleteObserver); + } + this._onCompleteObserver = this.onCompleteObservable.add(callback); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(GLTFFileLoader.prototype, "onError", { + /** + * Callback raised when an error occurs. + */ + set: function (callback) { + if (this._onErrorObserver) { + this.onErrorObservable.remove(this._onErrorObserver); + } + this._onErrorObserver = this.onErrorObservable.add(callback); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(GLTFFileLoader.prototype, "onDispose", { + /** + * Callback raised after the loader is disposed. + */ + set: function (callback) { + if (this._onDisposeObserver) { + this.onDisposeObservable.remove(this._onDisposeObserver); + } + this._onDisposeObserver = this.onDisposeObservable.add(callback); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", { + /** + * Callback raised after a loader extension is created. + */ + set: function (callback) { + if (this._onExtensionLoadedObserver) { + this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver); + } + this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(GLTFFileLoader.prototype, "loggingEnabled", { + /** + * Defines if the loader logging is enabled. + */ + get: function () { + return this._loggingEnabled; + }, + set: function (value) { + if (this._loggingEnabled === value) { + return; + } + this._loggingEnabled = value; + if (this._loggingEnabled) { + this._log = this._logEnabled; + } + else { + this._log = this._logDisabled; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(GLTFFileLoader.prototype, "capturePerformanceCounters", { + /** + * Defines if the loader should capture performance counters. + */ + get: function () { + return this._capturePerformanceCounters; + }, + set: function (value) { + if (this._capturePerformanceCounters === value) { + return; + } + this._capturePerformanceCounters = value; + if (this._capturePerformanceCounters) { + this._startPerformanceCounter = this._startPerformanceCounterEnabled; + this._endPerformanceCounter = this._endPerformanceCounterEnabled; + } + else { + this._startPerformanceCounter = this._startPerformanceCounterDisabled; + this._endPerformanceCounter = this._endPerformanceCounterDisabled; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(GLTFFileLoader.prototype, "onValidated", { + /** + * Callback raised after a loader extension is created. + */ + set: function (callback) { + if (this._onValidatedObserver) { + this.onValidatedObservable.remove(this._onValidatedObserver); + } + this._onValidatedObserver = this.onValidatedObservable.add(callback); + }, + enumerable: true, + configurable: true + }); + /** + * Disposes the loader, releases resources during load, and cancels any outstanding requests. + */ + GLTFFileLoader.prototype.dispose = function () { + if (this._loader) { + this._loader.dispose(); + this._loader = null; + } + this._clear(); + this.onDisposeObservable.notifyObservers(undefined); + this.onDisposeObservable.clear(); + }; + /** @hidden */ + GLTFFileLoader.prototype._clear = function () { + this.preprocessUrlAsync = function (url) { return Promise.resolve(url); }; + this.onMeshLoadedObservable.clear(); + this.onTextureLoadedObservable.clear(); + this.onMaterialLoadedObservable.clear(); + this.onCameraLoadedObservable.clear(); + this.onCompleteObservable.clear(); + this.onExtensionLoadedObservable.clear(); + }; + /** + * Imports one or more meshes from the loaded glTF data and adds them to the scene + * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file + * @param scene the scene the meshes should be added to + * @param data the glTF data to load + * @param rootUrl root url to load from + * @param onProgress event that fires when loading progress has occured + * @param fileName Defines the name of the file to load + * @returns a promise containg the loaded meshes, particles, skeletons and animations + */ + GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress, fileName) { + var _this = this; + return this._parseAsync(scene, data, rootUrl, fileName).then(function (loaderData) { + _this._log("Loading " + (fileName || "")); + _this._loader = _this._getLoader(loaderData); + return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress, fileName); + }); + }; + /** + * Imports all objects from the loaded glTF data and adds them to the scene + * @param scene the scene the objects should be added to + * @param data the glTF data to load + * @param rootUrl root url to load from + * @param onProgress event that fires when loading progress has occured + * @param fileName Defines the name of the file to load + * @returns a promise which completes when objects have been loaded to the scene + */ + GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress, fileName) { + var _this = this; + return this._parseAsync(scene, data, rootUrl, fileName).then(function (loaderData) { + _this._log("Loading " + (fileName || "")); + _this._loader = _this._getLoader(loaderData); + return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress, fileName); + }); + }; + /** + * Load into an asset container. + * @param scene The scene to load into + * @param data The data to import + * @param rootUrl The root url for scene and resources + * @param onProgress The callback when the load progresses + * @param fileName Defines the name of the file to load + * @returns The loaded asset container + */ + GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress, fileName) { + var _this = this; + return this._parseAsync(scene, data, rootUrl, fileName).then(function (loaderData) { + _this._log("Loading " + (fileName || "")); + _this._loader = _this._getLoader(loaderData); + // Get materials/textures when loading to add to container + var materials = []; + _this.onMaterialLoadedObservable.add(function (material) { + materials.push(material); + }); + var textures = []; + _this.onTextureLoadedObservable.add(function (texture) { + textures.push(texture); + }); + return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress, fileName).then(function (result) { + var container = new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["AssetContainer"](scene); + Array.prototype.push.apply(container.meshes, result.meshes); + Array.prototype.push.apply(container.particleSystems, result.particleSystems); + Array.prototype.push.apply(container.skeletons, result.skeletons); + Array.prototype.push.apply(container.animationGroups, result.animationGroups); + Array.prototype.push.apply(container.materials, materials); + Array.prototype.push.apply(container.textures, textures); + container.removeAllFromScene(); + return container; + }); + }); + }; + /** + * If the data string can be loaded directly. + * @param data string contianing the file data + * @returns if the data can be loaded directly + */ + GLTFFileLoader.prototype.canDirectLoad = function (data) { + return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1)); + }; + /** + * Instantiates a glTF file loader plugin. + * @returns the created plugin + */ + GLTFFileLoader.prototype.createPlugin = function () { + return new GLTFFileLoader(); + }; + Object.defineProperty(GLTFFileLoader.prototype, "loaderState", { + /** + * The loader state or null if the loader is not active. + */ + get: function () { + return this._loader ? this._loader.state : null; + }, + enumerable: true, + configurable: true + }); + /** + * Returns a promise that resolves when the asset is completely loaded. + * @returns a promise that resolves when the asset is completely loaded. + */ + GLTFFileLoader.prototype.whenCompleteAsync = function () { + var _this = this; + return new Promise(function (resolve, reject) { + _this.onCompleteObservable.addOnce(function () { + resolve(); + }); + _this.onErrorObservable.addOnce(function (reason) { + reject(reason); + }); + }); + }; + GLTFFileLoader.prototype._parseAsync = function (scene, data, rootUrl, fileName) { + var _this = this; + return Promise.resolve().then(function () { + return _this._validateAsync(scene, data, rootUrl, fileName).then(function () { + var unpacked = (data instanceof ArrayBuffer) ? _this._unpackBinary(data) : { json: data, bin: null }; + _this._startPerformanceCounter("Parse JSON"); + _this._log("JSON length: " + unpacked.json.length); + var loaderData = { + json: JSON.parse(unpacked.json), + bin: unpacked.bin + }; + _this._endPerformanceCounter("Parse JSON"); + _this.onParsedObservable.notifyObservers(loaderData); + _this.onParsedObservable.clear(); + return loaderData; + }); + }); + }; + GLTFFileLoader.prototype._validateAsync = function (scene, data, rootUrl, fileName) { + var _this = this; + if (!this.validate || typeof GLTFValidator === "undefined") { + return Promise.resolve(); + } + this._startPerformanceCounter("Validate JSON"); + var options = { + externalResourceFunction: function (uri) { + return _this.preprocessUrlAsync(rootUrl + uri) + .then(function (url) { return scene._loadFileAsync(url, true, true); }) + .then(function (data) { return new Uint8Array(data); }); + } + }; + if (fileName && fileName.substr(0, 5) !== "data:") { + options.uri = (rootUrl === "file:" ? fileName : "" + rootUrl + fileName); + } + var promise = (data instanceof ArrayBuffer) + ? GLTFValidator.validateBytes(new Uint8Array(data), options) + : GLTFValidator.validateString(data, options); + return promise.then(function (result) { + _this._endPerformanceCounter("Validate JSON"); + _this.onValidatedObservable.notifyObservers(result); + _this.onValidatedObservable.clear(); + }, function (reason) { + _this._endPerformanceCounter("Validate JSON"); + babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Tools"].Warn("Failed to validate: " + reason); + _this.onValidatedObservable.clear(); + }); + }; + GLTFFileLoader.prototype._getLoader = function (loaderData) { + var asset = loaderData.json.asset || {}; + this._log("Asset version: " + asset.version); + asset.minVersion && this._log("Asset minimum version: " + asset.minVersion); + asset.generator && this._log("Asset generator: " + asset.generator); + var version = GLTFFileLoader._parseVersion(asset.version); + if (!version) { + throw new Error("Invalid version: " + asset.version); + } + if (asset.minVersion !== undefined) { + var minVersion = GLTFFileLoader._parseVersion(asset.minVersion); + if (!minVersion) { + throw new Error("Invalid minimum version: " + asset.minVersion); + } + if (GLTFFileLoader._compareVersion(minVersion, { major: 2, minor: 0 }) > 0) { + throw new Error("Incompatible minimum version: " + asset.minVersion); + } + } + var createLoaders = { + 1: GLTFFileLoader._CreateGLTF1Loader, + 2: GLTFFileLoader._CreateGLTF2Loader + }; + var createLoader = createLoaders[version.major]; + if (!createLoader) { + throw new Error("Unsupported version: " + asset.version); + } + return createLoader(this); + }; + GLTFFileLoader.prototype._unpackBinary = function (data) { + this._startPerformanceCounter("Unpack binary"); + this._log("Binary length: " + data.byteLength); + var Binary = { + Magic: 0x46546C67 + }; + var binaryReader = new BinaryReader(data); + var magic = binaryReader.readUint32(); + if (magic !== Binary.Magic) { + throw new Error("Unexpected magic: " + magic); + } + var version = binaryReader.readUint32(); + if (this.loggingEnabled) { + this._log("Binary version: " + version); + } + var unpacked; + switch (version) { + case 1: { + unpacked = this._unpackBinaryV1(binaryReader); + break; + } + case 2: { + unpacked = this._unpackBinaryV2(binaryReader); + break; + } + default: { + throw new Error("Unsupported version: " + version); + } + } + this._endPerformanceCounter("Unpack binary"); + return unpacked; + }; + GLTFFileLoader.prototype._unpackBinaryV1 = function (binaryReader) { + var ContentFormat = { + JSON: 0 + }; + var length = binaryReader.readUint32(); + if (length != binaryReader.getLength()) { + throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength()); + } + var contentLength = binaryReader.readUint32(); + var contentFormat = binaryReader.readUint32(); + var content; + switch (contentFormat) { + case ContentFormat.JSON: { + content = GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)); + break; + } + default: { + throw new Error("Unexpected content format: " + contentFormat); + } + } + var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition(); + var body = binaryReader.readUint8Array(bytesRemaining); + return { + json: content, + bin: body + }; + }; + GLTFFileLoader.prototype._unpackBinaryV2 = function (binaryReader) { + var ChunkFormat = { + JSON: 0x4E4F534A, + BIN: 0x004E4942 + }; + var length = binaryReader.readUint32(); + if (length !== binaryReader.getLength()) { + throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength()); + } + // JSON chunk + var chunkLength = binaryReader.readUint32(); + var chunkFormat = binaryReader.readUint32(); + if (chunkFormat !== ChunkFormat.JSON) { + throw new Error("First chunk format is not JSON"); + } + var json = GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)); + // Look for BIN chunk + var bin = null; + while (binaryReader.getPosition() < binaryReader.getLength()) { + var chunkLength_1 = binaryReader.readUint32(); + var chunkFormat_1 = binaryReader.readUint32(); + switch (chunkFormat_1) { + case ChunkFormat.JSON: { + throw new Error("Unexpected JSON chunk"); + } + case ChunkFormat.BIN: { + bin = binaryReader.readUint8Array(chunkLength_1); + break; + } + default: { + // ignore unrecognized chunkFormat + binaryReader.skipBytes(chunkLength_1); + break; + } + } + } + return { + json: json, + bin: bin + }; + }; + GLTFFileLoader._parseVersion = function (version) { + if (version === "1.0" || version === "1.0.1") { + return { + major: 1, + minor: 0 + }; + } + var match = (version + "").match(/^(\d+)\.(\d+)/); + if (!match) { + return null; + } + return { + major: parseInt(match[1]), + minor: parseInt(match[2]) + }; + }; + GLTFFileLoader._compareVersion = function (a, b) { + if (a.major > b.major) { + return 1; + } + if (a.major < b.major) { + return -1; + } + if (a.minor > b.minor) { + return 1; + } + if (a.minor < b.minor) { + return -1; + } + return 0; + }; + GLTFFileLoader._decodeBufferToText = function (buffer) { + if (typeof TextDecoder !== "undefined") { + return new TextDecoder().decode(buffer); + } + var result = ""; + var length = buffer.byteLength; + for (var i = 0; i < length; i++) { + result += String.fromCharCode(buffer[i]); + } + return result; + }; + /** @hidden */ + GLTFFileLoader.prototype._logOpen = function (message) { + this._log(message); + this._logIndentLevel++; + }; + /** @hidden */ + GLTFFileLoader.prototype._logClose = function () { + --this._logIndentLevel; + }; + GLTFFileLoader.prototype._logEnabled = function (message) { + var spaces = GLTFFileLoader._logSpaces.substr(0, this._logIndentLevel * 2); + babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Tools"].Log("" + spaces + message); + }; + GLTFFileLoader.prototype._logDisabled = function (message) { + }; + GLTFFileLoader.prototype._startPerformanceCounterEnabled = function (counterName) { + babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Tools"].StartPerformanceCounter(counterName); + }; + GLTFFileLoader.prototype._startPerformanceCounterDisabled = function (counterName) { + }; + GLTFFileLoader.prototype._endPerformanceCounterEnabled = function (counterName) { + babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Tools"].EndPerformanceCounter(counterName); + }; + GLTFFileLoader.prototype._endPerformanceCounterDisabled = function (counterName) { + }; + // ---------- + // V1 options + // ---------- + /** + * Set this property to false to disable incremental loading which delays the loader from calling the success callback until after loading the meshes and shaders. + * Textures always loads asynchronously. For example, the success callback can compute the bounding information of the loaded meshes when incremental loading is disabled. + * Defaults to true. + * @hidden + */ + GLTFFileLoader.IncrementalLoading = true; + /** + * Set this property to true in order to work with homogeneous coordinates, available with some converters and exporters. + * Defaults to false. See https://en.wikipedia.org/wiki/Homogeneous_coordinates. + * @hidden + */ + GLTFFileLoader.HomogeneousCoordinates = false; + GLTFFileLoader._logSpaces = " "; + return GLTFFileLoader; +}()); + +var BinaryReader = /** @class */ (function () { + function BinaryReader(arrayBuffer) { + this._arrayBuffer = arrayBuffer; + this._dataView = new DataView(arrayBuffer); + this._byteOffset = 0; + } + BinaryReader.prototype.getPosition = function () { + return this._byteOffset; + }; + BinaryReader.prototype.getLength = function () { + return this._arrayBuffer.byteLength; + }; + BinaryReader.prototype.readUint32 = function () { + var value = this._dataView.getUint32(this._byteOffset, true); + this._byteOffset += 4; + return value; + }; + BinaryReader.prototype.readUint8Array = function (length) { + var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length); + this._byteOffset += length; + return value; + }; + BinaryReader.prototype.skipBytes = function (length) { + this._byteOffset += length; + }; + return BinaryReader; +}()); +if (babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["SceneLoader"]) { + babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_0__["SceneLoader"].RegisterPlugin(new GLTFFileLoader()); +} + + +/***/ }), + +/***/ "./legacy/legacy-glTF.ts": +/*!*******************************!*\ + !*** ./legacy/legacy-glTF.ts ***! + \*******************************/ +/*! exports provided: GLTFLoaderCoordinateSystemMode, GLTFLoaderAnimationStartMode, GLTFLoaderState, GLTFFileLoader */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* WEBPACK VAR INJECTION */(function(global) {/* harmony import */ var _glTF_glTFFileLoader__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../glTF/glTFFileLoader */ "./glTF/glTFFileLoader.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GLTFLoaderCoordinateSystemMode", function() { return _glTF_glTFFileLoader__WEBPACK_IMPORTED_MODULE_0__["GLTFLoaderCoordinateSystemMode"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GLTFLoaderAnimationStartMode", function() { return _glTF_glTFFileLoader__WEBPACK_IMPORTED_MODULE_0__["GLTFLoaderAnimationStartMode"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GLTFLoaderState", function() { return _glTF_glTFFileLoader__WEBPACK_IMPORTED_MODULE_0__["GLTFLoaderState"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GLTFFileLoader", function() { return _glTF_glTFFileLoader__WEBPACK_IMPORTED_MODULE_0__["GLTFFileLoader"]; }); + + +/** + * This is the entry point for the UMD module. + * The entry point for a future ESM package should be index.ts + */ +var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : undefined); +if (typeof globalObject !== "undefined") { + globalObject.BABYLON = globalObject.BABYLON || {}; + for (var key in _glTF_glTFFileLoader__WEBPACK_IMPORTED_MODULE_0__) { + globalObject.BABYLON[key] = _glTF_glTFFileLoader__WEBPACK_IMPORTED_MODULE_0__[key]; + } +} + + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../node_modules/webpack/buildin/global.js */ "../../node_modules/webpack/buildin/global.js"))) + +/***/ }), + +/***/ "./legacy/legacy-glTF2.ts": +/*!********************************!*\ + !*** ./legacy/legacy-glTF2.ts ***! + \********************************/ +/*! exports provided: GLTF2 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* WEBPACK VAR INJECTION */(function(global) {/* harmony import */ var _glTF_2_0_Extensions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../glTF/2.0/Extensions */ "./glTF/2.0/Extensions/index.ts"); +/* harmony import */ var _glTF_2_0_glTFLoaderInterfaces__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../glTF/2.0/glTFLoaderInterfaces */ "./glTF/2.0/glTFLoaderInterfaces.ts"); +/* harmony import */ var _glTF_2_0_glTFLoaderInterfaces__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_glTF_2_0_glTFLoaderInterfaces__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var _glTF_2_0__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../glTF/2.0 */ "./glTF/2.0/index.ts"); +/* harmony reexport (module object) */ __webpack_require__.d(__webpack_exports__, "GLTF2", function() { return _glTF_2_0__WEBPACK_IMPORTED_MODULE_2__; }); + + + +/** + * This is the entry point for the UMD module. + * The entry point for a future ESM package should be index.ts + */ +var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : undefined); +if (typeof globalObject !== "undefined") { + globalObject.BABYLON = globalObject.BABYLON || {}; + var BABYLON = globalObject.BABYLON; + BABYLON.GLTF2 = BABYLON.GLTF2 || {}; + BABYLON.GLTF2.Loader = BABYLON.GLTF2.Loader || {}; + BABYLON.GLTF2.Loader.Extensions = BABYLON.GLTF2.Loader.Extensions || {}; + var keys = []; + for (var key in _glTF_2_0_Extensions__WEBPACK_IMPORTED_MODULE_0__) { + BABYLON.GLTF2.Loader.Extensions[key] = _glTF_2_0_Extensions__WEBPACK_IMPORTED_MODULE_0__[key]; + keys.push(key); + } + for (var key in _glTF_2_0_glTFLoaderInterfaces__WEBPACK_IMPORTED_MODULE_1__) { + BABYLON.GLTF2.Loader[key] = _glTF_2_0_glTFLoaderInterfaces__WEBPACK_IMPORTED_MODULE_1__[key]; + keys.push(key); + } + for (var key in _glTF_2_0__WEBPACK_IMPORTED_MODULE_2__) { + // Prevent Reassignment. + if (keys.indexOf(key) > -1) { + continue; + } + BABYLON.GLTF2[key] = _glTF_2_0__WEBPACK_IMPORTED_MODULE_2__[key]; + } +} + + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../node_modules/webpack/buildin/global.js */ "../../node_modules/webpack/buildin/global.js"))) + +/***/ }), + +/***/ "./legacy/legacy-glTF2FileLoader.ts": +/*!******************************************!*\ + !*** ./legacy/legacy-glTF2FileLoader.ts ***! + \******************************************/ +/*! exports provided: GLTF2, GLTFLoaderCoordinateSystemMode, GLTFLoaderAnimationStartMode, GLTFLoaderState, GLTFFileLoader */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _legacy_glTF__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./legacy-glTF */ "./legacy/legacy-glTF.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GLTFLoaderCoordinateSystemMode", function() { return _legacy_glTF__WEBPACK_IMPORTED_MODULE_0__["GLTFLoaderCoordinateSystemMode"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GLTFLoaderAnimationStartMode", function() { return _legacy_glTF__WEBPACK_IMPORTED_MODULE_0__["GLTFLoaderAnimationStartMode"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GLTFLoaderState", function() { return _legacy_glTF__WEBPACK_IMPORTED_MODULE_0__["GLTFLoaderState"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GLTFFileLoader", function() { return _legacy_glTF__WEBPACK_IMPORTED_MODULE_0__["GLTFFileLoader"]; }); + +/* harmony import */ var _legacy_glTF2__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./legacy-glTF2 */ "./legacy/legacy-glTF2.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GLTF2", function() { return _legacy_glTF2__WEBPACK_IMPORTED_MODULE_1__["GLTF2"]; }); + + + + + +/***/ }), + +/***/ "babylonjs/Misc/observable": +/*!****************************************************************************************************!*\ + !*** external {"root":"BABYLON","commonjs":"babylonjs","commonjs2":"babylonjs","amd":"babylonjs"} ***! + \****************************************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +module.exports = __WEBPACK_EXTERNAL_MODULE_babylonjs_Misc_observable__; + +/***/ }) + +/******/ }); +}); +//# sourceMappingURL=babylon.glTF2FileLoader.js.map \ No newline at end of file diff --git a/Source/Scripts/babylon.glTF2FileLoader.min.js b/Source/Scripts/babylon.glTF2FileLoader.min.js new file mode 100644 index 000000000..9c08e578b --- /dev/null +++ b/Source/Scripts/babylon.glTF2FileLoader.min.js @@ -0,0 +1 @@ +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("babylonjs")):"function"==typeof define&&define.amd?define("babylonjs-loaders",["babylonjs"],t):"object"==typeof exports?exports["babylonjs-loaders"]=t(require("babylonjs")):e.LOADERS=t(e.BABYLON)}("undefined"!=typeof self?self:"undefined"!=typeof global?global:this,function(e){return function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=16)}([function(t,n){t.exports=e},function(e,t,n){"use strict";n.d(t,"a",function(){return a}),n.d(t,"b",function(){return i});var r=n(0),o=n(2),a=function(){function e(){}return e.Get=function(e,t,n){if(!t||null==n||!t[n])throw new Error(e+": Failed to find index ("+n+")");return t[n]},e.Assign=function(e){if(e)for(var t=0;t "+o.GLTFLoaderState[o.GLTFLoaderState.READY],s=o.GLTFLoaderState[o.GLTFLoaderState.LOADING]+" => "+o.GLTFLoaderState[o.GLTFLoaderState.COMPLETE];n._parent._startPerformanceCounter(i),n._parent._startPerformanceCounter(s),n._setState(o.GLTFLoaderState.LOADING),n._extensionsOnLoading();var l=new Array,u=n._babylonScene.blockMaterialDirtyMechanism;if(n._babylonScene.blockMaterialDirtyMechanism=!0,e)l.push(n.loadSceneAsync("/nodes",{nodes:e,index:-1}));else if(null!=n._gltf.scene||n._gltf.scenes&&n._gltf.scenes[0]){var d=a.Get("/scene",n._gltf.scenes,n._gltf.scene||0);l.push(n.loadSceneAsync("/scenes/"+d.index,d))}n._babylonScene.blockMaterialDirtyMechanism=u,n._parent.compileMaterials&&l.push(n._compileMaterialsAsync()),n._parent.compileShadowGenerators&&l.push(n._compileShadowGeneratorsAsync());var c=Promise.all(l).then(function(){return n._rootBabylonMesh&&n._rootBabylonMesh.setEnabled(!0),n._setState(o.GLTFLoaderState.READY),n._extensionsOnReady(),n._startAnimations(),t()});return c.then(function(){n._parent._endPerformanceCounter(i),r.Tools.SetImmediate(function(){n._disposed||Promise.all(n._completePromises).then(function(){n._parent._endPerformanceCounter(s),n._setState(o.GLTFLoaderState.COMPLETE),n._parent.onCompleteObservable.notifyObservers(void 0),n._parent.onCompleteObservable.clear(),n.dispose()},function(e){n._parent.onErrorObservable.notifyObservers(e),n._parent.onErrorObservable.clear(),n.dispose()})})}),c},function(e){throw n._disposed||(n._parent.onErrorObservable.notifyObservers(e),n._parent.onErrorObservable.clear(),n.dispose()),e})},e.prototype._loadData=function(e){if(this._gltf=e.json,this._setupData(),e.bin){var t=this._gltf.buffers;if(t&&t[0]&&!t[0].uri){var n=t[0];(n.byteLengthe.bin.byteLength)&&r.Tools.Warn("Binary buffer length ("+n.byteLength+") from JSON does not match chunk length ("+e.bin.byteLength+")"),n._data=Promise.resolve(e.bin)}else r.Tools.Warn("Unexpected BIN chunk")}},e.prototype._setupData=function(){if(a.Assign(this._gltf.accessors),a.Assign(this._gltf.animations),a.Assign(this._gltf.buffers),a.Assign(this._gltf.bufferViews),a.Assign(this._gltf.cameras),a.Assign(this._gltf.images),a.Assign(this._gltf.materials),a.Assign(this._gltf.meshes),a.Assign(this._gltf.nodes),a.Assign(this._gltf.samplers),a.Assign(this._gltf.scenes),a.Assign(this._gltf.skins),a.Assign(this._gltf.textures),this._gltf.nodes){for(var e={},t=0,n=this._gltf.nodes;t0)throw new Error("Incompatible minimum version: "+n.minVersion)}var a={1:e._CreateGLTF1Loader,2:e._CreateGLTF2Loader}[r.major];if(!a)throw new Error("Unsupported version: "+n.version);return a(this)},e.prototype._unpackBinary=function(e){this._startPerformanceCounter("Unpack binary"),this._log("Binary length: "+e.byteLength);var t=new l(e),n=t.readUint32();if(1179937895!==n)throw new Error("Unexpected magic: "+n);var r,o=t.readUint32();switch(this.loggingEnabled&&this._log("Binary version: "+o),o){case 1:r=this._unpackBinaryV1(t);break;case 2:r=this._unpackBinaryV2(t);break;default:throw new Error("Unsupported version: "+o)}return this._endPerformanceCounter("Unpack binary"),r},e.prototype._unpackBinaryV1=function(t){var n=t.readUint32();if(n!=t.getLength())throw new Error("Length in header does not match actual data length: "+n+" != "+t.getLength());var r,o=t.readUint32(),a=t.readUint32();switch(a){case 0:r=e._decodeBufferToText(t.readUint8Array(o));break;default:throw new Error("Unexpected content format: "+a)}var i=t.getLength()-t.getPosition();return{json:r,bin:t.readUint8Array(i)}},e.prototype._unpackBinaryV2=function(t){var n=1313821514,r=5130562,o=t.readUint32();if(o!==t.getLength())throw new Error("Length in header does not match actual data length: "+o+" != "+t.getLength());var a=t.readUint32();if(t.readUint32()!==n)throw new Error("First chunk format is not JSON");for(var i=e._decodeBufferToText(t.readUint8Array(a)),s=null;t.getPosition()t.major?1:e.majort.minor?1:e.minor=0;i--)if(a.push(o.a.Get(e+"/ids/"+r[i],n,r[i])),a.length===this.maxLODsToLoad)return a;return a.push(t),a},e.prototype._disposeUnusedMaterials=function(){var e=this._loader.gltf.materials;if(e)for(var t=0,n=e;t-1||(s.GLTF2[u]=a[u])}}).call(this,n(3))},,,,function(e,t,n){"use strict";n.r(t);var r=n(9);n.d(t,"GLTFLoaderCoordinateSystemMode",function(){return r.c}),n.d(t,"GLTFLoaderAnimationStartMode",function(){return r.b}),n.d(t,"GLTFLoaderState",function(){return r.d}),n.d(t,"GLTFFileLoader",function(){return r.a});var o=n(12);n.d(t,"GLTF2",function(){return o.a})}])}); \ No newline at end of file diff --git a/Source/Scripts/babylon.js b/Source/Scripts/babylon.js new file mode 100644 index 000000000..52a01ac22 --- /dev/null +++ b/Source/Scripts/babylon.js @@ -0,0 +1,16 @@ +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define("babylonjs",[],t):"object"==typeof exports?exports.babylonjs=t():e.BABYLON=t()}("undefined"!=typeof self?self:"undefined"!=typeof global?global:this,function(){return function(e){var t={};function i(n){if(t[n])return t[n].exports;var r=t[n]={i:n,l:!1,exports:{}};return e[n].call(r.exports,r,r.exports,i),r.l=!0,r.exports}return i.m=e,i.c=t,i.d=function(e,t,n){i.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},i.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},i.t=function(e,t){if(1&t&&(e=i(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(i.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var r in e)i.d(n,r,function(t){return e[t]}.bind(null,r));return n},i.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return i.d(t,"a",t),t},i.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},i.p="",i(i.s=130)}([function(e,t,i){"use strict";i.d(t,"u",function(){return s}),i.d(t,"v",function(){return a}),i.d(t,"h",function(){return c}),i.d(t,"e",function(){return l}),i.d(t,"f",function(){return u}),i.d(t,"w",function(){return h}),i.d(t,"x",function(){return d}),i.d(t,"y",function(){return f}),i.d(t,"r",function(){return p}),i.d(t,"q",function(){return _}),i.d(t,"j",function(){return m}),i.d(t,"n",function(){return g}),i.d(t,"z",function(){return v}),i.d(t,"i",function(){return y}),i.d(t,"s",function(){return n}),i.d(t,"c",function(){return T}),i.d(t,"d",function(){return E}),i.d(t,"k",function(){return b}),i.d(t,"a",function(){return x}),i.d(t,"b",function(){return A}),i.d(t,"l",function(){return P}),i.d(t,"m",function(){return R}),i.d(t,"g",function(){return S}),i.d(t,"p",function(){return C}),i.d(t,"o",function(){return M}),i.d(t,"t",function(){return O});var n,r=i(34),o=i(13),s=1/2.2,a=2.2,c=.001,l=function(){function e(e,t,i){void 0===e&&(e=0),void 0===t&&(t=0),void 0===i&&(i=0),this.r=e,this.g=t,this.b=i}return e.prototype.toString=function(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+"}"},e.prototype.getClassName=function(){return"Color3"},e.prototype.getHashCode=function(){var e=255*this.r||0;return e=397*(e=397*e^(255*this.g||0))^(255*this.b||0)},e.prototype.toArray=function(e,t){return void 0===t&&(t=0),e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,this},e.prototype.toColor4=function(e){return void 0===e&&(e=1),new u(this.r,this.g,this.b,e)},e.prototype.asArray=function(){var e=new Array;return this.toArray(e,0),e},e.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},e.prototype.multiply=function(t){return new e(this.r*t.r,this.g*t.g,this.b*t.b)},e.prototype.multiplyToRef=function(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,this},e.prototype.equals=function(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b},e.prototype.equalsFloats=function(e,t,i){return this.r===e&&this.g===t&&this.b===i},e.prototype.scale=function(t){return new e(this.r*t,this.g*t,this.b*t)},e.prototype.scaleToRef=function(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,this},e.prototype.scaleAndAddToRef=function(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,this},e.prototype.clampToRef=function(e,t,i){return void 0===e&&(e=0),void 0===t&&(t=1),i.r=o.a.Clamp(this.r,e,t),i.g=o.a.Clamp(this.g,e,t),i.b=o.a.Clamp(this.b,e,t),this},e.prototype.add=function(t){return new e(this.r+t.r,this.g+t.g,this.b+t.b)},e.prototype.addToRef=function(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,this},e.prototype.subtract=function(t){return new e(this.r-t.r,this.g-t.g,this.b-t.b)},e.prototype.subtractToRef=function(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,this},e.prototype.clone=function(){return new e(this.r,this.g,this.b)},e.prototype.copyFrom=function(e){return this.r=e.r,this.g=e.g,this.b=e.b,this},e.prototype.copyFromFloats=function(e,t,i){return this.r=e,this.g=t,this.b=i,this},e.prototype.set=function(e,t,i){return this.copyFromFloats(e,t,i)},e.prototype.toHexString=function(){var e=255*this.r|0,t=255*this.g|0,i=255*this.b|0;return"#"+o.a.ToHex(e)+o.a.ToHex(t)+o.a.ToHex(i)},e.prototype.toLinearSpace=function(){var t=new e;return this.toLinearSpaceToRef(t),t},e.prototype.toHSV=function(){var t=new e;return this.toHSVToRef(t),t},e.prototype.toHSVToRef=function(e){var t=this.r,i=this.g,n=this.b,r=Math.max(t,i,n),o=Math.min(t,i,n),s=0,a=0,c=r,l=r-o;0!==r&&(a=l/r),r!=o&&(r==t?(s=(i-n)/l,i=0&&o<=1?(a=r,c=s):o>=1&&o<=2?(a=s,c=r):o>=2&&o<=3?(c=r,l=s):o>=3&&o<=4?(c=s,l=r):o>=4&&o<=5?(a=s,l=r):o>=5&&o<=6&&(a=r,l=s);var u=i-r;n.set(a+u,c+u,l+u)},e.FromHexString=function(t){if("#"!==t.substring(0,1)||7!==t.length)return new e(0,0,0);var i=parseInt(t.substring(1,3),16),n=parseInt(t.substring(3,5),16),r=parseInt(t.substring(5,7),16);return e.FromInts(i,n,r)},e.FromArray=function(t,i){return void 0===i&&(i=0),new e(t[i],t[i+1],t[i+2])},e.FromInts=function(t,i,n){return new e(t/255,i/255,n/255)},e.Lerp=function(t,i,n){var r=new e(0,0,0);return e.LerpToRef(t,i,n,r),r},e.LerpToRef=function(e,t,i,n){n.r=e.r+(t.r-e.r)*i,n.g=e.g+(t.g-e.g)*i,n.b=e.b+(t.b-e.b)*i},e.Red=function(){return new e(1,0,0)},e.Green=function(){return new e(0,1,0)},e.Blue=function(){return new e(0,0,1)},e.Black=function(){return new e(0,0,0)},Object.defineProperty(e,"BlackReadOnly",{get:function(){return e._BlackReadOnly},enumerable:!0,configurable:!0}),e.White=function(){return new e(1,1,1)},e.Purple=function(){return new e(.5,0,.5)},e.Magenta=function(){return new e(1,0,1)},e.Yellow=function(){return new e(1,1,0)},e.Gray=function(){return new e(.5,.5,.5)},e.Teal=function(){return new e(0,1,1)},e.Random=function(){return new e(Math.random(),Math.random(),Math.random())},e._BlackReadOnly=e.Black(),e}(),u=function(){function e(e,t,i,n){void 0===e&&(e=0),void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=1),this.r=e,this.g=t,this.b=i,this.a=n}return e.prototype.addInPlace=function(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this.a+=e.a,this},e.prototype.asArray=function(){var e=new Array;return this.toArray(e,0),e},e.prototype.toArray=function(e,t){return void 0===t&&(t=0),e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e[t+3]=this.a,this},e.prototype.equals=function(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b&&this.a===e.a},e.prototype.add=function(t){return new e(this.r+t.r,this.g+t.g,this.b+t.b,this.a+t.a)},e.prototype.subtract=function(t){return new e(this.r-t.r,this.g-t.g,this.b-t.b,this.a-t.a)},e.prototype.subtractToRef=function(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,t.a=this.a-e.a,this},e.prototype.scale=function(t){return new e(this.r*t,this.g*t,this.b*t,this.a*t)},e.prototype.scaleToRef=function(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,t.a=this.a*e,this},e.prototype.scaleAndAddToRef=function(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,t.a+=this.a*e,this},e.prototype.clampToRef=function(e,t,i){return void 0===e&&(e=0),void 0===t&&(t=1),i.r=o.a.Clamp(this.r,e,t),i.g=o.a.Clamp(this.g,e,t),i.b=o.a.Clamp(this.b,e,t),i.a=o.a.Clamp(this.a,e,t),this},e.prototype.multiply=function(t){return new e(this.r*t.r,this.g*t.g,this.b*t.b,this.a*t.a)},e.prototype.multiplyToRef=function(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,t.a=this.a*e.a,t},e.prototype.toString=function(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+" A:"+this.a+"}"},e.prototype.getClassName=function(){return"Color4"},e.prototype.getHashCode=function(){var e=255*this.r||0;return e=397*(e=397*(e=397*e^(255*this.g||0))^(255*this.b||0))^(255*this.a||0)},e.prototype.clone=function(){return new e(this.r,this.g,this.b,this.a)},e.prototype.copyFrom=function(e){return this.r=e.r,this.g=e.g,this.b=e.b,this.a=e.a,this},e.prototype.copyFromFloats=function(e,t,i,n){return this.r=e,this.g=t,this.b=i,this.a=n,this},e.prototype.set=function(e,t,i,n){return this.copyFromFloats(e,t,i,n)},e.prototype.toHexString=function(){var e=255*this.r|0,t=255*this.g|0,i=255*this.b|0,n=255*this.a|0;return"#"+o.a.ToHex(e)+o.a.ToHex(t)+o.a.ToHex(i)+o.a.ToHex(n)},e.prototype.toLinearSpace=function(){var t=new e;return this.toLinearSpaceToRef(t),t},e.prototype.toLinearSpaceToRef=function(e){return e.r=Math.pow(this.r,a),e.g=Math.pow(this.g,a),e.b=Math.pow(this.b,a),e.a=this.a,this},e.prototype.toGammaSpace=function(){var t=new e;return this.toGammaSpaceToRef(t),t},e.prototype.toGammaSpaceToRef=function(e){return e.r=Math.pow(this.r,s),e.g=Math.pow(this.g,s),e.b=Math.pow(this.b,s),e.a=this.a,this},e.FromHexString=function(t){if("#"!==t.substring(0,1)||9!==t.length)return new e(0,0,0,0);var i=parseInt(t.substring(1,3),16),n=parseInt(t.substring(3,5),16),r=parseInt(t.substring(5,7),16),o=parseInt(t.substring(7,9),16);return e.FromInts(i,n,r,o)},e.Lerp=function(t,i,n){var r=new e(0,0,0,0);return e.LerpToRef(t,i,n,r),r},e.LerpToRef=function(e,t,i,n){n.r=e.r+(t.r-e.r)*i,n.g=e.g+(t.g-e.g)*i,n.b=e.b+(t.b-e.b)*i,n.a=e.a+(t.a-e.a)*i},e.FromColor3=function(t,i){return void 0===i&&(i=1),new e(t.r,t.g,t.b,i)},e.FromArray=function(t,i){return void 0===i&&(i=0),new e(t[i],t[i+1],t[i+2],t[i+3])},e.FromInts=function(t,i,n,r){return new e(t/255,i/255,n/255,r/255)},e.CheckColors4=function(e,t){if(e.length===3*t){for(var i=[],n=0;nn.x?n.x:r)n.y?n.y:o)i.x?t.x:i.x,t.y>i.y?t.y:i.y)},e.Transform=function(t,i){var n=e.Zero();return e.TransformToRef(t,i,n),n},e.TransformToRef=function(e,t,i){var n=t.m,r=e.x*n[0]+e.y*n[4]+n[12],o=e.x*n[1]+e.y*n[5]+n[13];i.x=r,i.y=o},e.PointInTriangle=function(e,t,i,n){var r=.5*(-i.y*n.x+t.y*(-i.x+n.x)+t.x*(i.y-n.y)+i.x*n.y),o=r<0?-1:1,s=(t.y*n.x-t.x*n.y+(n.y-t.y)*e.x+(t.x-n.x)*e.y)*o,a=(t.x*i.y-t.y*i.x+(t.y-i.y)*e.x+(i.x-t.x)*e.y)*o;return s>0&&a>0&&s+a<2*r*o},e.Distance=function(t,i){return Math.sqrt(e.DistanceSquared(t,i))},e.DistanceSquared=function(e,t){var i=e.x-t.x,n=e.y-t.y;return i*i+n*n},e.Center=function(e,t){var i=e.add(t);return i.scaleInPlace(.5),i},e.DistanceOfPointFromSegment=function(t,i,n){var r=e.DistanceSquared(i,n);if(0===r)return e.Distance(t,i);var o=n.subtract(i),s=Math.max(0,Math.min(1,e.Dot(t.subtract(i),o)/r)),a=i.add(o.multiplyByFloats(s,s));return e.Distance(t,a)},e}(),d=function(){function e(e,t,i){void 0===e&&(e=0),void 0===t&&(t=0),void 0===i&&(i=0),this.x=e,this.y=t,this.z=i}return e.prototype.toString=function(){return"{X: "+this.x+" Y:"+this.y+" Z:"+this.z+"}"},e.prototype.getClassName=function(){return"Vector3"},e.prototype.getHashCode=function(){var e=this.x||0;return e=397*(e=397*e^(this.y||0))^(this.z||0)},e.prototype.asArray=function(){var e=[];return this.toArray(e,0),e},e.prototype.toArray=function(e,t){return void 0===t&&(t=0),e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,this},e.prototype.toQuaternion=function(){return _.RotationYawPitchRoll(this.y,this.x,this.z)},e.prototype.addInPlace=function(e){return this.addInPlaceFromFloats(e.x,e.y,e.z)},e.prototype.addInPlaceFromFloats=function(e,t,i){return this.x+=e,this.y+=t,this.z+=i,this},e.prototype.add=function(t){return new e(this.x+t.x,this.y+t.y,this.z+t.z)},e.prototype.addToRef=function(e,t){return t.copyFromFloats(this.x+e.x,this.y+e.y,this.z+e.z)},e.prototype.subtractInPlace=function(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this},e.prototype.subtract=function(t){return new e(this.x-t.x,this.y-t.y,this.z-t.z)},e.prototype.subtractToRef=function(e,t){return this.subtractFromFloatsToRef(e.x,e.y,e.z,t)},e.prototype.subtractFromFloats=function(t,i,n){return new e(this.x-t,this.y-i,this.z-n)},e.prototype.subtractFromFloatsToRef=function(e,t,i,n){return n.copyFromFloats(this.x-e,this.y-t,this.z-i)},e.prototype.negate=function(){return new e(-this.x,-this.y,-this.z)},e.prototype.scaleInPlace=function(e){return this.x*=e,this.y*=e,this.z*=e,this},e.prototype.scale=function(t){return new e(this.x*t,this.y*t,this.z*t)},e.prototype.scaleToRef=function(e,t){return t.copyFromFloats(this.x*e,this.y*e,this.z*e)},e.prototype.scaleAndAddToRef=function(e,t){return t.addInPlaceFromFloats(this.x*e,this.y*e,this.z*e)},e.prototype.equals=function(e){return e&&this.x===e.x&&this.y===e.y&&this.z===e.z},e.prototype.equalsWithEpsilon=function(e,t){return void 0===t&&(t=c),e&&o.a.WithinEpsilon(this.x,e.x,t)&&o.a.WithinEpsilon(this.y,e.y,t)&&o.a.WithinEpsilon(this.z,e.z,t)},e.prototype.equalsToFloats=function(e,t,i){return this.x===e&&this.y===t&&this.z===i},e.prototype.multiplyInPlace=function(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this},e.prototype.multiply=function(e){return this.multiplyByFloats(e.x,e.y,e.z)},e.prototype.multiplyToRef=function(e,t){return t.copyFromFloats(this.x*e.x,this.y*e.y,this.z*e.z)},e.prototype.multiplyByFloats=function(t,i,n){return new e(this.x*t,this.y*i,this.z*n)},e.prototype.divide=function(t){return new e(this.x/t.x,this.y/t.y,this.z/t.z)},e.prototype.divideToRef=function(e,t){return t.copyFromFloats(this.x/e.x,this.y/e.y,this.z/e.z)},e.prototype.divideInPlace=function(e){return this.divideToRef(e,this)},e.prototype.minimizeInPlace=function(e){return this.minimizeInPlaceFromFloats(e.x,e.y,e.z)},e.prototype.maximizeInPlace=function(e){return this.maximizeInPlaceFromFloats(e.x,e.y,e.z)},e.prototype.minimizeInPlaceFromFloats=function(e,t,i){return ethis.x&&(this.x=e),t>this.y&&(this.y=t),i>this.z&&(this.z=i),this},e.prototype.isNonUniformWithinEpsilon=function(e){var t=Math.abs(this.x),i=Math.abs(this.y);if(!o.a.WithinEpsilon(t,i,e))return!0;var n=Math.abs(this.z);return!o.a.WithinEpsilon(t,n,e)||!o.a.WithinEpsilon(i,n,e)},Object.defineProperty(e.prototype,"isNonUniform",{get:function(){var e=Math.abs(this.x),t=Math.abs(this.y);if(e!==t)return!0;var i=Math.abs(this.z);return e!==i||t!==i},enumerable:!0,configurable:!0}),e.prototype.floor=function(){return new e(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z))},e.prototype.fract=function(){return new e(this.x-Math.floor(this.x),this.y-Math.floor(this.y),this.z-Math.floor(this.z))},e.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},e.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},e.prototype.normalize=function(){return this.normalizeFromLength(this.length())},e.prototype.reorderInPlace=function(e){var t=this;return"xyz"===(e=e.toLowerCase())?this:(I.Vector3[0].copyFrom(this),["x","y","z"].forEach(function(i,n){t[i]=I.Vector3[0][e[n]]}),this)},e.prototype.rotateByQuaternionToRef=function(t,i){return t.toRotationMatrix(I.Matrix[0]),e.TransformCoordinatesToRef(this,I.Matrix[0],i),i},e.prototype.rotateByQuaternionAroundPointToRef=function(e,t,i){return this.subtractToRef(t,I.Vector3[0]),I.Vector3[0].rotateByQuaternionToRef(e,I.Vector3[0]),t.addToRef(I.Vector3[0],i),i},e.prototype.normalizeFromLength=function(e){return 0===e||1===e?this:this.scaleInPlace(1/e)},e.prototype.normalizeToNew=function(){var t=new e(0,0,0);return this.normalizeToRef(t),t},e.prototype.normalizeToRef=function(e){var t=this.length();return 0===t||1===t?e.copyFromFloats(this.x,this.y,this.z):this.scaleToRef(1/t,e)},e.prototype.clone=function(){return new e(this.x,this.y,this.z)},e.prototype.copyFrom=function(e){return this.copyFromFloats(e.x,e.y,e.z)},e.prototype.copyFromFloats=function(e,t,i){return this.x=e,this.y=t,this.z=i,this},e.prototype.set=function(e,t,i){return this.copyFromFloats(e,t,i)},e.prototype.setAll=function(e){return this.x=this.y=this.z=e,this},e.GetClipFactor=function(t,i,n,r){var o=e.Dot(t,n)-r;return o/(o-(e.Dot(i,n)-r))},e.GetAngleBetweenVectors=function(t,i,n){var r=t.normalizeToRef(I.Vector3[1]),o=i.normalizeToRef(I.Vector3[2]),s=e.Dot(r,o),a=I.Vector3[3];return e.CrossToRef(r,o,a),e.Dot(a,n)>0?Math.acos(s):-Math.acos(s)},e.FromArray=function(t,i){return void 0===i&&(i=0),new e(t[i],t[i+1],t[i+2])},e.FromFloatArray=function(t,i){return e.FromArray(t,i)},e.FromArrayToRef=function(e,t,i){i.x=e[t],i.y=e[t+1],i.z=e[t+2]},e.FromFloatArrayToRef=function(t,i,n){return e.FromArrayToRef(t,i,n)},e.FromFloatsToRef=function(e,t,i,n){n.copyFromFloats(e,t,i)},e.Zero=function(){return new e(0,0,0)},e.One=function(){return new e(1,1,1)},e.Up=function(){return new e(0,1,0)},Object.defineProperty(e,"UpReadOnly",{get:function(){return e._UpReadOnly},enumerable:!0,configurable:!0}),Object.defineProperty(e,"ZeroReadOnly",{get:function(){return e._ZeroReadOnly},enumerable:!0,configurable:!0}),e.Down=function(){return new e(0,-1,0)},e.Forward=function(){return new e(0,0,1)},e.Backward=function(){return new e(0,0,-1)},e.Right=function(){return new e(1,0,0)},e.Left=function(){return new e(-1,0,0)},e.TransformCoordinates=function(t,i){var n=e.Zero();return e.TransformCoordinatesToRef(t,i,n),n},e.TransformCoordinatesToRef=function(t,i,n){e.TransformCoordinatesFromFloatsToRef(t.x,t.y,t.z,i,n)},e.TransformCoordinatesFromFloatsToRef=function(e,t,i,n,r){var o=n.m,s=e*o[0]+t*o[4]+i*o[8]+o[12],a=e*o[1]+t*o[5]+i*o[9]+o[13],c=e*o[2]+t*o[6]+i*o[10]+o[14],l=1/(e*o[3]+t*o[7]+i*o[11]+o[15]);r.x=s*l,r.y=a*l,r.z=c*l},e.TransformNormal=function(t,i){var n=e.Zero();return e.TransformNormalToRef(t,i,n),n},e.TransformNormalToRef=function(e,t,i){this.TransformNormalFromFloatsToRef(e.x,e.y,e.z,t,i)},e.TransformNormalFromFloatsToRef=function(e,t,i,n,r){var o=n.m;r.x=e*o[0]+t*o[4]+i*o[8],r.y=e*o[1]+t*o[5]+i*o[9],r.z=e*o[2]+t*o[6]+i*o[10]},e.CatmullRom=function(t,i,n,r,o){var s=o*o,a=o*s;return new e(.5*(2*i.x+(-t.x+n.x)*o+(2*t.x-5*i.x+4*n.x-r.x)*s+(-t.x+3*i.x-3*n.x+r.x)*a),.5*(2*i.y+(-t.y+n.y)*o+(2*t.y-5*i.y+4*n.y-r.y)*s+(-t.y+3*i.y-3*n.y+r.y)*a),.5*(2*i.z+(-t.z+n.z)*o+(2*t.z-5*i.z+4*n.z-r.z)*s+(-t.z+3*i.z-3*n.z+r.z)*a))},e.Clamp=function(t,i,n){var r=new e;return e.ClampToRef(t,i,n,r),r},e.ClampToRef=function(e,t,i,n){var r=e.x;r=(r=r>i.x?i.x:r)i.y?i.y:o)i.z?i.z:s)this.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),e.z>this.z&&(this.z=e.z),e.w>this.w&&(this.w=e.w),this},e.prototype.floor=function(){return new e(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z),Math.floor(this.w))},e.prototype.fract=function(){return new e(this.x-Math.floor(this.x),this.y-Math.floor(this.y),this.z-Math.floor(this.z),this.w-Math.floor(this.w))},e.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},e.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},e.prototype.normalize=function(){var e=this.length();return 0===e?this:this.scaleInPlace(1/e)},e.prototype.toVector3=function(){return new d(this.x,this.y,this.z)},e.prototype.clone=function(){return new e(this.x,this.y,this.z,this.w)},e.prototype.copyFrom=function(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this},e.prototype.copyFromFloats=function(e,t,i,n){return this.x=e,this.y=t,this.z=i,this.w=n,this},e.prototype.set=function(e,t,i,n){return this.copyFromFloats(e,t,i,n)},e.prototype.setAll=function(e){return this.x=this.y=this.z=this.w=e,this},e.FromArray=function(t,i){return i||(i=0),new e(t[i],t[i+1],t[i+2],t[i+3])},e.FromArrayToRef=function(e,t,i){i.x=e[t],i.y=e[t+1],i.z=e[t+2],i.w=e[t+3]},e.FromFloatArrayToRef=function(t,i,n){e.FromArrayToRef(t,i,n)},e.FromFloatsToRef=function(e,t,i,n,r){r.x=e,r.y=t,r.z=i,r.w=n},e.Zero=function(){return new e(0,0,0,0)},e.One=function(){return new e(1,1,1,1)},e.Normalize=function(t){var i=e.Zero();return e.NormalizeToRef(t,i),i},e.NormalizeToRef=function(e,t){t.copyFrom(e),t.normalize()},e.Minimize=function(e,t){var i=e.clone();return i.minimizeInPlace(t),i},e.Maximize=function(e,t){var i=e.clone();return i.maximizeInPlace(t),i},e.Distance=function(t,i){return Math.sqrt(e.DistanceSquared(t,i))},e.DistanceSquared=function(e,t){var i=e.x-t.x,n=e.y-t.y,r=e.z-t.z,o=e.w-t.w;return i*i+n*n+r*r+o*o},e.Center=function(e,t){var i=e.add(t);return i.scaleInPlace(.5),i},e.TransformNormal=function(t,i){var n=e.Zero();return e.TransformNormalToRef(t,i,n),n},e.TransformNormalToRef=function(e,t,i){var n=t.m,r=e.x*n[0]+e.y*n[4]+e.z*n[8],o=e.x*n[1]+e.y*n[5]+e.z*n[9],s=e.x*n[2]+e.y*n[6]+e.z*n[10];i.x=r,i.y=o,i.z=s,i.w=e.w},e.TransformNormalFromFloatsToRef=function(e,t,i,n,r,o){var s=r.m;o.x=e*s[0]+t*s[4]+i*s[8],o.y=e*s[1]+t*s[5]+i*s[9],o.z=e*s[2]+t*s[6]+i*s[10],o.w=n},e.FromVector3=function(t,i){return void 0===i&&(i=0),new e(t.x,t.y,t.z,i)},e}(),p=function(){function e(e,t){this.width=e,this.height=t}return e.prototype.toString=function(){return"{W: "+this.width+", H: "+this.height+"}"},e.prototype.getClassName=function(){return"Size"},e.prototype.getHashCode=function(){var e=this.width||0;return e=397*e^(this.height||0)},e.prototype.copyFrom=function(e){this.width=e.width,this.height=e.height},e.prototype.copyFromFloats=function(e,t){return this.width=e,this.height=t,this},e.prototype.set=function(e,t){return this.copyFromFloats(e,t)},e.prototype.multiplyByFloats=function(t,i){return new e(this.width*t,this.height*i)},e.prototype.clone=function(){return new e(this.width,this.height)},e.prototype.equals=function(e){return!!e&&(this.width===e.width&&this.height===e.height)},Object.defineProperty(e.prototype,"surface",{get:function(){return this.width*this.height},enumerable:!0,configurable:!0}),e.Zero=function(){return new e(0,0)},e.prototype.add=function(t){return new e(this.width+t.width,this.height+t.height)},e.prototype.subtract=function(t){return new e(this.width-t.width,this.height-t.height)},e.Lerp=function(t,i,n){return new e(t.width+(i.width-t.width)*n,t.height+(i.height-t.height)*n)},e}(),_=function(){function e(e,t,i,n){void 0===e&&(e=0),void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=1),this.x=e,this.y=t,this.z=i,this.w=n}return e.prototype.toString=function(){return"{X: "+this.x+" Y:"+this.y+" Z:"+this.z+" W:"+this.w+"}"},e.prototype.getClassName=function(){return"Quaternion"},e.prototype.getHashCode=function(){var e=this.x||0;return e=397*(e=397*(e=397*e^(this.y||0))^(this.z||0))^(this.w||0)},e.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},e.prototype.equals=function(e){return e&&this.x===e.x&&this.y===e.y&&this.z===e.z&&this.w===e.w},e.prototype.clone=function(){return new e(this.x,this.y,this.z,this.w)},e.prototype.copyFrom=function(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this},e.prototype.copyFromFloats=function(e,t,i,n){return this.x=e,this.y=t,this.z=i,this.w=n,this},e.prototype.set=function(e,t,i,n){return this.copyFromFloats(e,t,i,n)},e.prototype.add=function(t){return new e(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},e.prototype.addInPlace=function(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this},e.prototype.subtract=function(t){return new e(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},e.prototype.scale=function(t){return new e(this.x*t,this.y*t,this.z*t,this.w*t)},e.prototype.scaleToRef=function(e,t){return t.x=this.x*e,t.y=this.y*e,t.z=this.z*e,t.w=this.w*e,this},e.prototype.scaleInPlace=function(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this},e.prototype.scaleAndAddToRef=function(e,t){return t.x+=this.x*e,t.y+=this.y*e,t.z+=this.z*e,t.w+=this.w*e,this},e.prototype.multiply=function(t){var i=new e(0,0,0,1);return this.multiplyToRef(t,i),i},e.prototype.multiplyToRef=function(e,t){var i=this.x*e.w+this.y*e.z-this.z*e.y+this.w*e.x,n=-this.x*e.z+this.y*e.w+this.z*e.x+this.w*e.y,r=this.x*e.y-this.y*e.x+this.z*e.w+this.w*e.z,o=-this.x*e.x-this.y*e.y-this.z*e.z+this.w*e.w;return t.copyFromFloats(i,n,r,o),this},e.prototype.multiplyInPlace=function(e){return this.multiplyToRef(e,this),this},e.prototype.conjugateToRef=function(e){return e.copyFromFloats(-this.x,-this.y,-this.z,this.w),this},e.prototype.conjugateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},e.prototype.conjugate=function(){return new e(-this.x,-this.y,-this.z,this.w)},e.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},e.prototype.normalize=function(){var e=this.length();if(0===e)return this;var t=1/e;return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},e.prototype.toEulerAngles=function(e){void 0===e&&(e="YZX");var t=d.Zero();return this.toEulerAnglesToRef(t),t},e.prototype.toEulerAnglesToRef=function(e){var t=this.z,i=this.x,n=this.y,r=this.w,o=r*r,s=t*t,a=i*i,c=n*n,l=n*t-i*r;return l<-.4999999?(e.y=2*Math.atan2(n,r),e.x=Math.PI/2,e.z=0):l>.4999999?(e.y=2*Math.atan2(n,r),e.x=-Math.PI/2,e.z=0):(e.z=Math.atan2(2*(i*n+t*r),-s-a+c+o),e.x=Math.asin(-2*(t*n-i*r)),e.y=Math.atan2(2*(t*i+n*r),s-a-c+o)),this},e.prototype.toRotationMatrix=function(e){return m.FromQuaternionToRef(this,e),this},e.prototype.fromRotationMatrix=function(t){return e.FromRotationMatrixToRef(t,this),this},e.FromRotationMatrix=function(t){var i=new e;return e.FromRotationMatrixToRef(t,i),i},e.FromRotationMatrixToRef=function(e,t){var i,n=e.m,r=n[0],o=n[4],s=n[8],a=n[1],c=n[5],l=n[9],u=n[2],h=n[6],d=n[10],f=r+c+d;f>0?(i=.5/Math.sqrt(f+1),t.w=.25/i,t.x=(h-l)*i,t.y=(s-u)*i,t.z=(a-o)*i):r>c&&r>d?(i=2*Math.sqrt(1+r-c-d),t.w=(h-l)/i,t.x=.25*i,t.y=(o+a)/i,t.z=(s+u)/i):c>d?(i=2*Math.sqrt(1+c-r-d),t.w=(s-u)/i,t.x=(o+a)/i,t.y=.25*i,t.z=(l+h)/i):(i=2*Math.sqrt(1+d-r-c),t.w=(a-o)/i,t.x=(s+u)/i,t.y=(l+h)/i,t.z=.25*i)},e.Dot=function(e,t){return e.x*t.x+e.y*t.y+e.z*t.z+e.w*t.w},e.AreClose=function(t,i){return e.Dot(t,i)>=0},e.Zero=function(){return new e(0,0,0,0)},e.Inverse=function(t){return new e(-t.x,-t.y,-t.z,t.w)},e.InverseToRef=function(e,t){return t.set(-e.x,-e.y,-e.z,e.w),t},e.Identity=function(){return new e(0,0,0,1)},e.IsIdentity=function(e){return e&&0===e.x&&0===e.y&&0===e.z&&1===e.w},e.RotationAxis=function(t,i){return e.RotationAxisToRef(t,i,new e)},e.RotationAxisToRef=function(e,t,i){var n=Math.sin(t/2);return e.normalize(),i.w=Math.cos(t/2),i.x=e.x*n,i.y=e.y*n,i.z=e.z*n,i},e.FromArray=function(t,i){return i||(i=0),new e(t[i],t[i+1],t[i+2],t[i+3])},e.FromEulerAngles=function(t,i,n){var r=new e;return e.RotationYawPitchRollToRef(i,t,n,r),r},e.FromEulerAnglesToRef=function(t,i,n,r){return e.RotationYawPitchRollToRef(i,t,n,r),r},e.FromEulerVector=function(t){var i=new e;return e.RotationYawPitchRollToRef(t.y,t.x,t.z,i),i},e.FromEulerVectorToRef=function(t,i){return e.RotationYawPitchRollToRef(t.y,t.x,t.z,i),i},e.RotationYawPitchRoll=function(t,i,n){var r=new e;return e.RotationYawPitchRollToRef(t,i,n,r),r},e.RotationYawPitchRollToRef=function(e,t,i,n){var r=.5*i,o=.5*t,s=.5*e,a=Math.sin(r),c=Math.cos(r),l=Math.sin(o),u=Math.cos(o),h=Math.sin(s),d=Math.cos(s);n.x=d*l*c+h*u*a,n.y=h*u*c-d*l*a,n.z=d*u*a-h*l*c,n.w=d*u*c+h*l*a},e.RotationAlphaBetaGamma=function(t,i,n){var r=new e;return e.RotationAlphaBetaGammaToRef(t,i,n,r),r},e.RotationAlphaBetaGammaToRef=function(e,t,i,n){var r=.5*(i+e),o=.5*(i-e),s=.5*t;n.x=Math.cos(o)*Math.sin(s),n.y=Math.sin(o)*Math.sin(s),n.z=Math.sin(r)*Math.cos(s),n.w=Math.cos(r)*Math.cos(s)},e.RotationQuaternionFromAxis=function(t,i,n){var r=new e(0,0,0,0);return e.RotationQuaternionFromAxisToRef(t,i,n,r),r},e.RotationQuaternionFromAxisToRef=function(t,i,n,r){var o=I.Matrix[0];m.FromXYZAxesToRef(t.normalize(),i.normalize(),n.normalize(),o),e.FromRotationMatrixToRef(o,r)},e.Slerp=function(t,i,n){var r=e.Identity();return e.SlerpToRef(t,i,n,r),r},e.SlerpToRef=function(e,t,i,n){var r,o,s=e.x*t.x+e.y*t.y+e.z*t.z+e.w*t.w,a=!1;if(s<0&&(a=!0,s=-s),s>.999999)o=1-i,r=a?-i:i;else{var c=Math.acos(s),l=1/Math.sin(c);o=Math.sin((1-i)*c)*l,r=a?-Math.sin(i*c)*l:Math.sin(i*c)*l}n.x=o*e.x+r*t.x,n.y=o*e.y+r*t.y,n.z=o*e.z+r*t.z,n.w=o*e.w+r*t.w},e.Hermite=function(t,i,n,r,o){var s=o*o,a=o*s,c=2*a-3*s+1,l=-2*a+3*s,u=a-2*s+o,h=a-s;return new e(t.x*c+n.x*l+i.x*u+r.x*h,t.y*c+n.y*l+i.y*u+r.y*h,t.z*c+n.z*l+i.z*u+r.z*h,t.w*c+n.w*l+i.w*u+r.w*h)},e}(),m=function(){function e(){this._isIdentity=!1,this._isIdentityDirty=!0,this._isIdentity3x2=!0,this._isIdentity3x2Dirty=!0,this.updateFlag=-1,this._m=new Float32Array(16),this._updateIdentityStatus(!1)}return Object.defineProperty(e.prototype,"m",{get:function(){return this._m},enumerable:!0,configurable:!0}),e.prototype._markAsUpdated=function(){this.updateFlag=e._updateFlagSeed++,this._isIdentity=!1,this._isIdentity3x2=!1,this._isIdentityDirty=!0,this._isIdentity3x2Dirty=!0},e.prototype._updateIdentityStatus=function(t,i,n,r){void 0===i&&(i=!1),void 0===n&&(n=!1),void 0===r&&(r=!0),this.updateFlag=e._updateFlagSeed++,this._isIdentity=t,this._isIdentity3x2=t||n,this._isIdentityDirty=!this._isIdentity&&i,this._isIdentity3x2Dirty=!this._isIdentity3x2&&r},e.prototype.isIdentity=function(){if(this._isIdentityDirty){this._isIdentityDirty=!1;var e=this._m;this._isIdentity=1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15]}return this._isIdentity},e.prototype.isIdentityAs3x2=function(){return this._isIdentity3x2Dirty&&(this._isIdentity3x2Dirty=!1,1!==this._m[0]||1!==this._m[5]||1!==this._m[15]?this._isIdentity3x2=!1:0!==this._m[1]||0!==this._m[2]||0!==this._m[3]||0!==this._m[4]||0!==this._m[6]||0!==this._m[7]||0!==this._m[8]||0!==this._m[9]||0!==this._m[10]||0!==this._m[11]||0!==this._m[12]||0!==this._m[13]||0!==this._m[14]?this._isIdentity3x2=!1:this._isIdentity3x2=!0),this._isIdentity3x2},e.prototype.determinant=function(){if(!0===this._isIdentity)return 1;var e=this._m,t=e[0],i=e[1],n=e[2],r=e[3],o=e[4],s=e[5],a=e[6],c=e[7],l=e[8],u=e[9],h=e[10],d=e[11],f=e[12],p=e[13],_=e[14],m=e[15],g=h*m-_*d,v=u*m-p*d,y=u*_-p*h,b=l*m-f*d,T=l*_-h*f,E=l*p-f*u;return t*+(s*g-a*v+c*y)+i*-(o*g-a*b+c*T)+n*+(o*v-s*b+c*E)+r*-(o*y-s*T+a*E)},e.prototype.toArray=function(){return this._m},e.prototype.asArray=function(){return this._m},e.prototype.invert=function(){return this.invertToRef(this),this},e.prototype.reset=function(){return e.FromValuesToRef(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,this),this._updateIdentityStatus(!1),this},e.prototype.add=function(t){var i=new e;return this.addToRef(t,i),i},e.prototype.addToRef=function(e,t){for(var i=this._m,n=t._m,r=e.m,o=0;o<16;o++)n[o]=i[o]+r[o];return t._markAsUpdated(),this},e.prototype.addToSelf=function(e){for(var t=this._m,i=e.m,n=0;n<16;n++)t[n]+=i[n];return this._markAsUpdated(),this},e.prototype.invertToRef=function(t){if(!0===this._isIdentity)return e.IdentityToRef(t),this;var i=this._m,n=i[0],r=i[1],o=i[2],s=i[3],a=i[4],c=i[5],l=i[6],u=i[7],h=i[8],d=i[9],f=i[10],p=i[11],_=i[12],m=i[13],g=i[14],v=i[15],y=f*v-g*p,b=d*v-m*p,T=d*g-m*f,E=h*v-_*p,x=h*g-f*_,A=h*m-_*d,P=+(c*y-l*b+u*T),R=-(a*y-l*E+u*x),S=+(a*b-c*E+u*A),C=-(a*T-c*x+l*A),M=n*P+r*R+o*S+s*C;if(0===M)return t.copyFrom(this),this;var O=1/M,I=l*v-g*u,D=c*v-m*u,L=c*g-m*l,w=a*v-_*u,F=a*g-_*l,N=a*m-_*c,B=l*p-f*u,U=c*p-d*u,V=c*f-d*l,k=a*p-h*u,G=a*f-h*l,z=a*d-h*c,j=-(r*y-o*b+s*T),W=+(n*y-o*E+s*x),H=-(n*b-r*E+s*A),X=+(n*T-r*x+o*A),Y=+(r*I-o*D+s*L),K=-(n*I-o*w+s*F),Q=+(n*D-r*w+s*N),q=-(n*L-r*F+o*N),Z=-(r*B-o*U+s*V),J=+(n*B-o*k+s*G),$=-(n*U-r*k+s*z),ee=+(n*V-r*G+o*z);return e.FromValuesToRef(P*O,j*O,Y*O,Z*O,R*O,W*O,K*O,J*O,S*O,H*O,Q*O,$*O,C*O,X*O,q*O,ee*O,t),this},e.prototype.addAtIndex=function(e,t){return this._m[e]+=t,this._markAsUpdated(),this},e.prototype.multiplyAtIndex=function(e,t){return this._m[e]*=t,this._markAsUpdated(),this},e.prototype.setTranslationFromFloats=function(e,t,i){return this._m[12]=e,this._m[13]=t,this._m[14]=i,this._markAsUpdated(),this},e.prototype.addTranslationFromFloats=function(e,t,i){return this._m[12]+=e,this._m[13]+=t,this._m[14]+=i,this._markAsUpdated(),this},e.prototype.setTranslation=function(e){return this.setTranslationFromFloats(e.x,e.y,e.z)},e.prototype.getTranslation=function(){return new d(this._m[12],this._m[13],this._m[14])},e.prototype.getTranslationToRef=function(e){return e.x=this._m[12],e.y=this._m[13],e.z=this._m[14],this},e.prototype.removeRotationAndScaling=function(){var t=this.m;return e.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t[12],t[13],t[14],t[15],this),this._updateIdentityStatus(0===t[12]&&0===t[13]&&0===t[14]&&1===t[15]),this},e.prototype.multiply=function(t){var i=new e;return this.multiplyToRef(t,i),i},e.prototype.copyFrom=function(e){e.copyToArray(this._m);var t=e;return this._updateIdentityStatus(t._isIdentity,t._isIdentityDirty,t._isIdentity3x2,t._isIdentity3x2Dirty),this},e.prototype.copyToArray=function(e,t){void 0===t&&(t=0);for(var i=0;i<16;i++)e[t+i]=this._m[i];return this},e.prototype.multiplyToRef=function(e,t){return this._isIdentity?(t.copyFrom(e),this):e._isIdentity?(t.copyFrom(this),this):(this.multiplyToArray(e,t._m,0),t._markAsUpdated(),this)},e.prototype.multiplyToArray=function(e,t,i){var n=this._m,r=e.m,o=n[0],s=n[1],a=n[2],c=n[3],l=n[4],u=n[5],h=n[6],d=n[7],f=n[8],p=n[9],_=n[10],m=n[11],g=n[12],v=n[13],y=n[14],b=n[15],T=r[0],E=r[1],x=r[2],A=r[3],P=r[4],R=r[5],S=r[6],C=r[7],M=r[8],O=r[9],I=r[10],D=r[11],L=r[12],w=r[13],F=r[14],N=r[15];return t[i]=o*T+s*P+a*M+c*L,t[i+1]=o*E+s*R+a*O+c*w,t[i+2]=o*x+s*S+a*I+c*F,t[i+3]=o*A+s*C+a*D+c*N,t[i+4]=l*T+u*P+h*M+d*L,t[i+5]=l*E+u*R+h*O+d*w,t[i+6]=l*x+u*S+h*I+d*F,t[i+7]=l*A+u*C+h*D+d*N,t[i+8]=f*T+p*P+_*M+m*L,t[i+9]=f*E+p*R+_*O+m*w,t[i+10]=f*x+p*S+_*I+m*F,t[i+11]=f*A+p*C+_*D+m*N,t[i+12]=g*T+v*P+y*M+b*L,t[i+13]=g*E+v*R+y*O+b*w,t[i+14]=g*x+v*S+y*I+b*F,t[i+15]=g*A+v*C+y*D+b*N,this},e.prototype.equals=function(e){var t=e;if(!t)return!1;if((this._isIdentity||t._isIdentity)&&!this._isIdentityDirty&&!t._isIdentityDirty)return this._isIdentity&&t._isIdentity;var i=this.m,n=t.m;return i[0]===n[0]&&i[1]===n[1]&&i[2]===n[2]&&i[3]===n[3]&&i[4]===n[4]&&i[5]===n[5]&&i[6]===n[6]&&i[7]===n[7]&&i[8]===n[8]&&i[9]===n[9]&&i[10]===n[10]&&i[11]===n[11]&&i[12]===n[12]&&i[13]===n[13]&&i[14]===n[14]&&i[15]===n[15]},e.prototype.clone=function(){var t=new e;return t.copyFrom(this),t},e.prototype.getClassName=function(){return"Matrix"},e.prototype.getHashCode=function(){for(var e=this._m[0]||0,t=1;t<16;t++)e=397*e^(this._m[t]||0);return e},e.prototype.decompose=function(t,i,n){if(this._isIdentity)return n&&n.setAll(0),t&&t.setAll(1),i&&i.copyFromFloats(0,0,0,1),!0;var r=this._m;if(n&&n.copyFromFloats(r[12],r[13],r[14]),(t=t||I.Vector3[0]).x=Math.sqrt(r[0]*r[0]+r[1]*r[1]+r[2]*r[2]),t.y=Math.sqrt(r[4]*r[4]+r[5]*r[5]+r[6]*r[6]),t.z=Math.sqrt(r[8]*r[8]+r[9]*r[9]+r[10]*r[10]),this.determinant()<=0&&(t.y*=-1),0===t.x||0===t.y||0===t.z)return i&&i.copyFromFloats(0,0,0,1),!1;if(i){var o=1/t.x,s=1/t.y,a=1/t.z;e.FromValuesToRef(r[0]*o,r[1]*o,r[2]*o,0,r[4]*s,r[5]*s,r[6]*s,0,r[8]*a,r[9]*a,r[10]*a,0,0,0,0,1,I.Matrix[0]),_.FromRotationMatrixToRef(I.Matrix[0],i)}return!0},e.prototype.getRow=function(e){if(e<0||e>3)return null;var t=4*e;return new f(this._m[t+0],this._m[t+1],this._m[t+2],this._m[t+3])},e.prototype.setRow=function(e,t){return this.setRowFromFloats(e,t.x,t.y,t.z,t.w)},e.prototype.transpose=function(){return e.Transpose(this)},e.prototype.transposeToRef=function(t){return e.TransposeToRef(this,t),this},e.prototype.setRowFromFloats=function(e,t,i,n,r){if(e<0||e>3)return this;var o=4*e;return this._m[o+0]=t,this._m[o+1]=i,this._m[o+2]=n,this._m[o+3]=r,this._markAsUpdated(),this},e.prototype.scale=function(t){var i=new e;return this.scaleToRef(t,i),i},e.prototype.scaleToRef=function(e,t){for(var i=0;i<16;i++)t._m[i]=this._m[i]*e;return t._markAsUpdated(),this},e.prototype.scaleAndAddToRef=function(e,t){for(var i=0;i<16;i++)t._m[i]+=this._m[i]*e;return t._markAsUpdated(),this},e.prototype.toNormalMatrix=function(t){var i=I.Matrix[0];this.invertToRef(i),i.transposeToRef(t);var n=t._m;e.FromValuesToRef(n[0],n[1],n[2],0,n[4],n[5],n[6],0,n[8],n[9],n[10],0,0,0,0,1,t)},e.prototype.getRotationMatrix=function(){var t=new e;return this.getRotationMatrixToRef(t),t},e.prototype.getRotationMatrixToRef=function(t){var i=I.Vector3[0];if(!this.decompose(i))return e.IdentityToRef(t),this;var n=this._m,r=1/i.x,o=1/i.y,s=1/i.z;return e.FromValuesToRef(n[0]*r,n[1]*r,n[2]*r,0,n[4]*o,n[5]*o,n[6]*o,0,n[8]*s,n[9]*s,n[10]*s,0,0,0,0,1,t),this},e.prototype.toggleModelMatrixHandInPlace=function(){var e=this._m;e[2]*=-1,e[6]*=-1,e[8]*=-1,e[9]*=-1,e[14]*=-1,this._markAsUpdated()},e.prototype.toggleProjectionMatrixHandInPlace=function(){var e=this._m;e[8]*=-1,e[9]*=-1,e[10]*=-1,e[11]*=-1,this._markAsUpdated()},e.FromArray=function(t,i){void 0===i&&(i=0);var n=new e;return e.FromArrayToRef(t,i,n),n},e.FromArrayToRef=function(e,t,i){for(var n=0;n<16;n++)i._m[n]=e[n+t];i._markAsUpdated()},e.FromFloat32ArrayToRefScaled=function(e,t,i,n){for(var r=0;r<16;r++)n._m[r]=e[r+t]*i;n._markAsUpdated()},Object.defineProperty(e,"IdentityReadOnly",{get:function(){return e._identityReadOnly},enumerable:!0,configurable:!0}),e.FromValuesToRef=function(e,t,i,n,r,o,s,a,c,l,u,h,d,f,p,_,m){var g=m._m;g[0]=e,g[1]=t,g[2]=i,g[3]=n,g[4]=r,g[5]=o,g[6]=s,g[7]=a,g[8]=c,g[9]=l,g[10]=u,g[11]=h,g[12]=d,g[13]=f,g[14]=p,g[15]=_,m._markAsUpdated()},e.FromValues=function(t,i,n,r,o,s,a,c,l,u,h,d,f,p,_,m){var g=new e,v=g._m;return v[0]=t,v[1]=i,v[2]=n,v[3]=r,v[4]=o,v[5]=s,v[6]=a,v[7]=c,v[8]=l,v[9]=u,v[10]=h,v[11]=d,v[12]=f,v[13]=p,v[14]=_,v[15]=m,g._markAsUpdated(),g},e.Compose=function(t,i,n){var r=new e;return e.ComposeToRef(t,i,n,r),r},e.ComposeToRef=function(e,t,i,n){var r=n._m,o=t.x,s=t.y,a=t.z,c=t.w,l=o+o,u=s+s,h=a+a,d=o*l,f=o*u,p=o*h,_=s*u,m=s*h,g=a*h,v=c*l,y=c*u,b=c*h,T=e.x,E=e.y,x=e.z;r[0]=(1-(_+g))*T,r[1]=(f+b)*T,r[2]=(p-y)*T,r[3]=0,r[4]=(f-b)*E,r[5]=(1-(d+g))*E,r[6]=(m+v)*E,r[7]=0,r[8]=(p+y)*x,r[9]=(m-v)*x,r[10]=(1-(d+_))*x,r[11]=0,r[12]=i.x,r[13]=i.y,r[14]=i.z,r[15]=1,n._markAsUpdated()},e.Identity=function(){var t=e.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);return t._updateIdentityStatus(!0),t},e.IdentityToRef=function(t){e.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t),t._updateIdentityStatus(!0)},e.Zero=function(){var t=e.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);return t._updateIdentityStatus(!1),t},e.RotationX=function(t){var i=new e;return e.RotationXToRef(t,i),i},e.Invert=function(t){var i=new e;return t.invertToRef(i),i},e.RotationXToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);e.FromValuesToRef(1,0,0,0,0,r,n,0,0,-n,r,0,0,0,0,1,i),i._updateIdentityStatus(1===r&&0===n)},e.RotationY=function(t){var i=new e;return e.RotationYToRef(t,i),i},e.RotationYToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);e.FromValuesToRef(r,0,-n,0,0,1,0,0,n,0,r,0,0,0,0,1,i),i._updateIdentityStatus(1===r&&0===n)},e.RotationZ=function(t){var i=new e;return e.RotationZToRef(t,i),i},e.RotationZToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);e.FromValuesToRef(r,n,0,0,-n,r,0,0,0,0,1,0,0,0,0,1,i),i._updateIdentityStatus(1===r&&0===n)},e.RotationAxis=function(t,i){var n=new e;return e.RotationAxisToRef(t,i,n),n},e.RotationAxisToRef=function(e,t,i){var n=Math.sin(-t),r=Math.cos(-t),o=1-r;e.normalize();var s=i._m;s[0]=e.x*e.x*o+r,s[1]=e.x*e.y*o-e.z*n,s[2]=e.x*e.z*o+e.y*n,s[3]=0,s[4]=e.y*e.x*o+e.z*n,s[5]=e.y*e.y*o+r,s[6]=e.y*e.z*o-e.x*n,s[7]=0,s[8]=e.z*e.x*o-e.y*n,s[9]=e.z*e.y*o+e.x*n,s[10]=e.z*e.z*o+r,s[11]=0,s[12]=0,s[13]=0,s[14]=0,s[15]=1,i._markAsUpdated()},e.RotationAlignToRef=function(e,t,i){var n=d.Cross(t,e),r=d.Dot(t,e),o=1/(1+r),s=i._m;s[0]=n.x*n.x*o+r,s[1]=n.y*n.x*o-n.z,s[2]=n.z*n.x*o+n.y,s[3]=0,s[4]=n.x*n.y*o+n.z,s[5]=n.y*n.y*o+r,s[6]=n.z*n.y*o-n.x,s[7]=0,s[8]=n.x*n.z*o-n.y,s[9]=n.y*n.z*o+n.x,s[10]=n.z*n.z*o+r,s[11]=0,s[12]=0,s[13]=0,s[14]=0,s[15]=1,i._markAsUpdated()},e.RotationYawPitchRoll=function(t,i,n){var r=new e;return e.RotationYawPitchRollToRef(t,i,n,r),r},e.RotationYawPitchRollToRef=function(e,t,i,n){_.RotationYawPitchRollToRef(e,t,i,I.Quaternion[0]),I.Quaternion[0].toRotationMatrix(n)},e.Scaling=function(t,i,n){var r=new e;return e.ScalingToRef(t,i,n,r),r},e.ScalingToRef=function(t,i,n,r){e.FromValuesToRef(t,0,0,0,0,i,0,0,0,0,n,0,0,0,0,1,r),r._updateIdentityStatus(1===t&&1===i&&1===n)},e.Translation=function(t,i,n){var r=new e;return e.TranslationToRef(t,i,n,r),r},e.TranslationToRef=function(t,i,n,r){e.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,i,n,1,r),r._updateIdentityStatus(0===t&&0===i&&0===n)},e.Lerp=function(t,i,n){var r=new e;return e.LerpToRef(t,i,n,r),r},e.LerpToRef=function(e,t,i,n){for(var r=n._m,o=e.m,s=t.m,a=0;a<16;a++)r[a]=o[a]*(1-i)+s[a]*i;n._markAsUpdated()},e.DecomposeLerp=function(t,i,n){var r=new e;return e.DecomposeLerpToRef(t,i,n,r),r},e.DecomposeLerpToRef=function(t,i,n,r){var o=I.Vector3[0],s=I.Quaternion[0],a=I.Vector3[1];t.decompose(o,s,a);var c=I.Vector3[2],l=I.Quaternion[1],u=I.Vector3[3];i.decompose(c,l,u);var h=I.Vector3[4];d.LerpToRef(o,c,n,h);var f=I.Quaternion[2];_.SlerpToRef(s,l,n,f);var p=I.Vector3[5];d.LerpToRef(a,u,n,p),e.ComposeToRef(h,f,p,r)},e.LookAtLH=function(t,i,n){var r=new e;return e.LookAtLHToRef(t,i,n,r),r},e.LookAtLHToRef=function(t,i,n,r){var o=I.Vector3[0],s=I.Vector3[1],a=I.Vector3[2];i.subtractToRef(t,a),a.normalize(),d.CrossToRef(n,a,o);var c=o.lengthSquared();0===c?o.x=1:o.normalizeFromLength(Math.sqrt(c)),d.CrossToRef(a,o,s),s.normalize();var l=-d.Dot(o,t),u=-d.Dot(s,t),h=-d.Dot(a,t);e.FromValuesToRef(o.x,s.x,a.x,0,o.y,s.y,a.y,0,o.z,s.z,a.z,0,l,u,h,1,r)},e.LookAtRH=function(t,i,n){var r=new e;return e.LookAtRHToRef(t,i,n,r),r},e.LookAtRHToRef=function(t,i,n,r){var o=I.Vector3[0],s=I.Vector3[1],a=I.Vector3[2];t.subtractToRef(i,a),a.normalize(),d.CrossToRef(n,a,o);var c=o.lengthSquared();0===c?o.x=1:o.normalizeFromLength(Math.sqrt(c)),d.CrossToRef(a,o,s),s.normalize();var l=-d.Dot(o,t),u=-d.Dot(s,t),h=-d.Dot(a,t);e.FromValuesToRef(o.x,s.x,a.x,0,o.y,s.y,a.y,0,o.z,s.z,a.z,0,l,u,h,1,r)},e.OrthoLH=function(t,i,n,r){var o=new e;return e.OrthoLHToRef(t,i,n,r,o),o},e.OrthoLHToRef=function(t,i,n,r,o){var s=2/t,a=2/i,c=2/(r-n),l=-(r+n)/(r-n);e.FromValuesToRef(s,0,0,0,0,a,0,0,0,0,c,0,0,0,l,1,o),o._updateIdentityStatus(1===s&&1===a&&1===c&&0===l)},e.OrthoOffCenterLH=function(t,i,n,r,o,s){var a=new e;return e.OrthoOffCenterLHToRef(t,i,n,r,o,s,a),a},e.OrthoOffCenterLHToRef=function(t,i,n,r,o,s,a){var c=2/(i-t),l=2/(r-n),u=2/(s-o),h=-(s+o)/(s-o),d=(t+i)/(t-i),f=(r+n)/(n-r);e.FromValuesToRef(c,0,0,0,0,l,0,0,0,0,u,0,d,f,h,1,a),a._markAsUpdated()},e.OrthoOffCenterRH=function(t,i,n,r,o,s){var a=new e;return e.OrthoOffCenterRHToRef(t,i,n,r,o,s,a),a},e.OrthoOffCenterRHToRef=function(t,i,n,r,o,s,a){e.OrthoOffCenterLHToRef(t,i,n,r,o,s,a),a._m[10]*=-1},e.PerspectiveLH=function(t,i,n,r){var o=new e,s=2*n/t,a=2*n/i,c=(r+n)/(r-n),l=-2*r*n/(r-n);return e.FromValuesToRef(s,0,0,0,0,a,0,0,0,0,c,1,0,0,l,0,o),o._updateIdentityStatus(!1),o},e.PerspectiveFovLH=function(t,i,n,r){var o=new e;return e.PerspectiveFovLHToRef(t,i,n,r,o),o},e.PerspectiveFovLHToRef=function(t,i,n,r,o,s){void 0===s&&(s=!0);var a=n,c=r,l=1/Math.tan(.5*t),u=s?l/i:l,h=s?l:l*i,d=(c+a)/(c-a),f=-2*c*a/(c-a);e.FromValuesToRef(u,0,0,0,0,h,0,0,0,0,d,1,0,0,f,0,o),o._updateIdentityStatus(!1)},e.PerspectiveFovRH=function(t,i,n,r){var o=new e;return e.PerspectiveFovRHToRef(t,i,n,r,o),o},e.PerspectiveFovRHToRef=function(t,i,n,r,o,s){void 0===s&&(s=!0);var a=n,c=r,l=1/Math.tan(.5*t),u=s?l/i:l,h=s?l:l*i,d=-(c+a)/(c-a),f=-2*c*a/(c-a);e.FromValuesToRef(u,0,0,0,0,h,0,0,0,0,d,-1,0,0,f,0,o),o._updateIdentityStatus(!1)},e.PerspectiveFovWebVRToRef=function(e,t,i,n,r){void 0===r&&(r=!1);var o=r?-1:1,s=Math.tan(e.upDegrees*Math.PI/180),a=Math.tan(e.downDegrees*Math.PI/180),c=Math.tan(e.leftDegrees*Math.PI/180),l=Math.tan(e.rightDegrees*Math.PI/180),u=2/(c+l),h=2/(s+a),d=n._m;d[0]=u,d[1]=d[2]=d[3]=d[4]=0,d[5]=h,d[6]=d[7]=0,d[8]=(c-l)*u*.5,d[9]=-(s-a)*h*.5,d[10]=-i/(t-i),d[11]=1*o,d[12]=d[13]=d[15]=0,d[14]=-2*i*t/(i-t),n._markAsUpdated()},e.GetFinalMatrix=function(t,i,n,r,o,s){var a=t.width,c=t.height,l=t.x,u=t.y,h=e.FromValues(a/2,0,0,0,0,-c/2,0,0,0,0,s-o,0,l+a/2,c/2+u,o,1),d=I.Matrix[0];return i.multiplyToRef(n,d),d.multiplyToRef(r,d),d.multiply(h)},e.GetAsMatrix2x2=function(e){var t=e.m;return new Float32Array([t[0],t[1],t[4],t[5]])},e.GetAsMatrix3x3=function(e){var t=e.m;return new Float32Array([t[0],t[1],t[2],t[4],t[5],t[6],t[8],t[9],t[10]])},e.Transpose=function(t){var i=new e;return e.TransposeToRef(t,i),i},e.TransposeToRef=function(e,t){var i=t._m,n=e.m;i[0]=n[0],i[1]=n[4],i[2]=n[8],i[3]=n[12],i[4]=n[1],i[5]=n[5],i[6]=n[9],i[7]=n[13],i[8]=n[2],i[9]=n[6],i[10]=n[10],i[11]=n[14],i[12]=n[3],i[13]=n[7],i[14]=n[11],i[15]=n[15],t._updateIdentityStatus(e._isIdentity,e._isIdentityDirty)},e.Reflection=function(t){var i=new e;return e.ReflectionToRef(t,i),i},e.ReflectionToRef=function(t,i){t.normalize();var n=t.normal.x,r=t.normal.y,o=t.normal.z,s=-2*n,a=-2*r,c=-2*o;e.FromValuesToRef(s*n+1,a*n,c*n,0,s*r,a*r+1,c*r,0,s*o,a*o,c*o+1,0,s*t.d,a*t.d,c*t.d,1,i)},e.FromXYZAxesToRef=function(t,i,n,r){e.FromValuesToRef(t.x,t.y,t.z,0,i.x,i.y,i.z,0,n.x,n.y,n.z,0,0,0,0,1,r)},e.FromQuaternionToRef=function(e,t){var i=e.x*e.x,n=e.y*e.y,r=e.z*e.z,o=e.x*e.y,s=e.z*e.w,a=e.z*e.x,c=e.y*e.w,l=e.y*e.z,u=e.x*e.w;t._m[0]=1-2*(n+r),t._m[1]=2*(o+s),t._m[2]=2*(a-c),t._m[3]=0,t._m[4]=2*(o-s),t._m[5]=1-2*(r+i),t._m[6]=2*(l+u),t._m[7]=0,t._m[8]=2*(a+c),t._m[9]=2*(l-u),t._m[10]=1-2*(n+i),t._m[11]=0,t._m[12]=0,t._m[13]=0,t._m[14]=0,t._m[15]=1,t._markAsUpdated()},e._updateFlagSeed=0,e._identityReadOnly=e.Identity(),e}(),g=function(){function e(e,t,i,n){this.normal=new d(e,t,i),this.d=n}return e.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},e.prototype.clone=function(){return new e(this.normal.x,this.normal.y,this.normal.z,this.d)},e.prototype.getClassName=function(){return"Plane"},e.prototype.getHashCode=function(){var e=this.normal.getHashCode();return e=397*e^(this.d||0)},e.prototype.normalize=function(){var e=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),t=0;return 0!==e&&(t=1/e),this.normal.x*=t,this.normal.y*=t,this.normal.z*=t,this.d*=t,this},e.prototype.transform=function(t){var i=I.Matrix[0];m.TransposeToRef(t,i);var n=i.m,r=this.normal.x,o=this.normal.y,s=this.normal.z,a=this.d;return new e(r*n[0]+o*n[1]+s*n[2]+a*n[3],r*n[4]+o*n[5]+s*n[6]+a*n[7],r*n[8]+o*n[9]+s*n[10]+a*n[11],r*n[12]+o*n[13]+s*n[14]+a*n[15])},e.prototype.dotCoordinate=function(e){return this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z+this.d},e.prototype.copyFromPoints=function(e,t,i){var n,r=t.x-e.x,o=t.y-e.y,s=t.z-e.z,a=i.x-e.x,c=i.y-e.y,l=i.z-e.z,u=o*l-s*c,h=s*a-r*l,d=r*c-o*a,f=Math.sqrt(u*u+h*h+d*d);return n=0!==f?1/f:0,this.normal.x=u*n,this.normal.y=h*n,this.normal.z=d*n,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this},e.prototype.isFrontFacingTo=function(e,t){return d.Dot(this.normal,e)<=t},e.prototype.signedDistanceTo=function(e){return d.Dot(e,this.normal)+this.d},e.FromArray=function(t){return new e(t[0],t[1],t[2],t[3])},e.FromPoints=function(t,i,n){var r=new e(0,0,0,0);return r.copyFromPoints(t,i,n),r},e.FromPositionAndNormal=function(t,i){var n=new e(0,0,0,0);return i.normalize(),n.normal=i,n.d=-(i.x*t.x+i.y*t.y+i.z*t.z),n},e.SignedDistanceToPlaneFromPositionAndNormal=function(e,t,i){var n=-(t.x*e.x+t.y*e.y+t.z*e.z);return d.Dot(i,t)+n},e}(),v=function(){function e(e,t,i,n){this.x=e,this.y=t,this.width=i,this.height=n}return e.prototype.toGlobal=function(t,i){return new e(this.x*t,this.y*i,this.width*t,this.height*i)},e.prototype.toGlobalToRef=function(e,t,i){return i.x=this.x*e,i.y=this.y*t,i.width=this.width*e,i.height=this.height*t,this},e.prototype.clone=function(){return new e(this.x,this.y,this.width,this.height)},e}(),y=function(){function e(){}return e.GetPlanes=function(t){for(var i=[],n=0;n<6;n++)i.push(new g(0,0,0,0));return e.GetPlanesToRef(t,i),i},e.GetNearPlaneToRef=function(e,t){var i=e.m;t.normal.x=i[3]+i[2],t.normal.y=i[7]+i[6],t.normal.z=i[11]+i[10],t.d=i[15]+i[14],t.normalize()},e.GetFarPlaneToRef=function(e,t){var i=e.m;t.normal.x=i[3]-i[2],t.normal.y=i[7]-i[6],t.normal.z=i[11]-i[10],t.d=i[15]-i[14],t.normalize()},e.GetLeftPlaneToRef=function(e,t){var i=e.m;t.normal.x=i[3]+i[0],t.normal.y=i[7]+i[4],t.normal.z=i[11]+i[8],t.d=i[15]+i[12],t.normalize()},e.GetRightPlaneToRef=function(e,t){var i=e.m;t.normal.x=i[3]-i[0],t.normal.y=i[7]-i[4],t.normal.z=i[11]-i[8],t.d=i[15]-i[12],t.normalize()},e.GetTopPlaneToRef=function(e,t){var i=e.m;t.normal.x=i[3]-i[1],t.normal.y=i[7]-i[5],t.normal.z=i[11]-i[9],t.d=i[15]-i[13],t.normalize()},e.GetBottomPlaneToRef=function(e,t){var i=e.m;t.normal.x=i[3]+i[1],t.normal.y=i[7]+i[5],t.normal.z=i[11]+i[9],t.d=i[15]+i[13],t.normalize()},e.GetPlanesToRef=function(t,i){e.GetNearPlaneToRef(t,i[0]),e.GetFarPlaneToRef(t,i[1]),e.GetLeftPlaneToRef(t,i[2]),e.GetRightPlaneToRef(t,i[3]),e.GetTopPlaneToRef(t,i[4]),e.GetBottomPlaneToRef(t,i[5])},e}();!function(e){e[e.LOCAL=0]="LOCAL",e[e.WORLD=1]="WORLD",e[e.BONE=2]="BONE"}(n||(n={}));var b,T=function(){function e(){}return e.X=new d(1,0,0),e.Y=new d(0,1,0),e.Z=new d(0,0,1),e}(),E=function(){function e(){}return e.Interpolate=function(e,t,i,n,r){for(var o=1-3*n+3*t,s=3*n-6*t,a=3*t,c=e,l=0;l<5;l++){var u=c*c;c-=(o*(u*c)+s*u+a*c-e)*(1/(3*o*u+2*s*c+a)),c=Math.min(1,Math.max(0,c))}return 3*Math.pow(1-c,2)*c*i+3*(1-c)*Math.pow(c,2)*r+Math.pow(c,3)},e}();!function(e){e[e.CW=0]="CW",e[e.CCW=1]="CCW"}(b||(b={}));var x=function(){function e(e){this._radians=e,this._radians<0&&(this._radians+=2*Math.PI)}return e.prototype.degrees=function(){return 180*this._radians/Math.PI},e.prototype.radians=function(){return this._radians},e.BetweenTwoPoints=function(t,i){var n=i.subtract(t);return new e(Math.atan2(n.y,n.x))},e.FromRadians=function(t){return new e(t)},e.FromDegrees=function(t){return new e(t*Math.PI/180)},e}(),A=function(){return function(e,t,i){this.startPoint=e,this.midPoint=t,this.endPoint=i;var n=Math.pow(t.x,2)+Math.pow(t.y,2),r=(Math.pow(e.x,2)+Math.pow(e.y,2)-n)/2,o=(n-Math.pow(i.x,2)-Math.pow(i.y,2))/2,s=(e.x-t.x)*(t.y-i.y)-(t.x-i.x)*(e.y-t.y);this.centerPoint=new h((r*(t.y-i.y)-o*(e.y-t.y))/s,((e.x-t.x)*o-(t.x-i.x)*r)/s),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=x.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),c=x.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),l=x.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();c-a>180&&(c-=360),c-a<-180&&(c+=360),l-c>180&&(l-=360),l-c<-180&&(l+=360),this.orientation=c-a<0?b.CW:b.CCW,this.angle=x.FromDegrees(this.orientation===b.CW?a-l:l-a)}}(),P=function(){function e(e,t){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new h(e,t))}return e.prototype.addLineTo=function(e,t){if(this.closed)return this;var i=new h(e,t),n=this._points[this._points.length-1];return this._points.push(i),this._length+=i.subtract(n).length(),this},e.prototype.addArcTo=function(e,t,i,n,r){if(void 0===r&&(r=36),this.closed)return this;var o=this._points[this._points.length-1],s=new h(e,t),a=new h(i,n),c=new A(o,s,a),l=c.angle.radians()/r;c.orientation===b.CW&&(l*=-1);for(var u=c.startAngle.radians()+l,d=0;d1)return h.Zero();for(var t=e*this.length(),i=0,n=0;n=i&&t<=a){var c=s.normalize(),l=t-i;return new h(o.x+c.x*l,o.y+c.y*l)}i=a}return h.Zero()},e.StartingAt=function(t,i){return new e(t,i)},e}(),R=function(){function e(e,t,i){void 0===t&&(t=null),this.path=e,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var n=0;nt+1;)t++,i=this._curve[e].subtract(this._curve[e-t]);return i},e.prototype._normalVector=function(e,t){var i,n,r=e.length();(0===r&&(r=1),null==t)?(n=o.a.WithinEpsilon(Math.abs(e.y)/r,1,c)?o.a.WithinEpsilon(Math.abs(e.x)/r,1,c)?o.a.WithinEpsilon(Math.abs(e.z)/r,1,c)?d.Zero():new d(0,0,1):new d(1,0,0):new d(0,-1,0),i=d.Cross(e,n)):(i=d.Cross(e,t),d.CrossToRef(i,e,i));return i.normalize(),i},e}(),S=function(){function e(e){this._length=0,this._points=e,this._length=this._computeLength(e)}return e.CreateQuadraticBezier=function(t,i,n,r){r=r>2?r:3;for(var o=new Array,s=function(e,t,i,n){return(1-e)*(1-e)*t+2*e*(1-e)*i+e*e*n},a=0;a<=r;a++)o.push(new d(s(a/r,t.x,i.x,n.x),s(a/r,t.y,i.y,n.y),s(a/r,t.z,i.z,n.z)));return new e(o)},e.CreateCubicBezier=function(t,i,n,r,o){o=o>3?o:4;for(var s=new Array,a=function(e,t,i,n,r){return(1-e)*(1-e)*(1-e)*t+3*e*(1-e)*(1-e)*i+3*e*e*(1-e)*n+e*e*e*r},c=0;c<=o;c++)s.push(new d(a(c/o,t.x,i.x,n.x,r.x),a(c/o,t.y,i.y,n.y,r.y),a(c/o,t.z,i.z,n.z,r.z)));return new e(s)},e.CreateHermiteSpline=function(t,i,n,r,o){for(var s=new Array,a=1/o,c=0;c<=o;c++)s.push(d.Hermite(t,i,n,r,c*a));return new e(s)},e.CreateCatmullRomSpline=function(t,i,n){var r=new Array,o=1/i,s=0;if(n){for(var a=t.length,c=0;c=0;a--)(r=e[a])&&(s=(o<3?r(s):o>3?r(t,i,s):r(t,i))||s);return o>3&&s&&Object.defineProperty(t,i,s),s}function a(e,t,i,n){return new(i||(i=Promise))(function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){e.done?r(e.value):new i(function(t){t(e.value)}).then(s,a)}c((n=n.apply(e,t||[])).next())})}function c(e,t){var i,n,r,o,s={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(o){return function(a){return function(o){if(i)throw new TypeError("Generator is already executing.");for(;s;)try{if(i=1,n&&(r=2&o[0]?n.return:o[0]?n.throw||((r=n.return)&&r.call(n),0):n.next)&&!(r=r.call(n,o[1])).done)return r;switch(n=0,r&&(o=[2&o[0],r.value]),o[0]){case 0:case 1:r=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(r=(r=s.trys).length>0&&r[r.length-1])&&(6===o[0]||2===o[0])){s=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]0},enumerable:!0,configurable:!0}),t.prototype.getLODLevels=function(){return this._internalMeshDataInfo._LODLevels},t.prototype._sortLODLevels=function(){this._internalMeshDataInfo._LODLevels.sort(function(e,t){return e.distancet.distance?-1:0})},t.prototype.addLODLevel=function(e,t){if(t&&t._masterMesh)return T.a.Warn("You cannot use a mesh as LOD level twice"),this;var i=new P.a(e,t);return this._internalMeshDataInfo._LODLevels.push(i),t&&(t._masterMesh=this),this._sortLODLevels(),this},t.prototype.getLODLevelAtDistance=function(e){for(var t=this._internalMeshDataInfo,i=0;ir)return this.onLODLevelSelection&&this.onLODLevelSelection(r,this,n._LODLevels[n._LODLevels.length-1].mesh),this;for(var o=0;o0;this.computeWorldMatrix();var s=this.material||r.defaultMaterial;if(s)if(s._storeEffectOnSubMeshes)for(var a=0,c=this.subMeshes;a0){var i=this.getIndices();if(!i)return null;var n=i.length,r=!1;if(e)r=!0;else for(var o=0,s=this.subMeshes;o=n){r=!0;break}if(a.verticesStart+a.verticesCount>=t){r=!0;break}}if(!r)return this.subMeshes[0]}return this.releaseSubMeshes(),new p.b(0,0,t,0,this.getTotalIndices(),this)},t.prototype.subdivide=function(e){if(!(e<1)){for(var t=this.getTotalIndices(),i=t/e|0,n=0;i%3!=0;)i++;this.releaseSubMeshes();for(var r=0;r=t);r++)p.b.CreateFromIndices(0,n,Math.min(i,t-n),this),n+=i;this.synchronizeInstances()}},t.prototype.setVerticesData=function(e,t,i,n){if(void 0===i&&(i=!1),this._geometry)this._geometry.setVerticesData(e,t,i,n);else{var r=new h.a;r.set(t,e);var o=this.getScene();new d.a(d.a.RandomId(),o,r,i,this)}return this},t.prototype.markVerticesDataAsUpdatable=function(e,t){void 0===t&&(t=!0);var i=this.getVertexBuffer(e);i&&i.isUpdatable()!==t&&this.setVerticesData(e,this.getVerticesData(e),t)},t.prototype.setVerticesBuffer=function(e){return this._geometry||(this._geometry=d.a.CreateGeometryForMesh(this)),this._geometry.setVerticesBuffer(e),this},t.prototype.updateVerticesData=function(e,t,i,n){return this._geometry?(n?(this.makeGeometryUnique(),this.updateVerticesData(e,t,i,!1)):this._geometry.updateVerticesData(e,t,i),this):this},t.prototype.updateMeshPositions=function(e,t){void 0===t&&(t=!0);var i=this.getVerticesData(u.b.PositionKind);if(!i)return this;if(e(i),this.updateVerticesData(u.b.PositionKind,i,!1,!1),t){var n=this.getIndices(),r=this.getVerticesData(u.b.NormalKind);if(!r)return this;h.a.ComputeNormals(i,n,r),this.updateVerticesData(u.b.NormalKind,r,!1,!1)}return this},t.prototype.makeGeometryUnique=function(){if(!this._geometry)return this;var e=this._geometry,t=this._geometry.copy(d.a.RandomId());return e.releaseForMesh(this,!0),t.applyToMesh(this),this},t.prototype.setIndices=function(e,t,i){if(void 0===t&&(t=null),void 0===i&&(i=!1),this._geometry)this._geometry.setIndices(e,t,i);else{var n=new h.a;n.indices=e;var r=this.getScene();new d.a(d.a.RandomId(),r,n,i,this)}return this},t.prototype.updateIndices=function(e,t,i){return void 0===i&&(i=!1),this._geometry?(this._geometry.updateIndices(e,t,i),this):this},t.prototype.toLeftHanded=function(){return this._geometry?(this._geometry.toLeftHanded(),this):this},t.prototype._bind=function(e,t,i){if(!this._geometry)return this;var n,r=this.getScene().getEngine();if(this._unIndexed)n=null;else switch(i){case m.a.PointFillMode:n=null;break;case m.a.WireFrameFillMode:n=e._getLinesIndexBuffer(this.getIndices(),r);break;default:case m.a.TriangleFillMode:n=this._geometry.getIndexBuffer()}return this._geometry._bind(t,n),this},t.prototype._draw=function(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;this._internalMeshDataInfo._onBeforeDrawObservable&&this._internalMeshDataInfo._onBeforeDrawObservable.notifyObservers(this);var n=this.getScene().getEngine();return this._unIndexed||t==m.a.PointFillMode?n.drawArraysType(t,e.verticesStart,e.verticesCount,i):t==m.a.WireFrameFillMode?n.drawElementsType(t,0,e._linesIndexCount,i):n.drawElementsType(t,e.indexStart,e.indexCount,i),this},t.prototype.registerBeforeRender=function(e){return this.onBeforeRenderObservable.add(e),this},t.prototype.unregisterBeforeRender=function(e){return this.onBeforeRenderObservable.removeCallback(e),this},t.prototype.registerAfterRender=function(e){return this.onAfterRenderObservable.add(e),this},t.prototype.unregisterAfterRender=function(e){return this.onAfterRenderObservable.removeCallback(e),this},t.prototype._getInstancesRenderList=function(e){if(this._instanceDataStorage.isFrozen&&this._instanceDataStorage.previousBatch)return this._instanceDataStorage.previousBatch;var t=this.getScene(),i=t._isInIntermediateRendering(),n=i?this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate:this._internalAbstractMeshDataInfo._onlyForInstances,r=this._instanceDataStorage.batchCache;if(r.mustReturn=!1,r.renderSelf[e]=!n&&this.isEnabled()&&this.isVisible,r.visibleInstances[e]=null,this._instanceDataStorage.visibleInstances){var o=this._instanceDataStorage.visibleInstances,s=t.getRenderId(),a=i?o.intermediateDefaultRenderId:o.defaultRenderId;r.visibleInstances[e]=o[s],!r.visibleInstances[e]&&a&&(r.visibleInstances[e]=o[a])}return r.hardwareInstancedRendering[e]=this._instanceDataStorage.hardwareInstancedRendering&&null!==r.visibleInstances[e]&&void 0!==r.visibleInstances[e],this._instanceDataStorage.previousBatch=r,r},t.prototype._renderWithInstances=function(e,t,i,n,r){var o=i.visibleInstances[e._id];if(!o)return this;for(var s=this._instanceDataStorage,a=s.instancesBufferSize,c=s.instancesBuffer,l=16*(o.length+1)*4;s.instancesBufferSizeh&&n++,0!==_&&f++,d+=_,h=_}if(c[f]++,f>o&&(o=f),0===d)r++;else{var m=1/d,g=0;for(p=0;p.001&&s++}}var v=this.skeleton.bones.length,y=this.getVerticesData(u.b.MatricesIndicesKind),b=this.getVerticesData(u.b.MatricesIndicesExtraKind),T=0;for(l=0;l=v||E<0)&&T++}return{skinned:!0,valid:0===r&&0===s&&0===T,report:"Number of Weights = "+i/4+"\nMaximum influences = "+o+"\nMissing Weights = "+r+"\nNot Sorted = "+n+"\nNot Normalized = "+s+"\nWeightCounts = ["+c+"]\nNumber of bones = "+v+"\nBad Bone Indices = "+T}},t.prototype._checkDelayState=function(){var e=this.getScene();return this._geometry?this._geometry.load(e):this.delayLoadState===y.a.DELAYLOADSTATE_NOTLOADED&&(this.delayLoadState=y.a.DELAYLOADSTATE_LOADING,this._queueLoad(e)),this},t.prototype._queueLoad=function(e){var t=this;e._addPendingData(this);var i=-1!==this.delayLoadingFile.indexOf(".babylonbinarymeshdata");return o.h.LoadFile(this.delayLoadingFile,function(i){i instanceof ArrayBuffer?t._delayLoadingFunction(i,t):t._delayLoadingFunction(JSON.parse(i),t),t.instances.forEach(function(e){e.refreshBoundingInfo(),e._syncSubMeshes()}),t.delayLoadState=y.a.DELAYLOADSTATE_LOADED,e._removePendingData(t)},function(){},e.offlineProvider,i),this},t.prototype.isInFrustum=function(t){return this.delayLoadState!==y.a.DELAYLOADSTATE_LOADING&&(!!e.prototype.isInFrustum.call(this,t)&&(this._checkDelayState(),!0))},t.prototype.setMaterialByID=function(e){var t,i=this.getScene().materials;for(t=i.length-1;t>-1;t--)if(i[t].id===e)return this.material=i[t],this;var n=this.getScene().multiMaterials;for(t=n.length-1;t>-1;t--)if(n[t].id===e)return this.material=n[t],this;return this},t.prototype.getAnimatables=function(){var e=new Array;return this.material&&e.push(this.material),this.skeleton&&e.push(this.skeleton),e},t.prototype.bakeTransformIntoVertices=function(e){if(!this.isVerticesDataPresent(u.b.PositionKind))return this;var t=this.subMeshes.splice(0);this._resetPointsArrayCache();var i,n=this.getVerticesData(u.b.PositionKind),r=new Array;for(i=0;i-1&&(r.morphTargetManager=i.getMorphTargetManagerById(e.morphTargetManagerId)),e.skeletonId>-1&&(r.skeleton=i.getLastSkeletonByID(e.skeletonId),e.numBoneInfluencers&&(r.numBoneInfluencers=e.numBoneInfluencers)),e.animations){for(var o=0;o4,h=l?this.getVerticesData(u.b.MatricesIndicesExtraKind):null,d=l?this.getVerticesData(u.b.MatricesWeightsExtraKind):null,f=e.getTransformMatrices(this),p=c.x.Zero(),_=new c.j,m=new c.j,g=0,v=0;v0&&(c.j.FromFloat32ArrayToRefScaled(f,Math.floor(16*o[g+a]),y,m),_.addToSelf(m));if(l)for(a=0;a<4;a++)(y=d[g+a])>0&&(c.j.FromFloat32ArrayToRefScaled(f,Math.floor(16*h[g+a]),y,m),_.addToSelf(m));c.x.TransformCoordinatesFromFloatsToRef(t._sourcePositions[v],t._sourcePositions[v+1],t._sourcePositions[v+2],_,p),p.toArray(n,v),c.x.TransformNormalFromFloatsToRef(t._sourceNormals[v],t._sourceNormals[v+1],t._sourceNormals[v+2],_,p),p.toArray(r,v),_.reset()}return this.updateVerticesData(u.b.PositionKind,n),this.updateVerticesData(u.b.NormalKind,r),this},t.MinMax=function(e){var t=null,i=null;return e.forEach(function(e){var n=e.getBoundingInfo().boundingBox;t&&i?(t.minimizeInPlace(n.minimumWorld),i.maximizeInPlace(n.maximumWorld)):(t=n.minimumWorld,i=n.maximumWorld)}),t&&i?{min:t,max:i}:{min:c.x.Zero(),max:c.x.Zero()}},t.Center=function(e){var i=e instanceof Array?t.MinMax(e):e;return c.x.Center(i.min,i.max)},t.MergeMeshes=function(e,i,n,r,o,s){var a;if(void 0===i&&(i=!0),!n){var c=0;for(a=0;a65536)return T.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(s){var l,u,d=null;o=!1}var f,_=new Array,m=new Array,v=null,y=new Array,b=null;for(a=0;a":i=n>r;break;case"<":i=n=":i=n>=r;break;case"==":i=n===r}return i},t}(f),v=function(){function e(){}return e.Process=function(e,t,i){var n=this;this._ProcessIncludes(e,t,function(e){var r=n._ProcessShaderConversion(e,t);i(r)})},e._ProcessPrecision=function(e,t){var i=t.shouldUseHighPrecisionShader;return-1===e.indexOf("precision highp float")?e=i?"precision highp float;\n"+e:"precision mediump float;\n"+e:i||(e=e.replace("precision highp float","precision mediump float")),e},e._ExtractOperation=function(e){var t=/defined\((.+)\)/.exec(e);if(t&&t.length)return new p(t[1].trim(),"!"===e[0]);for(var i="",n=0,r=0,o=["==",">=","<=","<",">"];r-1));r++);if(-1===n)return new p(e);var s=e.substring(0,n).trim(),a=e.substring(n+i.length).trim();return new g(s,i,a)},e._BuildSubExpression=function(e){var t=e.indexOf("||");if(-1===t){var i=e.indexOf("&&");if(i>-1){var n=new m,r=e.substring(0,i).trim(),o=e.substring(i+2).trim();return n.leftOperand=this._BuildSubExpression(r),n.rightOperand=this._BuildSubExpression(o),n}return this._ExtractOperation(e)}var s=new _;r=e.substring(0,t).trim(),o=e.substring(t+2).trim();return s.leftOperand=this._BuildSubExpression(r),s.rightOperand=this._BuildSubExpression(o),s},e._BuildExpression=function(e,t){var i=new d,n=e.substring(0,t),r=e.substring(t).trim();return i.testExpression="#ifdef"===n?new p(r):"#ifndef"===n?new p(r,!0):this._BuildSubExpression(r),i},e._MoveCursorWithinIf=function(e,t,i){for(var n=e.currentLine;this._MoveCursor(e,i);){var r=(n=e.currentLine).substring(0,5).toLowerCase();if("#else"===r){var o=new c;return t.children.push(o),void this._MoveCursor(e,o)}if("#elif"===r){var s=this._BuildExpression(n,5);t.children.push(s),i=s}}},e._MoveCursor=function(e,t){for(;e.canRead;){e.lineIndex++;var i=e.currentLine,n=/(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/.exec(i);if(n&&n.length){switch(n[0]){case"#ifdef":var r=new h;t.children.push(r);var o=this._BuildExpression(i,6);r.children.push(o),this._MoveCursorWithinIf(e,r,o);break;case"#else":case"#elif":return!0;case"#endif":return!1;case"#ifndef":r=new h;t.children.push(r);o=this._BuildExpression(i,7);r.children.push(o),this._MoveCursorWithinIf(e,r,o);break;case"#if":r=new h,o=this._BuildExpression(i,3);t.children.push(r),r.children.push(o),this._MoveCursorWithinIf(e,r,o)}}else{var s=new c;if(s.line=i,t.children.push(s),"#"===i[0]&&"d"===i[1]){var a=i.replace(";","").split(" ");s.additionalDefineKey=a[1],3===a.length&&(s.additionalDefineValue=a[2])}}}return!1},e._EvaluatePreProcessors=function(e,t,i){var n=new c,r=new l;return r.lineIndex=-1,r.lines=e.split("\n"),this._MoveCursor(r,n),n.process(t,i)},e._PreparePreProcessors=function(e){for(var t={},i=0,n=e.defines;i1?r[1]:""}return t.GL_ES="true",t.__VERSION__=e.version,t[e.platformName]="true",t},e._ProcessShaderConversion=function(e,t){var i=this._ProcessPrecision(e,t);if(!t.processor)return i;if(-1!==i.indexOf("#version 3"))return i.replace("#version 300 es","");var n=t.defines,r=this._PreparePreProcessors(t);return t.processor.preProcessor&&(i=t.processor.preProcessor(i,n,t.isFragment)),i=this._EvaluatePreProcessors(i,r,t),t.processor.postProcessor&&(i=t.processor.postProcessor(i,n,t.isFragment)),i},e._ProcessIncludes=function(e,t,i){for(var n=this,r=/#include<(.+)>(\((.*)\))*(\[(.*)\])*/g,o=r.exec(e),s=new String(e);null!=o;){var c=o[1];if(-1!==c.indexOf("__decl__")&&(c=c.replace(/__decl__/,""),t.supportsUniformBuffers&&(c=(c=c.replace(/Vertex/,"Ubo")).replace(/Fragment/,"Ubo")),c+="Declaration"),!t.includesShadersStore[c]){var l=t.shadersRepository+"ShadersInclude/"+c+".fx";return void a.h.LoadFile(l,function(e){t.includesShadersStore[c]=e,n._ProcessIncludes(s,t,i)})}var u=t.includesShadersStore[c];if(o[2])for(var h=o[3].split(","),d=0;dthis._maxRank&&(this._maxRank=e),this._defines[e]=new Array),this._defines[e].push(t)},e.prototype.addCPUSkinningFallback=function(e,t){this._mesh=t,ethis._maxRank&&(this._maxRank=e)},Object.defineProperty(e.prototype,"isMoreFallbacks",{get:function(){return this._currentRank<=this._maxRank},enumerable:!0,configurable:!0}),e.prototype.reduce=function(e,t){if(this._mesh&&this._mesh.computeBonesUsingShaders&&this._mesh.numBoneInfluencers>0&&this._mesh.material){this._mesh.computeBonesUsingShaders=!1,e=e.replace("#define NUM_BONE_INFLUENCERS "+this._mesh.numBoneInfluencers,"#define NUM_BONE_INFLUENCERS 0"),t._bonesComputationForcedToCPU=!0;for(var i=this._mesh.getScene(),n=0;n=2?"WEBGL2":"WEBGL1"};this._loadVertexShader(f,function(e){_._loadFragmentShader(p,function(i){v.Process(e,y,function(e){y.isFragment=!0,v.Process(i,y,function(i){_._useFinalCode(e,i,t)})})})})}return Object.defineProperty(e.prototype,"onBindObservable",{get:function(){return this._onBindObservable||(this._onBindObservable=new n.c),this._onBindObservable},enumerable:!0,configurable:!0}),e.prototype._useFinalCode=function(e,t,i){if(i){var n=i.vertexElement||i.vertex||i,r=i.fragmentElement||i.fragment||i;this._vertexSourceCode="#define SHADER_NAME vertex:"+n+"\n"+e,this._fragmentSourceCode="#define SHADER_NAME fragment:"+r+"\n"+t}else this._vertexSourceCode=e,this._fragmentSourceCode=t;this._prepareEffect()},Object.defineProperty(e.prototype,"key",{get:function(){return this._key},enumerable:!0,configurable:!0}),e.prototype.isReady=function(){return!!this._isReady||!!this._pipelineContext&&this._pipelineContext.isReady},e.prototype.getEngine=function(){return this._engine},e.prototype.getPipelineContext=function(){return this._pipelineContext},e.prototype.getAttributesNames=function(){return this._attributesNames},e.prototype.getAttributeLocation=function(e){return this._attributes[e]},e.prototype.getAttributeLocationByName=function(e){var t=this._attributesNames.indexOf(e);return this._attributes[t]},e.prototype.getAttributesCount=function(){return this._attributes.length},e.prototype.getUniformIndex=function(e){return this._uniformsNames.indexOf(e)},e.prototype.getUniform=function(e){return this._uniforms[e]},e.prototype.getSamplers=function(){return this._samplerList},e.prototype.getCompilationError=function(){return this._compilationError},e.prototype.executeWhenCompiled=function(e){var t=this;this.isReady()?e(this):(this.onCompileObservable.add(function(t){e(t)}),this._pipelineContext&&!this._pipelineContext.isAsync||setTimeout(function(){t._checkIsReady()},16))},e.prototype._checkIsReady=function(){var e=this;this.isReady()||setTimeout(function(){e._checkIsReady()},16)},e.prototype._loadVertexShader=function(t,i){var n;if("undefined"!=typeof HTMLElement&&t instanceof HTMLElement)return void i(o.a.GetDOMTextContent(t));"source:"!==t.substr(0,7)?"base64:"!==t.substr(0,7)?e.ShadersStore[t+"VertexShader"]?i(e.ShadersStore[t+"VertexShader"]):(n="."===t[0]||"/"===t[0]||t.indexOf("http")>-1?t:e.ShadersRepository+t,this._engine._loadFile(n+".vertex.fx",i)):i(window.atob(t.substr(7))):i(t.substr(7))},e.prototype._loadFragmentShader=function(t,i){var n;if("undefined"!=typeof HTMLElement&&t instanceof HTMLElement)return void i(o.a.GetDOMTextContent(t));"source:"!==t.substr(0,7)?"base64:"!==t.substr(0,7)?e.ShadersStore[t+"PixelShader"]?i(e.ShadersStore[t+"PixelShader"]):e.ShadersStore[t+"FragmentShader"]?i(e.ShadersStore[t+"FragmentShader"]):(n="."===t[0]||"/"===t[0]||t.indexOf("http")>-1?t:e.ShadersRepository+t,this._engine._loadFile(n+".fragment.fx",i)):i(window.atob(t.substr(7))):i(t.substr(7))},e.prototype._dumpShadersSource=function(e,t,i){var n=(this._engine.webGLVersion>1?"#version 300 es\n#define WEBGL2 \n":"")+(i?i+"\n":"");t=n+t;var r=2,o=/\n/gm,a="\n1\t"+(e=n+e).replace(o,function(){return"\n"+r+++"\t"});r=2;var c="\n1\t"+t.replace(o,function(){return"\n"+r+++"\t"});this.name.vertexElement?(s.a.Error("Vertex shader: "+this.name.vertexElement+a),s.a.Error("Fragment shader: "+this.name.fragmentElement+c)):this.name.vertex?(s.a.Error("Vertex shader: "+this.name.vertex+a),s.a.Error("Fragment shader: "+this.name.fragment+c)):(s.a.Error("Vertex shader: "+this.name+a),s.a.Error("Fragment shader: "+this.name+c))},e.prototype._rebuildProgram=function(e,t,i,n){var o=this;this._isReady=!1,this._vertexSourceCodeOverride=e,this._fragmentSourceCodeOverride=t,this.onError=function(e,t){n&&n(t)},this.onCompiled=function(){for(var e=o.getEngine().scenes,t=0;t
";e._AddLogEntry(n)},e._WarnDisabled=function(e){},e._WarnEnabled=function(t){var i=e._FormatMessage(t);console.warn("BJS - "+i);var n="
"+i+"

";e._AddLogEntry(n)},e._ErrorDisabled=function(e){},e._ErrorEnabled=function(t){e.errorsCount++;var i=e._FormatMessage(t);console.error("BJS - "+i);var n="
"+i+"

";e._AddLogEntry(n)},Object.defineProperty(e,"LogCache",{get:function(){return e._LogCache},enumerable:!0,configurable:!0}),e.ClearLogCache=function(){e._LogCache="",e.errorsCount=0},Object.defineProperty(e,"LogLevels",{set:function(t){(t&e.MessageLogLevel)===e.MessageLogLevel?e.Log=e._LogEnabled:e.Log=e._LogDisabled,(t&e.WarningLogLevel)===e.WarningLogLevel?e.Warn=e._WarnEnabled:e.Warn=e._WarnDisabled,(t&e.ErrorLogLevel)===e.ErrorLogLevel?e.Error=e._ErrorEnabled:e.Error=e._ErrorDisabled},enumerable:!0,configurable:!0}),e.NoneLogLevel=0,e.MessageLogLevel=1,e.WarningLogLevel=2,e.ErrorLogLevel=4,e.AllLogLevel=7,e._LogCache="",e.errorsCount=0,e.Log=e._LogEnabled,e.Warn=e._WarnEnabled,e.Error=e._ErrorEnabled,e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return d});var n=i(1),r=i(2),o=i(9),s=i(11),a=i(0),c=i(44),l=i(3),u=i(22),h=i(19),d=function(e){function t(i,n,r,a,c,u,h,d,f,p){void 0===r&&(r=!1),void 0===a&&(a=!0),void 0===c&&(c=t.TRILINEAR_SAMPLINGMODE),void 0===u&&(u=null),void 0===h&&(h=null),void 0===d&&(d=null),void 0===f&&(f=!1);var _=e.call(this,n)||this;if(_.url=null,_.uOffset=0,_.vOffset=0,_.uScale=1,_.vScale=1,_.uAng=0,_.vAng=0,_.wAng=0,_.uRotationCenter=.5,_.vRotationCenter=.5,_.wRotationCenter=.5,_.inspectableCustomProperties=null,_._noMipmap=!1,_._invertY=!1,_._rowGenerationMatrix=null,_._cachedTextureMatrix=null,_._projectionModeMatrix=null,_._t0=null,_._t1=null,_._t2=null,_._cachedUOffset=-1,_._cachedVOffset=-1,_._cachedUScale=0,_._cachedVScale=0,_._cachedUAng=-1,_._cachedVAng=-1,_._cachedWAng=-1,_._cachedProjectionMatrixId=-1,_._cachedCoordinatesMode=-1,_._initialSamplingMode=t.BILINEAR_SAMPLINGMODE,_._buffer=null,_._deleteBuffer=!1,_._format=null,_._delayedOnLoad=null,_._delayedOnError=null,_.onLoadObservable=new o.c,_._isBlocking=!0,_.name=i||"",_.url=i,_._noMipmap=r,_._invertY=a,_._initialSamplingMode=c,_._buffer=d,_._deleteBuffer=f,p&&(_._format=p),!(n=_.getScene()))return _;n.getEngine().onBeforeTextureInitObservable.notifyObservers(_);var m=function(){_._texture&&_._texture._invertVScale&&(_.vScale=-1),_.onLoadObservable.hasObservers()&&_.onLoadObservable.notifyObservers(_),u&&u(),!_.isBlocking&&n&&n.resetCachedMaterial()};return _.url?(_._texture=_._getFromCache(_.url,r,c,a),_._texture?_._texture.isReady?s.h.SetImmediate(function(){return m()}):_._texture.onLoadedObservable.add(m):n.useDelayedTextureLoading?(_.delayLoadState=l.a.DELAYLOADSTATE_NOTLOADED,_._delayedOnLoad=m,_._delayedOnError=h):(_._texture=n.getEngine().createTexture(_.url,r,a,n,c,m,h,_._buffer,void 0,_._format),f&&delete _._buffer),_):(_._delayedOnLoad=m,_._delayedOnError=h,_)}return n.d(t,e),Object.defineProperty(t.prototype,"noMipmap",{get:function(){return this._noMipmap},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isBlocking",{get:function(){return this._isBlocking},set:function(e){this._isBlocking=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"samplingMode",{get:function(){return this._texture?this._texture.samplingMode:this._initialSamplingMode},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"invertY",{get:function(){return this._invertY},enumerable:!0,configurable:!0}),t.prototype.updateURL=function(e,t,i){void 0===t&&(t=null),this.url&&(this.releaseInternalTexture(),this.getScene().markAllMaterialsAsDirty(l.a.MATERIAL_TextureDirtyFlag)),this.url=e,this._buffer=t,this.delayLoadState=l.a.DELAYLOADSTATE_NOTLOADED,i&&(this._delayedOnLoad=i),this.delayLoad()},t.prototype.delayLoad=function(){if(this.delayLoadState===l.a.DELAYLOADSTATE_NOTLOADED){var e=this.getScene();e&&(this.delayLoadState=l.a.DELAYLOADSTATE_LOADED,this._texture=this._getFromCache(this.url,this._noMipmap,this.samplingMode,this._invertY),this._texture?this._delayedOnLoad&&(this._texture.isReady?s.h.SetImmediate(this._delayedOnLoad):this._texture.onLoadedObservable.add(this._delayedOnLoad)):(this._texture=e.getEngine().createTexture(this.url,this._noMipmap,this._invertY,e,this.samplingMode,this._delayedOnLoad,this._delayedOnError,this._buffer,null,this._format),this._deleteBuffer&&delete this._buffer),this._delayedOnLoad=null,this._delayedOnError=null)}},t.prototype._prepareRowForTextureGeneration=function(e,t,i,n){e*=this.uScale,t*=this.vScale,e-=this.uRotationCenter*this.uScale,t-=this.vRotationCenter*this.vScale,i-=this.wRotationCenter,a.x.TransformCoordinatesFromFloatsToRef(e,t,i,this._rowGenerationMatrix,n),n.x+=this.uRotationCenter*this.uScale+this.uOffset,n.y+=this.vRotationCenter*this.vScale+this.vOffset,n.z+=this.wRotationCenter},t.prototype.getTextureMatrix=function(){var e=this;if(this.uOffset===this._cachedUOffset&&this.vOffset===this._cachedVOffset&&this.uScale===this._cachedUScale&&this.vScale===this._cachedVScale&&this.uAng===this._cachedUAng&&this.vAng===this._cachedVAng&&this.wAng===this._cachedWAng)return this._cachedTextureMatrix;this._cachedUOffset=this.uOffset,this._cachedVOffset=this.vOffset,this._cachedUScale=this.uScale,this._cachedVScale=this.vScale,this._cachedUAng=this.uAng,this._cachedVAng=this.vAng,this._cachedWAng=this.wAng,this._cachedTextureMatrix||(this._cachedTextureMatrix=a.j.Zero(),this._rowGenerationMatrix=new a.j,this._t0=a.x.Zero(),this._t1=a.x.Zero(),this._t2=a.x.Zero()),a.j.RotationYawPitchRollToRef(this.vAng,this.uAng,this.wAng,this._rowGenerationMatrix),this._prepareRowForTextureGeneration(0,0,0,this._t0),this._prepareRowForTextureGeneration(1,0,0,this._t1),this._prepareRowForTextureGeneration(0,1,0,this._t2),this._t1.subtractInPlace(this._t0),this._t2.subtractInPlace(this._t0),a.j.FromValuesToRef(this._t1.x,this._t1.y,this._t1.z,0,this._t2.x,this._t2.y,this._t2.z,0,this._t0.x,this._t0.y,this._t0.z,0,0,0,0,1,this._cachedTextureMatrix);var t=this.getScene();return t?(t.markAllMaterialsAsDirty(l.a.MATERIAL_TextureDirtyFlag,function(t){return t.hasTexture(e)}),this._cachedTextureMatrix):this._cachedTextureMatrix},t.prototype.getReflectionTextureMatrix=function(){var e=this,i=this.getScene();if(!i)return this._cachedTextureMatrix;if(this.uOffset===this._cachedUOffset&&this.vOffset===this._cachedVOffset&&this.uScale===this._cachedUScale&&this.vScale===this._cachedVScale&&this.coordinatesMode===this._cachedCoordinatesMode){if(this.coordinatesMode!==t.PROJECTION_MODE)return this._cachedTextureMatrix;if(this._cachedProjectionMatrixId===i.getProjectionMatrix().updateFlag)return this._cachedTextureMatrix}switch(this._cachedTextureMatrix||(this._cachedTextureMatrix=a.j.Zero()),this._projectionModeMatrix||(this._projectionModeMatrix=a.j.Zero()),this._cachedUOffset=this.uOffset,this._cachedVOffset=this.vOffset,this._cachedUScale=this.uScale,this._cachedVScale=this.vScale,this._cachedCoordinatesMode=this.coordinatesMode,this.coordinatesMode){case t.PLANAR_MODE:a.j.IdentityToRef(this._cachedTextureMatrix),this._cachedTextureMatrix[0]=this.uScale,this._cachedTextureMatrix[5]=this.vScale,this._cachedTextureMatrix[12]=this.uOffset,this._cachedTextureMatrix[13]=this.vOffset;break;case t.PROJECTION_MODE:a.j.FromValuesToRef(.5,0,0,0,0,-.5,0,0,0,0,0,0,.5,.5,1,1,this._projectionModeMatrix);var n=i.getProjectionMatrix();this._cachedProjectionMatrixId=n.updateFlag,n.multiplyToRef(this._projectionModeMatrix,this._cachedTextureMatrix);break;default:a.j.IdentityToRef(this._cachedTextureMatrix)}return i.markAllMaterialsAsDirty(l.a.MATERIAL_TextureDirtyFlag,function(t){return-1!==t.getActiveTextures().indexOf(e)}),this._cachedTextureMatrix},t.prototype.clone=function(){var e=this;return r.a.Clone(function(){return new t(e._texture?e._texture.url:null,e.getScene(),e._noMipmap,e._invertY,e.samplingMode,void 0,void 0,e._texture?e._texture._buffer:void 0)},this)},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return"string"==typeof this._buffer&&"data:"===this._buffer.substr(0,5)&&(t.base64String=this._buffer,t.name=t.name.replace("data:","")),t.invertY=this._invertY,t.samplingMode=this.samplingMode,t},t.prototype.getClassName=function(){return"Texture"},t.prototype.dispose=function(){e.prototype.dispose.call(this),this.onLoadObservable.clear(),this._delayedOnLoad=null,this._delayedOnError=null},t.Parse=function(e,i,n){if(e.customType){var o=s.h.Instantiate(e.customType).Parse(e,i,n);return e.samplingMode&&o.updateSamplingMode&&o._samplingMode&&o._samplingMode!==e.samplingMode&&o.updateSamplingMode(e.samplingMode),o}if(e.isCube&&!e.isRenderTarget)return t._CubeTextureParser(e,i,n);if(!e.name&&!e.isRenderTarget)return null;var c=r.a.Parse(function(){var r,o=!0;if(e.noMipmap&&(o=!1),e.mirrorPlane){var s=t._CreateMirror(e.name,e.renderTargetSize,i,o);return s._waitingRenderList=e.renderList,s.mirrorPlane=a.n.FromArray(e.mirrorPlane),s}if(e.isRenderTarget){var c=null;if(e.isCube){if(i.reflectionProbes)for(var l=0;l0},e.prototype.clear=function(){this._observers=new Array,this._onObserverAdded=null},e.prototype.clone=function(){var t=new e;return t._observers=this._observers.slice(0),t},e.prototype.hasSpecificMask=function(e){void 0===e&&(e=-1);for(var t=0,i=this._observers;t0)if(parseInt(P[P.length-1])>=A)continue}for(var R=0,S=b;R1&&(this._shaderProcessor=new E.a),this._badOS=/iPad/i.test(navigator.userAgent)||/iPhone/i.test(navigator.userAgent),this._badDesktopOS=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),console.log("Babylon.js v"+e.Version+" - "+this.description),this.enableOfflineSupport=void 0!==e.OfflineProviderFactory}}return Object.defineProperty(e,"Instances",{get:function(){return g.a.Instances},enumerable:!0,configurable:!0}),Object.defineProperty(e,"LastCreatedEngine",{get:function(){return g.a.LastCreatedEngine},enumerable:!0,configurable:!0}),Object.defineProperty(e,"LastCreatedScene",{get:function(){return g.a.LastCreatedScene},enumerable:!0,configurable:!0}),e.MarkAllMaterialsAsDirty=function(t,i){for(var n=0;n1&&!this.disableUniformBuffers},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"_shouldUseHighPrecisionShader",{get:function(){return this._caps.highPrecisionShaderSupported&&this._highPrecisionShadersAllowed},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"needPOTTextures",{get:function(){return this._webGLVersion<2||this.forcePOTTextures},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"doNotHandleContextLost",{get:function(){return this._doNotHandleContextLost},set:function(e){this._doNotHandleContextLost=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"performanceMonitor",{get:function(){return this._performanceMonitor},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"texturesSupported",{get:function(){return this._texturesSupported},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"textureFormatInUse",{get:function(){return this._textureFormatInUse},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"currentViewport",{get:function(){return this._cachedViewport},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"emptyTexture",{get:function(){return this._emptyTexture||(this._emptyTexture=this.createRawTexture(new Uint8Array(4),1,1,e.TEXTUREFORMAT_RGBA,!1,!1,e.TEXTURE_NEAREST_SAMPLINGMODE)),this._emptyTexture},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"emptyTexture3D",{get:function(){return this._emptyTexture3D||(this._emptyTexture3D=this.createRawTexture3D(new Uint8Array(4),1,1,1,e.TEXTUREFORMAT_RGBA,!1,!1,e.TEXTURE_NEAREST_SAMPLINGMODE)),this._emptyTexture3D},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"emptyCubeTexture",{get:function(){if(!this._emptyCubeTexture){var t=new Uint8Array(4),i=[t,t,t,t,t,t];this._emptyCubeTexture=this.createRawCubeTexture(i,1,e.TEXTUREFORMAT_RGBA,e.TEXTURETYPE_UNSIGNED_INT,!1,!1,e.TEXTURE_NEAREST_SAMPLINGMODE)}return this._emptyCubeTexture},enumerable:!0,configurable:!0}),e.prototype.initWebVR=function(){throw y.a.WarnImport("WebVRCamera")},e.prototype._prepareVRComponent=function(){},e.prototype._connectVREvents=function(e,t){},e.prototype._submitVRFrame=function(){},e.prototype.disableVR=function(){},e.prototype.isVRPresenting=function(){return!1},e.prototype._requestVRFrame=function(){},e.prototype._disableTouchAction=function(){this._renderingCanvas&&(this._renderingCanvas.setAttribute("touch-action","none"),this._renderingCanvas.style.touchAction="none",this._renderingCanvas.style.msTouchAction="none")},e.prototype._rebuildInternalTextures=function(){for(var e=0,t=this._internalTexturesCache.slice();e1||null!==this._gl.getExtension("OES_standard_derivatives"),this._caps.astc=this._gl.getExtension("WEBGL_compressed_texture_astc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_astc"),this._caps.s3tc=this._gl.getExtension("WEBGL_compressed_texture_s3tc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"),this._caps.pvrtc=this._gl.getExtension("WEBGL_compressed_texture_pvrtc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),this._caps.etc1=this._gl.getExtension("WEBGL_compressed_texture_etc1")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc1"),this._caps.etc2=this._gl.getExtension("WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBGL_compressed_texture_es3_0"),this._caps.textureAnisotropicFilterExtension=this._gl.getExtension("EXT_texture_filter_anisotropic")||this._gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic")||this._gl.getExtension("MOZ_EXT_texture_filter_anisotropic"),this._caps.maxAnisotropy=this._caps.textureAnisotropicFilterExtension?this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0,this._caps.uintIndices=this._webGLVersion>1||null!==this._gl.getExtension("OES_element_index_uint"),this._caps.fragmentDepthSupported=this._webGLVersion>1||null!==this._gl.getExtension("EXT_frag_depth"),this._caps.highPrecisionShaderSupported=!1,this._caps.timerQuery=this._gl.getExtension("EXT_disjoint_timer_query_webgl2")||this._gl.getExtension("EXT_disjoint_timer_query"),this._caps.timerQuery&&(1===this._webGLVersion&&(this._gl.getQuery=this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery)),this._caps.canUseTimestampForTimerQuery=this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT,this._caps.timerQuery.QUERY_COUNTER_BITS_EXT)>0),this._caps.colorBufferFloat=this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_float"),this._caps.textureFloat=!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_float")),this._caps.textureFloatLinearFiltering=!(!this._caps.textureFloat||!this._gl.getExtension("OES_texture_float_linear")),this._caps.textureFloatRender=!(!this._caps.textureFloat||!this._canRenderToFloatFramebuffer()),this._caps.textureHalfFloat=!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_half_float")),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._caps.textureHalfFloatRender=this._caps.textureHalfFloat&&this._canRenderToHalfFloatFramebuffer(),this._caps.textureLOD=!!(this._webGLVersion>1||this._gl.getExtension("EXT_shader_texture_lod")),this._caps.multiview=this._gl.getExtension("OVR_multiview2"),this._webGLVersion>1)this._caps.drawBuffersExtension=!0;else{var t=this._gl.getExtension("WEBGL_draw_buffers");if(null!==t){this._caps.drawBuffersExtension=!0,this._gl.drawBuffers=t.drawBuffersWEBGL.bind(t),this._gl.DRAW_FRAMEBUFFER=this._gl.FRAMEBUFFER;for(var i=0;i<16;i++)this._gl["COLOR_ATTACHMENT"+i+"_WEBGL"]=t["COLOR_ATTACHMENT"+i+"_WEBGL"]}else this._caps.drawBuffersExtension=!1}if(this._caps.parallelShaderCompile=this._gl.getExtension("KHR_parallel_shader_compile"),this._webGLVersion>1)this._caps.depthTextureExtension=!0;else{var n=this._gl.getExtension("WEBGL_depth_texture");null!=n&&(this._caps.depthTextureExtension=!0,this._gl.UNSIGNED_INT_24_8=n.UNSIGNED_INT_24_8_WEBGL)}if(this.disableVertexArrayObjects)this._caps.vertexArrayObject=!1;else if(this._webGLVersion>1)this._caps.vertexArrayObject=!0;else{var r=this._gl.getExtension("OES_vertex_array_object");null!=r?(this._caps.vertexArrayObject=!0,this._gl.createVertexArray=r.createVertexArrayOES.bind(r),this._gl.bindVertexArray=r.bindVertexArrayOES.bind(r),this._gl.deleteVertexArray=r.deleteVertexArrayOES.bind(r)):this._caps.vertexArrayObject=!1}if(this._webGLVersion>1)this._caps.instancedArrays=!0;else{var o=this._gl.getExtension("ANGLE_instanced_arrays");null!=o?(this._caps.instancedArrays=!0,this._gl.drawArraysInstanced=o.drawArraysInstancedANGLE.bind(o),this._gl.drawElementsInstanced=o.drawElementsInstancedANGLE.bind(o),this._gl.vertexAttribDivisor=o.vertexAttribDivisorANGLE.bind(o)):this._caps.instancedArrays=!1}if(this._caps.astc&&this.texturesSupported.push("-astc.ktx"),this._caps.s3tc&&this.texturesSupported.push("-dxt.ktx"),this._caps.pvrtc&&this.texturesSupported.push("-pvrtc.ktx"),this._caps.etc2&&this.texturesSupported.push("-etc2.ktx"),this._caps.etc1&&this.texturesSupported.push("-etc1.ktx"),this._gl.getShaderPrecisionFormat){var s=this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER,this._gl.HIGH_FLOAT),a=this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER,this._gl.HIGH_FLOAT);s&&a&&(this._caps.highPrecisionShaderSupported=0!==s.precision&&0!==a.precision)}this.setDepthBuffer(!0),this.setDepthFunctionToLessOrEqual(),this.setDepthWrite(!0),this._maxSimultaneousTextures=this._caps.maxCombinedTexturesImageUnits;for(var c=0;c=0&&this._activeRenderLoops.splice(t,1)}else this._activeRenderLoops=[]},e.prototype._renderLoop=function(){if(!this._contextWasLost){var e=!0;if(!this.renderEvenInBackground&&this._windowIsBackground&&(e=!1),e){this.beginFrame();for(var t=0;t0?this.customAnimationFrameRequester?(this.customAnimationFrameRequester.requestID=this._queueNewFrame(this.customAnimationFrameRequester.renderFunction||this._bindedRenderFunction,this.customAnimationFrameRequester),this._frameHandler=this.customAnimationFrameRequester.requestID):this.isVRPresenting()?this._requestVRFrame():this._frameHandler=this._queueNewFrame(this._bindedRenderFunction):this._renderingQueueLaunched=!1},e.prototype._queueNewFrame=function(e,t){return c.h.QueueNewFrame(e,t)},e.prototype.runRenderLoop=function(e){-1===this._activeRenderLoops.indexOf(e)&&(this._activeRenderLoops.push(e),this._renderingQueueLaunched||(this._renderingQueueLaunched=!0,this._bindedRenderFunction=this._renderLoop.bind(this),this._frameHandler=this._queueNewFrame(this._bindedRenderFunction)))},e.prototype.switchFullscreen=function(e){this.isFullscreen?this.exitFullscreen():this.enterFullscreen(e)},e.prototype.enterFullscreen=function(e){this.isFullscreen||(this._pointerLockRequested=e,this._renderingCanvas&&c.h.RequestFullscreen(this._renderingCanvas))},e.prototype.exitFullscreen=function(){this.isFullscreen&&c.h.ExitFullscreen()},e.prototype.enterPointerlock=function(){this._renderingCanvas&&c.h.RequestPointerlock(this._renderingCanvas)},e.prototype.exitPointerlock=function(){c.h.ExitPointerlock()},e.prototype.clear=function(e,t,i,n){void 0===n&&(n=!1),this.applyStates();var r=0;t&&e&&(this._gl.clearColor(e.r,e.g,e.b,void 0!==e.a?e.a:1),r|=this._gl.COLOR_BUFFER_BIT),i&&(this._gl.clearDepth(1),r|=this._gl.DEPTH_BUFFER_BIT),n&&(this._gl.clearStencil(0),r|=this._gl.STENCIL_BUFFER_BIT),this._gl.clear(r)},e.prototype.scissorClear=function(e,t,i,n,r){this.enableScissor(e,t,i,n),this.clear(r,!0,!0,!0),this.disableScissor()},e.prototype.enableScissor=function(e,t,i,n){var r=this._gl;r.enable(r.SCISSOR_TEST),r.scissor(e,t,i,n)},e.prototype.disableScissor=function(){var e=this._gl;e.disable(e.SCISSOR_TEST)},e.prototype._viewport=function(e,t,i,n){e===this._viewportCached.x&&t===this._viewportCached.y&&i===this._viewportCached.z&&n===this._viewportCached.w||(this._viewportCached.x=e,this._viewportCached.y=t,this._viewportCached.z=i,this._viewportCached.w=n,this._gl.viewport(e,t,i,n))},e.prototype.setViewport=function(e,t,i){var n=t||this.getRenderWidth(),r=i||this.getRenderHeight(),o=e.x||0,s=e.y||0;this._cachedViewport=e,this._viewport(o*n,s*r,n*e.width,r*e.height)},e.prototype.setDirectViewport=function(e,t,i,n){var r=this._cachedViewport;return this._cachedViewport=null,this._viewport(e,t,i,n),r},e.prototype.beginFrame=function(){this.onBeginFrameObservable.notifyObservers(this),this._measureFps()},e.prototype.endFrame=function(){this._badOS&&this.flushFramebuffer(),this._submitVRFrame(),this.onEndFrameObservable.notifyObservers(this)},e.prototype.resize=function(){if(!this.isVRPresenting()){var e=this._renderingCanvas?this._renderingCanvas.clientWidth:window.innerWidth,t=this._renderingCanvas?this._renderingCanvas.clientHeight:window.innerHeight;this.setSize(e/this._hardwareScalingLevel,t/this._hardwareScalingLevel)}},e.prototype.setSize=function(e,t){if(this._renderingCanvas&&(this._renderingCanvas.width!==e||this._renderingCanvas.height!==t)){this._renderingCanvas.width=e,this._renderingCanvas.height=t;for(var i=0;i65535)return new Uint32Array(e);return new Uint16Array(e)}return new Uint16Array(e)},e.prototype.bindArrayBuffer=function(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.bindBuffer(e,this._gl.ARRAY_BUFFER)},e.prototype.bindUniformBuffer=function(e){this._gl.bindBuffer(this._gl.UNIFORM_BUFFER,e?e.underlyingResource:null)},e.prototype.bindUniformBufferBase=function(e,t){this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER,t,e?e.underlyingResource:null)},e.prototype.bindUniformBlock=function(e,t,i){var n=e.program,r=this._gl.getUniformBlockIndex(n,t);this._gl.uniformBlockBinding(n,r,i)},e.prototype.bindIndexBuffer=function(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.bindBuffer(e,this._gl.ELEMENT_ARRAY_BUFFER)},e.prototype.bindBuffer=function(e,t){(this._vaoRecordInProgress||this._currentBoundBuffer[t]!==e)&&(this._gl.bindBuffer(t,e?e.underlyingResource:null),this._currentBoundBuffer[t]=e)},e.prototype.updateArrayBuffer=function(e){this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,e)},e.prototype._vertexAttribPointer=function(e,t,i,n,r,o,s){var a=this._currentBufferPointers[t],c=!1;a.active?(a.buffer!==e&&(a.buffer=e,c=!0),a.size!==i&&(a.size=i,c=!0),a.type!==n&&(a.type=n,c=!0),a.normalized!==r&&(a.normalized=r,c=!0),a.stride!==o&&(a.stride=o,c=!0),a.offset!==s&&(a.offset=s,c=!0)):(c=!0,a.active=!0,a.index=t,a.size=i,a.type=n,a.normalized=r,a.stride=o,a.offset=s,a.buffer=e),(c||this._vaoRecordInProgress)&&(this.bindArrayBuffer(e),this._gl.vertexAttribPointer(t,i,n,r,o,s))},e.prototype._bindIndexBufferWithCache=function(e){null!=e&&this._cachedIndexBuffer!==e&&(this._cachedIndexBuffer=e,this.bindIndexBuffer(e),this._uintIndicesCurrentlySet=e.is32Bits)},e.prototype._bindVertexBuffersAttributes=function(e,t){var i=t.getAttributesNames();this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.unbindAllAttributes();for(var n=0;n=0){var o=e[i[n]];if(!o)continue;this._gl.enableVertexAttribArray(r),this._vaoRecordInProgress||(this._vertexAttribArraysEnabled[r]=!0);var s=o.getBuffer();s&&(this._vertexAttribPointer(s,r,o.getSize(),o.type,o.normalized,o.byteStride,o.byteOffset),o.getIsInstanced()&&(this._gl.vertexAttribDivisor(r,o.getInstanceDivisor()),this._vaoRecordInProgress||(this._currentInstanceLocations.push(r),this._currentInstanceBuffers.push(s))))}}},e.prototype.recordVertexArrayObject=function(e,t,i){var n=this._gl.createVertexArray();return this._vaoRecordInProgress=!0,this._gl.bindVertexArray(n),this._mustWipeVertexAttributes=!0,this._bindVertexBuffersAttributes(e,i),this.bindIndexBuffer(t),this._vaoRecordInProgress=!1,this._gl.bindVertexArray(null),n},e.prototype.bindVertexArrayObject=function(e,t){this._cachedVertexArrayObject!==e&&(this._cachedVertexArrayObject=e,this._gl.bindVertexArray(e),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._uintIndicesCurrentlySet=null!=t&&t.is32Bits,this._mustWipeVertexAttributes=!0)},e.prototype.bindBuffersDirectly=function(e,t,i,n,r){if(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==r){this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=r;var o=r.getAttributesCount();this._unbindVertexArrayObject(),this.unbindAllAttributes();for(var s=0,a=0;a=0&&(this._gl.enableVertexAttribArray(c),this._vertexAttribArraysEnabled[c]=!0,this._vertexAttribPointer(e,c,i[a],this._gl.FLOAT,!1,n,s)),s+=4*i[a]}}this._bindIndexBufferWithCache(t)},e.prototype._unbindVertexArrayObject=function(){this._cachedVertexArrayObject&&(this._cachedVertexArrayObject=null,this._gl.bindVertexArray(null))},e.prototype.bindBuffers=function(e,t,i){this._cachedVertexBuffers===e&&this._cachedEffectForVertexBuffers===i||(this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=i,this._bindVertexBuffersAttributes(e,i)),this._bindIndexBufferWithCache(t)},e.prototype.unbindInstanceAttributes=function(){for(var e,t=0,i=this._currentInstanceLocations.length;t1?"#version 300 es\n#define WEBGL2 \n":"",a=this._compileShader(t,"vertex",n,s),c=this._compileShader(i,"fragment",n,s),l=this._createShaderProgram(e,a,c,r,o);return this.onAfterShaderCompilationObservable.notifyObservers(this),l},e.prototype.createPipelineContext=function(){var e=new b.a;return e.engine=this,this._caps.parallelShaderCompile&&(e.isParallelCompiled=!0),e},e.prototype._createShaderProgram=function(e,t,i,n,r){void 0===r&&(r=null);var o=n.createProgram();if(e.program=o,!o)throw new Error("Unable to create program");if(n.attachShader(o,t),n.attachShader(o,i),this.webGLVersion>1&&r){var s=this.createTransformFeedback();this.bindTransformFeedback(s),this.setTranformFeedbackVaryings(o,r),e.transformFeedback=s}return n.linkProgram(o),this.webGLVersion>1&&r&&this.bindTransformFeedback(null),e.context=n,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||this._finalizePipelineContext(e),o},e.prototype._finalizePipelineContext=function(e){var t=e.context,i=e.vertexShader,n=e.fragmentShader,r=e.program;if(!t.getProgramParameter(r,t.LINK_STATUS)){var o,s;if(!this._gl.getShaderParameter(i,this._gl.COMPILE_STATUS))if(o=this._gl.getShaderInfoLog(i))throw new Error(o);if(!this._gl.getShaderParameter(n,this._gl.COMPILE_STATUS))if(o=this._gl.getShaderInfoLog(n))throw new Error(o);if(s=t.getProgramInfoLog(r))throw new Error(s)}if(this.validateShaderPrograms&&(t.validateProgram(r),!t.getProgramParameter(r,t.VALIDATE_STATUS)&&(s=t.getProgramInfoLog(r))))throw new Error(s);t.deleteShader(i),t.deleteShader(n),e.vertexShader=void 0,e.fragmentShader=void 0,e.onCompiled&&(e.onCompiled(),e.onCompiled=void 0)},e.prototype._preparePipelineContext=function(e,t,i,n,r,o,s){var a=e;a.program=n?this.createRawShaderProgram(a,t,i,void 0,s):this.createShaderProgram(a,t,i,o,void 0,s),a.program.__SPECTOR_rebuildProgram=r},e.prototype._isRenderingStateCompiled=function(e){var t=e;return!!this._gl.getProgramParameter(t.program,this._caps.parallelShaderCompile.COMPLETION_STATUS_KHR)&&(this._finalizePipelineContext(t),!0)},e.prototype._executeWhenRenderingStateIsCompiled=function(e,t){var i=e;i.isParallelCompiled?i.onCompiled=t:t()},e.prototype.getUniforms=function(e,t){for(var i=new Array,n=e,r=0;r-1?m.substring(T).toLowerCase():""),x=null,A=0,P=e._TextureLoaders;Al||t.height>l||null===e._RescalePostProcessFactory)return _._prepareWorkingCanvas(),!(!_._workingCanvas||!_._workingContext)&&(_._workingCanvas.width=i,_._workingCanvas.height=n,_._workingContext.drawImage(t,0,0,t.width,t.height,0,0,i,n),s.texImage2D(s.TEXTURE_2D,0,c,c,s.UNSIGNED_BYTE,_._workingCanvas),b.width=i,b.height=n,!1);var u=new d.a(_,d.a.DATASOURCE_TEMP);return _._bindTextureDirectly(s.TEXTURE_2D,u,!0),s.texImage2D(s.TEXTURE_2D,0,c,c,s.UNSIGNED_BYTE,t),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),_._rescaleTexture(u,b,r,c,function(){_._releaseTexture(u),_._bindTextureDirectly(s.TEXTURE_2D,b,!0),o()}),!0},o)};!g||y?l instanceof HTMLImageElement?O(l):c.h.LoadImage(m,O,C,r?r.offlineProvider:null):"string"==typeof l||l instanceof ArrayBuffer||l instanceof Blob?c.h.LoadImage(l,O,C,r?r.offlineProvider:null):O(l)}return b},e.prototype._rescaleTexture=function(t,i,n,r,o){var s=this,a=this.createRenderTargetTexture({width:i.width,height:i.height},{generateMipMaps:!1,type:e.TEXTURETYPE_UNSIGNED_INT,samplingMode:e.TEXTURE_BILINEAR_SAMPLINGMODE,generateDepthBuffer:!1,generateStencilBuffer:!1});!this._rescalePostProcess&&e._RescalePostProcessFactory&&(this._rescalePostProcess=e._RescalePostProcessFactory(this)),this._rescalePostProcess.getEffect().executeWhenCompiled(function(){s._rescalePostProcess.onApply=function(e){e._bindTexture("textureSampler",t)};var e=n;e||(e=s.scenes[s.scenes.length-1]),e.postProcessManager.directRender([s._rescalePostProcess],a,!0),s._bindTextureDirectly(s._gl.TEXTURE_2D,i,!0),s._gl.copyTexImage2D(s._gl.TEXTURE_2D,0,r,0,0,i.width,i.height,0),s.unBindFramebuffer(a),s._releaseTexture(a),o&&o()})},e.prototype.createRawTexture=function(t,i,n,r,o,s,a,c,l){throw void 0===c&&(c=null),void 0===l&&(l=e.TEXTURETYPE_UNSIGNED_INT),y.a.WarnImport("Engine.RawTexture")},e.prototype._unpackFlipY=function(e){this._unpackFlipYCached!==e&&(this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,e?1:0),this.enableUnpackFlipYCached&&(this._unpackFlipYCached=e))},e.prototype._getUnpackAlignement=function(){return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT)},e.prototype.createDynamicTexture=function(e,t,i,n){var r=new d.a(this,d.a.DATASOURCE_DYNAMIC);return r.baseWidth=e,r.baseHeight=t,i&&(e=this.needPOTTextures?c.h.GetExponentOfTwo(e,this._caps.maxTextureSize):e,t=this.needPOTTextures?c.h.GetExponentOfTwo(t,this._caps.maxTextureSize):t),r.width=e,r.height=t,r.isReady=!1,r.generateMipMaps=i,r.samplingMode=n,this.updateTextureSamplingMode(n,r),this._internalTexturesCache.push(r),r},e.prototype.updateTextureSamplingMode=function(e,t){var i=this._getSamplingParameters(e,t.generateMipMaps);t.isCube?(this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP,this._gl.TEXTURE_MAG_FILTER,i.mag,t),this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP,this._gl.TEXTURE_MIN_FILTER,i.min),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)):t.is3D?(this._setTextureParameterInteger(this._gl.TEXTURE_3D,this._gl.TEXTURE_MAG_FILTER,i.mag,t),this._setTextureParameterInteger(this._gl.TEXTURE_3D,this._gl.TEXTURE_MIN_FILTER,i.min),this._bindTextureDirectly(this._gl.TEXTURE_3D,null)):(this._setTextureParameterInteger(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,i.mag,t),this._setTextureParameterInteger(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,i.min),this._bindTextureDirectly(this._gl.TEXTURE_2D,null)),t.samplingMode=e},e.prototype.updateDynamicTexture=function(e,t,i,n,r,o){if(void 0===n&&(n=!1),void 0===o&&(o=!1),e){this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0,o),this._unpackFlipY(i),n&&this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1);var s=r?this._getInternalFormat(r):this._gl.RGBA;this._gl.texImage2D(this._gl.TEXTURE_2D,0,s,s,this._gl.UNSIGNED_BYTE,t),e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),n&&this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.isReady=!0}},e.prototype.updateVideoTexture=function(e,t,i){if(e&&!e._isDisabled){var n=this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0);this._unpackFlipY(!i);try{if(void 0===this._videoTextureSupported&&(this._gl.texImage2D(this._gl.TEXTURE_2D,0,this._gl.RGBA,this._gl.RGBA,this._gl.UNSIGNED_BYTE,t),0!==this._gl.getError()?this._videoTextureSupported=!1:this._videoTextureSupported=!0),this._videoTextureSupported)this._gl.texImage2D(this._gl.TEXTURE_2D,0,this._gl.RGBA,this._gl.RGBA,this._gl.UNSIGNED_BYTE,t);else{if(!e._workingCanvas){e._workingCanvas=document.createElement("canvas");var r=e._workingCanvas.getContext("2d");if(!r)throw new Error("Unable to get 2d context");e._workingContext=r,e._workingCanvas.width=e.width,e._workingCanvas.height=e.height}e._workingContext.drawImage(t,0,0,t.videoWidth,t.videoHeight,0,0,e.width,e.height),this._gl.texImage2D(this._gl.TEXTURE_2D,0,this._gl.RGBA,this._gl.RGBA,this._gl.UNSIGNED_BYTE,e._workingCanvas)}e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),n||this._bindTextureDirectly(this._gl.TEXTURE_2D,null),e.isReady=!0}catch(t){e._isDisabled=!0}}},e.prototype.updateTextureComparisonFunction=function(t,i){if(1!==this.webGLVersion){var n=this._gl;t.isCube?(this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,t,!0),0===i?(n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_COMPARE_FUNC,e.LEQUAL),n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_COMPARE_MODE,n.NONE)):(n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_COMPARE_FUNC,i),n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_COMPARE_MODE,n.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)):(this._bindTextureDirectly(this._gl.TEXTURE_2D,t,!0),0===i?(n.texParameteri(n.TEXTURE_2D,n.TEXTURE_COMPARE_FUNC,e.LEQUAL),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_COMPARE_MODE,n.NONE)):(n.texParameteri(n.TEXTURE_2D,n.TEXTURE_COMPARE_FUNC,i),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_COMPARE_MODE,n.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_2D,null)),t._comparisonFunction=i}else m.a.Error("WebGL 1 does not support texture comparison.")},e.prototype._setupDepthStencilTexture=function(t,i,n,r,o){var s=i.width||i,a=i.height||i;t.baseWidth=s,t.baseHeight=a,t.width=s,t.height=a,t.isReady=!0,t.samples=1,t.generateMipMaps=!1,t._generateDepthBuffer=!0,t._generateStencilBuffer=n,t.samplingMode=r?e.TEXTURE_BILINEAR_SAMPLINGMODE:e.TEXTURE_NEAREST_SAMPLINGMODE,t.type=e.TEXTURETYPE_UNSIGNED_INT,t._comparisonFunction=o;var c=this._gl,l=t.isCube?c.TEXTURE_CUBE_MAP:c.TEXTURE_2D,u=this._getSamplingParameters(t.samplingMode,!1);c.texParameteri(l,c.TEXTURE_MAG_FILTER,u.mag),c.texParameteri(l,c.TEXTURE_MIN_FILTER,u.min),c.texParameteri(l,c.TEXTURE_WRAP_S,c.CLAMP_TO_EDGE),c.texParameteri(l,c.TEXTURE_WRAP_T,c.CLAMP_TO_EDGE),0===o?(c.texParameteri(l,c.TEXTURE_COMPARE_FUNC,e.LEQUAL),c.texParameteri(l,c.TEXTURE_COMPARE_MODE,c.NONE)):(c.texParameteri(l,c.TEXTURE_COMPARE_FUNC,o),c.texParameteri(l,c.TEXTURE_COMPARE_MODE,c.COMPARE_REF_TO_TEXTURE))},e.prototype.createDepthStencilTexture=function(e,t){if(t.isCube){var i=e.width||e;return this._createDepthStencilCubeTexture(i,t)}return this._createDepthStencilTexture(e,t)},e.prototype._createDepthStencilTexture=function(e,t){var i=new d.a(this,d.a.DATASOURCE_DEPTHTEXTURE);if(!this._caps.depthTextureExtension)return m.a.Error("Depth texture is not supported by your browser or hardware."),i;var r=n.a({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1},t),o=this._gl;return this._bindTextureDirectly(o.TEXTURE_2D,i,!0),this._setupDepthStencilTexture(i,e,r.generateStencil,r.bilinearFiltering,r.comparisonFunction),this.webGLVersion>1?r.generateStencil?o.texImage2D(o.TEXTURE_2D,0,o.DEPTH24_STENCIL8,i.width,i.height,0,o.DEPTH_STENCIL,o.UNSIGNED_INT_24_8,null):o.texImage2D(o.TEXTURE_2D,0,o.DEPTH_COMPONENT24,i.width,i.height,0,o.DEPTH_COMPONENT,o.UNSIGNED_INT,null):r.generateStencil?o.texImage2D(o.TEXTURE_2D,0,o.DEPTH_STENCIL,i.width,i.height,0,o.DEPTH_STENCIL,o.UNSIGNED_INT_24_8,null):o.texImage2D(o.TEXTURE_2D,0,o.DEPTH_COMPONENT,i.width,i.height,0,o.DEPTH_COMPONENT,o.UNSIGNED_INT,null),this._bindTextureDirectly(o.TEXTURE_2D,null),i},e.prototype.setFrameBufferDepthStencilTexture=function(e){var t=e.getInternalTexture();if(t&&t._framebuffer&&e.depthStencilTexture){var i=this._gl,n=e.depthStencilTexture;this._bindUnboundFramebuffer(t._framebuffer),n.isCube?n._generateStencilBuffer?i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,i.TEXTURE_CUBE_MAP_POSITIVE_X,n._webGLTexture,0):i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.TEXTURE_CUBE_MAP_POSITIVE_X,n._webGLTexture,0):n._generateStencilBuffer?i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,i.TEXTURE_2D,n._webGLTexture,0):i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.TEXTURE_2D,n._webGLTexture,0),this._bindUnboundFramebuffer(null)}},e.prototype.createRenderTargetTexture=function(t,i){var n=new v.a;void 0!==i&&"object"==typeof i?(n.generateMipMaps=i.generateMipMaps,n.generateDepthBuffer=void 0===i.generateDepthBuffer||i.generateDepthBuffer,n.generateStencilBuffer=n.generateDepthBuffer&&i.generateStencilBuffer,n.type=void 0===i.type?e.TEXTURETYPE_UNSIGNED_INT:i.type,n.samplingMode=void 0===i.samplingMode?e.TEXTURE_TRILINEAR_SAMPLINGMODE:i.samplingMode,n.format=void 0===i.format?e.TEXTUREFORMAT_RGBA:i.format):(n.generateMipMaps=i,n.generateDepthBuffer=!0,n.generateStencilBuffer=!1,n.type=e.TEXTURETYPE_UNSIGNED_INT,n.samplingMode=e.TEXTURE_TRILINEAR_SAMPLINGMODE,n.format=e.TEXTUREFORMAT_RGBA),(n.type!==e.TEXTURETYPE_FLOAT||this._caps.textureFloatLinearFiltering)&&(n.type!==e.TEXTURETYPE_HALF_FLOAT||this._caps.textureHalfFloatLinearFiltering)||(n.samplingMode=e.TEXTURE_NEAREST_SAMPLINGMODE);var r=this._gl,o=new d.a(this,d.a.DATASOURCE_RENDERTARGET);this._bindTextureDirectly(r.TEXTURE_2D,o,!0);var s=t.width||t,a=t.height||t,c=this._getSamplingParameters(n.samplingMode,!!n.generateMipMaps);n.type!==e.TEXTURETYPE_FLOAT||this._caps.textureFloat||(n.type=e.TEXTURETYPE_UNSIGNED_INT,m.a.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type")),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,c.mag),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,c.min),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.texImage2D(r.TEXTURE_2D,0,this._getRGBABufferInternalSizedFormat(n.type,n.format),s,a,0,this._getInternalFormat(n.format),this._getWebGLTextureType(n.type),null);var l=this._currentFramebuffer,u=r.createFramebuffer();return this._bindUnboundFramebuffer(u),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,o._webGLTexture,0),o._depthStencilBuffer=this._setupFramebufferDepthAttachments(!!n.generateStencilBuffer,n.generateDepthBuffer,s,a),n.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(r.TEXTURE_2D,null),r.bindRenderbuffer(r.RENDERBUFFER,null),this._bindUnboundFramebuffer(l),o._framebuffer=u,o.baseWidth=s,o.baseHeight=a,o.width=s,o.height=a,o.isReady=!0,o.samples=1,o.generateMipMaps=!!n.generateMipMaps,o.samplingMode=n.samplingMode,o.type=n.type,o.format=n.format,o._generateDepthBuffer=n.generateDepthBuffer,o._generateStencilBuffer=!!n.generateStencilBuffer,this._internalTexturesCache.push(o),o},e.prototype._setupFramebufferDepthAttachments=function(e,t,i,n,r){void 0===r&&(r=1);var o=null,s=this._gl;return e?(o=s.createRenderbuffer(),s.bindRenderbuffer(s.RENDERBUFFER,o),r>1?s.renderbufferStorageMultisample(s.RENDERBUFFER,r,s.DEPTH24_STENCIL8,i,n):s.renderbufferStorage(s.RENDERBUFFER,s.DEPTH_STENCIL,i,n),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_STENCIL_ATTACHMENT,s.RENDERBUFFER,o)):t&&(o=s.createRenderbuffer(),s.bindRenderbuffer(s.RENDERBUFFER,o),r>1?s.renderbufferStorageMultisample(s.RENDERBUFFER,r,s.DEPTH_COMPONENT16,i,n):s.renderbufferStorage(s.RENDERBUFFER,s.DEPTH_COMPONENT16,i,n),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.RENDERBUFFER,o)),o},e.prototype.updateRenderTargetTextureSampleCount=function(e,t){if(this.webGLVersion<2||!e)return 1;if(e.samples===t)return t;var i=this._gl;if(t=Math.min(t,i.getParameter(i.MAX_SAMPLES)),e._depthStencilBuffer&&(i.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=null),e._MSAAFramebuffer&&(i.deleteFramebuffer(e._MSAAFramebuffer),e._MSAAFramebuffer=null),e._MSAARenderBuffer&&(i.deleteRenderbuffer(e._MSAARenderBuffer),e._MSAARenderBuffer=null),t>1){var n=i.createFramebuffer();if(!n)throw new Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=n,this._bindUnboundFramebuffer(e._MSAAFramebuffer);var r=i.createRenderbuffer();if(!r)throw new Error("Unable to create multi sampled framebuffer");i.bindRenderbuffer(i.RENDERBUFFER,r),i.renderbufferStorageMultisample(i.RENDERBUFFER,t,this._getRGBAMultiSampleBufferFormat(e.type),e.width,e.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.RENDERBUFFER,r),e._MSAARenderBuffer=r}else this._bindUnboundFramebuffer(e._framebuffer);return e.samples=t,e._depthStencilBuffer=this._setupFramebufferDepthAttachments(e._generateStencilBuffer,e._generateDepthBuffer,e.width,e.height,t),i.bindRenderbuffer(i.RENDERBUFFER,null),this._bindUnboundFramebuffer(null),t},e.prototype._uploadCompressedDataToTextureDirectly=function(e,t,i,n,r,o,s){void 0===o&&(o=0),void 0===s&&(s=0);var a=this._gl,c=a.TEXTURE_2D;e.isCube&&(c=a.TEXTURE_CUBE_MAP_POSITIVE_X+o),this._gl.compressedTexImage2D(c,s,t,i,n,0,r)},e.prototype._uploadDataToTextureDirectly=function(e,t,i,n){void 0===i&&(i=0),void 0===n&&(n=0);var r=this._gl,o=this._getWebGLTextureType(e.type),s=this._getInternalFormat(e.format),a=this._getRGBABufferInternalSizedFormat(e.type,s);this._unpackFlipY(e.invertY);var c=r.TEXTURE_2D;e.isCube&&(c=r.TEXTURE_CUBE_MAP_POSITIVE_X+i);var l=Math.round(u.a.Log2(e.width)),h=Math.round(u.a.Log2(e.height)),d=Math.pow(2,Math.max(l-n,0)),f=Math.pow(2,Math.max(h-n,0));r.texImage2D(c,n,a,d,f,0,s,o,t)},e.prototype._uploadArrayBufferViewToTexture=function(e,t,i,n){void 0===i&&(i=0),void 0===n&&(n=0);var r=this._gl,o=e.isCube?r.TEXTURE_CUBE_MAP:r.TEXTURE_2D;this._bindTextureDirectly(o,e,!0),this._uploadDataToTextureDirectly(e,t,i,n),this._bindTextureDirectly(o,null,!0)},e.prototype._uploadImageToTexture=function(e,t,i,n){void 0===i&&(i=0),void 0===n&&(n=0);var r=this._gl,o=this._getWebGLTextureType(e.type),s=this._getInternalFormat(e.format),a=this._getRGBABufferInternalSizedFormat(e.type,s),c=e.isCube?r.TEXTURE_CUBE_MAP:r.TEXTURE_2D;this._bindTextureDirectly(c,e,!0),this._unpackFlipY(e.invertY);var l=r.TEXTURE_2D;e.isCube&&(l=r.TEXTURE_CUBE_MAP_POSITIVE_X+i),r.texImage2D(l,n,a,s,o,t),this._bindTextureDirectly(c,null,!0)},e.prototype._setCubeMapTextureParams=function(e){var t=this._gl;t.texParameteri(t.TEXTURE_CUBE_MAP,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_CUBE_MAP,t.TEXTURE_MIN_FILTER,e?t.LINEAR_MIPMAP_LINEAR:t.LINEAR),t.texParameteri(t.TEXTURE_CUBE_MAP,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_CUBE_MAP,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),this._bindTextureDirectly(t.TEXTURE_CUBE_MAP,null)},e.prototype.createRawCubeTexture=function(e,t,i,n,r,o,s,a){throw void 0===a&&(a=null),y.a.WarnImport("Engine.RawTexture")},e.prototype.createRawTexture3D=function(t,i,n,r,o,s,a,c,l,u){throw void 0===l&&(l=null),void 0===u&&(u=e.TEXTURETYPE_UNSIGNED_INT),y.a.WarnImport("Engine.RawTexture")},e.prototype._prepareWebGLTextureContinuation=function(e,t,i,n,r){var o=this._gl;if(o){var s=this._getSamplingParameters(r,!i);o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,s.mag),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,s.min),i||n||o.generateMipmap(o.TEXTURE_2D),this._bindTextureDirectly(o.TEXTURE_2D,null),t&&t._removePendingData(e),e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}},e.prototype._prepareWebGLTexture=function(t,i,n,r,o,s,a,l,u){var h=this;void 0===u&&(u=e.TEXTURE_TRILINEAR_SAMPLINGMODE);var d=this.getCaps().maxTextureSize,f=Math.min(d,this.needPOTTextures?c.h.GetExponentOfTwo(n,d):n),p=Math.min(d,this.needPOTTextures?c.h.GetExponentOfTwo(r,d):r),_=this._gl;_&&(t._webGLTexture?(this._bindTextureDirectly(_.TEXTURE_2D,t,!0),this._unpackFlipY(void 0===o||!!o),t.baseWidth=n,t.baseHeight=r,t.width=f,t.height=p,t.isReady=!0,l(f,p,function(){h._prepareWebGLTextureContinuation(t,i,s,a,u)})||this._prepareWebGLTextureContinuation(t,i,s,a,u)):i&&i._removePendingData(t))},e.prototype._convertRGBtoRGBATextureData=function(t,i,n,r){var o;o=r===e.TEXTURETYPE_FLOAT?new Float32Array(i*n*4):new Uint32Array(i*n*4);for(var s=0;s-1;return i&&o&&(this._activeChannel=t._associatedChannel),this._boundTexturesCache[this._activeChannel]!==t||n?(this._activateCurrentTexture(),t&&t.isMultiview?this._gl.bindTexture(e,t?t._colorTextureArray:null):this._gl.bindTexture(e,t?t._webGLTexture:null),this._boundTexturesCache[this._activeChannel]=t,t&&(t._associatedChannel=this._activeChannel)):i&&(r=!0,this._activateCurrentTexture()),o&&!i&&this._bindSamplerUniformToChannel(t._associatedChannel,this._activeChannel),r},e.prototype._bindTexture=function(e,t){void 0!==e&&(t&&(t._associatedChannel=e),this._activeChannel=e,this._bindTextureDirectly(this._gl.TEXTURE_2D,t))},e.prototype.setTextureFromPostProcess=function(e,t){this._bindTexture(e,t?t._textures.data[t._currentRenderTextureInd]:null)},e.prototype.setTextureFromPostProcessOutput=function(e,t){this._bindTexture(e,t?t._outputTexture:null)},e.prototype.unbindAllTextures=function(){for(var e=0;e1&&this._bindTextureDirectly(this._gl.TEXTURE_3D,null)},e.prototype.setTexture=function(e,t,i){void 0!==e&&(t&&(this._boundUniforms[e]=t),this._setTexture(e,i))},e.prototype.setDepthStencilTexture=function(e,t,i){void 0!==e&&(t&&(this._boundUniforms[e]=t),i&&i.depthStencilTexture?this._setTexture(e,i,!1,!0):this._setTexture(e,null))},e.prototype._bindSamplerUniformToChannel=function(e,t){var i=this._boundUniforms[e];i._currentState!==t&&(this._gl.uniform1i(i,t),i._currentState=t)},e.prototype._getTextureWrapMode=function(t){switch(t){case e.TEXTURE_WRAP_ADDRESSMODE:return this._gl.REPEAT;case e.TEXTURE_CLAMP_ADDRESSMODE:return this._gl.CLAMP_TO_EDGE;case e.TEXTURE_MIRROR_ADDRESSMODE:return this._gl.MIRRORED_REPEAT}return this._gl.REPEAT},e.prototype._setTexture=function(t,i,n,r){if(void 0===n&&(n=!1),void 0===r&&(r=!1),!i)return null!=this._boundTexturesCache[t]&&(this._activeChannel=t,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)),!1;if(i.video)this._activeChannel=t,i.update();else if(i.delayLoadState===e.DELAYLOADSTATE_NOTLOADED)return i.delayLoad(),!1;var o;o=r?i.depthStencilTexture:i.isReady()?i.getInternalTexture():i.isCube?this.emptyCubeTexture:i.is3D?this.emptyTexture3D:this.emptyTexture,!n&&o&&(o._associatedChannel=t);var s=!0;if(this._boundTexturesCache[t]===o&&(n||this._bindSamplerUniformToChannel(o._associatedChannel,t),s=!1),this._activeChannel=t,o&&o.isMultiview)s&&this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,o,n);else if(o&&o.is3D)s&&this._bindTextureDirectly(this._gl.TEXTURE_3D,o,n),o&&o._cachedWrapU!==i.wrapU&&(o._cachedWrapU=i.wrapU,this._setTextureParameterInteger(this._gl.TEXTURE_3D,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(i.wrapU),o)),o&&o._cachedWrapV!==i.wrapV&&(o._cachedWrapV=i.wrapV,this._setTextureParameterInteger(this._gl.TEXTURE_3D,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(i.wrapV),o)),o&&o._cachedWrapR!==i.wrapR&&(o._cachedWrapR=i.wrapR,this._setTextureParameterInteger(this._gl.TEXTURE_3D,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(i.wrapR),o)),this._setAnisotropicLevel(this._gl.TEXTURE_3D,i);else if(o&&o.isCube){if(s&&this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,o,n),o._cachedCoordinatesMode!==i.coordinatesMode){o._cachedCoordinatesMode=i.coordinatesMode;var a=i.coordinatesMode!==e.TEXTURE_CUBIC_MODE&&i.coordinatesMode!==e.TEXTURE_SKYBOX_MODE?this._gl.REPEAT:this._gl.CLAMP_TO_EDGE;this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP,this._gl.TEXTURE_WRAP_S,a,o),this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP,this._gl.TEXTURE_WRAP_T,a)}this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP,i)}else s&&this._bindTextureDirectly(this._gl.TEXTURE_2D,o,n),o&&o._cachedWrapU!==i.wrapU&&(o._cachedWrapU=i.wrapU,this._setTextureParameterInteger(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(i.wrapU),o)),o&&o._cachedWrapV!==i.wrapV&&(o._cachedWrapV=i.wrapV,this._setTextureParameterInteger(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(i.wrapV),o)),this._setAnisotropicLevel(this._gl.TEXTURE_2D,i);return!0},e.prototype.setTextureArray=function(e,t,i){if(void 0!==e&&t){this._boundUniforms[e]=t,this._textureUnits&&this._textureUnits.length===i.length||(this._textureUnits=new Int32Array(i.length));for(var n=0;n=this._caps.maxVertexAttribs||!this._vertexAttribArraysEnabled[e]||(this._gl.disableVertexAttribArray(e),this._vertexAttribArraysEnabled[e]=!1,this._currentBufferPointers[e].active=!1)}},e.prototype.releaseEffects=function(){for(var e in this._compiledEffects){var t=this._compiledEffects[e].getPipelineContext();this._deletePipelineContext(t)}this._compiledEffects={}},e.prototype.dispose=function(){for(this.hideLoadingUI(),this.stopRenderLoop(),this.onNewSceneAddedObservable.clear();this.postProcesses.length;)this.postProcesses[0].dispose();for(this._emptyTexture&&(this._releaseTexture(this._emptyTexture),this._emptyTexture=null),this._emptyCubeTexture&&(this._releaseTexture(this._emptyCubeTexture),this._emptyCubeTexture=null),this._rescalePostProcess&&this._rescalePostProcess.dispose();this.scenes.length;)this.scenes[0].dispose();1===e.Instances.length&&e.audioEngine&&e.audioEngine.dispose(),this.releaseEffects(),this.unbindAllAttributes(),this._boundUniforms=[],this._dummyFramebuffer&&this._gl.deleteFramebuffer(this._dummyFramebuffer),this.disableVR(),_.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),this._doNotHandleContextLost||(this._renderingCanvas.removeEventListener("webglcontextlost",this._onContextLost),this._renderingCanvas.removeEventListener("webglcontextrestored",this._onContextRestored))),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));var t=e.Instances.indexOf(this);t>=0&&e.Instances.splice(t,1),this._workingCanvas=null,this._workingContext=null,this._currentBufferPointers=[],this._renderingCanvas=null,this._currentProgram=null,this._bindedRenderFunction=null,this.onResizeObservable.clear(),this.onCanvasBlurObservable.clear(),this.onCanvasFocusObservable.clear(),this.onCanvasPointerOutObservable.clear(),this.onBeginFrameObservable.clear(),this.onEndFrameObservable.clear(),h.a.ResetCache();for(var i=0,n=this._activeRequests;i-1?s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.TEXTURE_CUBE_MAP_POSITIVE_X+n,e._webGLTexture,r):s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,e._webGLTexture,r);var c=void 0!==e.type?this._getWebGLTextureType(e.type):s.UNSIGNED_BYTE;switch(c){case s.UNSIGNED_BYTE:o||(o=new Uint8Array(4*t*i)),c=s.UNSIGNED_BYTE;break;default:o||(o=new Float32Array(4*t*i)),c=s.FLOAT}return s.readPixels(0,0,t,i,s.RGBA,c,o),s.bindFramebuffer(s.FRAMEBUFFER,this._currentFramebuffer),o},e.prototype._canRenderToFloatFramebuffer=function(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(e.TEXTURETYPE_FLOAT)},e.prototype._canRenderToHalfFloatFramebuffer=function(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(e.TEXTURETYPE_HALF_FLOAT)},e.prototype._canRenderToFramebuffer=function(e){for(var t=this._gl;t.getError()!==t.NO_ERROR;);var i=!0,n=t.createTexture();t.bindTexture(t.TEXTURE_2D,n),t.texImage2D(t.TEXTURE_2D,0,this._getRGBABufferInternalSizedFormat(e),1,1,0,t.RGBA,this._getWebGLTextureType(e),null),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST);var r=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,n,0);var o=t.checkFramebufferStatus(t.FRAMEBUFFER);if((i=(i=i&&o===t.FRAMEBUFFER_COMPLETE)&&t.getError()===t.NO_ERROR)&&(t.clear(t.COLOR_BUFFER_BIT),i=i&&t.getError()===t.NO_ERROR),i){t.bindFramebuffer(t.FRAMEBUFFER,null);var s=t.RGBA,a=t.UNSIGNED_BYTE,c=new Uint8Array(4);t.readPixels(0,0,1,1,s,a,c),i=i&&t.getError()===t.NO_ERROR}for(t.deleteTexture(n),t.deleteFramebuffer(r),t.bindFramebuffer(t.FRAMEBUFFER,null);!i&&t.getError()!==t.NO_ERROR;);return i},e.prototype._getWebGLTextureType=function(t){if(1===this._webGLVersion){switch(t){case e.TEXTURETYPE_FLOAT:return this._gl.FLOAT;case e.TEXTURETYPE_HALF_FLOAT:return this._gl.HALF_FLOAT_OES;case e.TEXTURETYPE_UNSIGNED_BYTE:return this._gl.UNSIGNED_BYTE}return this._gl.UNSIGNED_BYTE}switch(t){case e.TEXTURETYPE_BYTE:return this._gl.BYTE;case e.TEXTURETYPE_UNSIGNED_BYTE:return this._gl.UNSIGNED_BYTE;case e.TEXTURETYPE_SHORT:return this._gl.SHORT;case e.TEXTURETYPE_UNSIGNED_SHORT:return this._gl.UNSIGNED_SHORT;case e.TEXTURETYPE_INT:return this._gl.INT;case e.TEXTURETYPE_UNSIGNED_INTEGER:return this._gl.UNSIGNED_INT;case e.TEXTURETYPE_FLOAT:return this._gl.FLOAT;case e.TEXTURETYPE_HALF_FLOAT:return this._gl.HALF_FLOAT;case e.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:return this._gl.UNSIGNED_SHORT_4_4_4_4;case e.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:return this._gl.UNSIGNED_SHORT_5_5_5_1;case e.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:return this._gl.UNSIGNED_SHORT_5_6_5;case e.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:return this._gl.UNSIGNED_INT_2_10_10_10_REV;case e.TEXTURETYPE_UNSIGNED_INT_24_8:return this._gl.UNSIGNED_INT_24_8;case e.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:return this._gl.UNSIGNED_INT_10F_11F_11F_REV;case e.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:return this._gl.UNSIGNED_INT_5_9_9_9_REV;case e.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV}return this._gl.UNSIGNED_BYTE},e.prototype._getInternalFormat=function(t){var i=this._gl.RGBA;switch(t){case e.TEXTUREFORMAT_ALPHA:i=this._gl.ALPHA;break;case e.TEXTUREFORMAT_LUMINANCE:i=this._gl.LUMINANCE;break;case e.TEXTUREFORMAT_LUMINANCE_ALPHA:i=this._gl.LUMINANCE_ALPHA;break;case e.TEXTUREFORMAT_RED:i=this._gl.RED;break;case e.TEXTUREFORMAT_RG:i=this._gl.RG;break;case e.TEXTUREFORMAT_RGB:i=this._gl.RGB;break;case e.TEXTUREFORMAT_RGBA:i=this._gl.RGBA}if(this._webGLVersion>1)switch(t){case e.TEXTUREFORMAT_RED_INTEGER:i=this._gl.RED_INTEGER;break;case e.TEXTUREFORMAT_RG_INTEGER:i=this._gl.RG_INTEGER;break;case e.TEXTUREFORMAT_RGB_INTEGER:i=this._gl.RGB_INTEGER;break;case e.TEXTUREFORMAT_RGBA_INTEGER:i=this._gl.RGBA_INTEGER}return i},e.prototype._getRGBABufferInternalSizedFormat=function(t,i){if(1===this._webGLVersion){if(void 0!==i)switch(i){case e.TEXTUREFORMAT_ALPHA:return this._gl.ALPHA;case e.TEXTUREFORMAT_LUMINANCE:return this._gl.LUMINANCE;case e.TEXTUREFORMAT_LUMINANCE_ALPHA:return this._gl.LUMINANCE_ALPHA}return this._gl.RGBA}switch(t){case e.TEXTURETYPE_BYTE:switch(i){case e.TEXTUREFORMAT_RED:return this._gl.R8_SNORM;case e.TEXTUREFORMAT_RG:return this._gl.RG8_SNORM;case e.TEXTUREFORMAT_RGB:return this._gl.RGB8_SNORM;case e.TEXTUREFORMAT_RED_INTEGER:return this._gl.R8I;case e.TEXTUREFORMAT_RG_INTEGER:return this._gl.RG8I;case e.TEXTUREFORMAT_RGB_INTEGER:return this._gl.RGB8I;case e.TEXTUREFORMAT_RGBA_INTEGER:return this._gl.RGBA8I;default:return this._gl.RGBA8_SNORM}case e.TEXTURETYPE_UNSIGNED_BYTE:switch(i){case e.TEXTUREFORMAT_RED:return this._gl.R8;case e.TEXTUREFORMAT_RG:return this._gl.RG8;case e.TEXTUREFORMAT_RGB:return this._gl.RGB8;case e.TEXTUREFORMAT_RGBA:return this._gl.RGBA8;case e.TEXTUREFORMAT_RED_INTEGER:return this._gl.R8UI;case e.TEXTUREFORMAT_RG_INTEGER:return this._gl.RG8UI;case e.TEXTUREFORMAT_RGB_INTEGER:return this._gl.RGB8UI;case e.TEXTUREFORMAT_RGBA_INTEGER:return this._gl.RGBA8UI;case e.TEXTUREFORMAT_ALPHA:return this._gl.ALPHA;case e.TEXTUREFORMAT_LUMINANCE:return this._gl.LUMINANCE;case e.TEXTUREFORMAT_LUMINANCE_ALPHA:return this._gl.LUMINANCE_ALPHA;default:return this._gl.RGBA8}case e.TEXTURETYPE_SHORT:switch(i){case e.TEXTUREFORMAT_RED_INTEGER:return this._gl.R16I;case e.TEXTUREFORMAT_RG_INTEGER:return this._gl.RG16I;case e.TEXTUREFORMAT_RGB_INTEGER:return this._gl.RGB16I;case e.TEXTUREFORMAT_RGBA_INTEGER:default:return this._gl.RGBA16I}case e.TEXTURETYPE_UNSIGNED_SHORT:switch(i){case e.TEXTUREFORMAT_RED_INTEGER:return this._gl.R16UI;case e.TEXTUREFORMAT_RG_INTEGER:return this._gl.RG16UI;case e.TEXTUREFORMAT_RGB_INTEGER:return this._gl.RGB16UI;case e.TEXTUREFORMAT_RGBA_INTEGER:default:return this._gl.RGBA16UI}case e.TEXTURETYPE_INT:switch(i){case e.TEXTUREFORMAT_RED_INTEGER:return this._gl.R32I;case e.TEXTUREFORMAT_RG_INTEGER:return this._gl.RG32I;case e.TEXTUREFORMAT_RGB_INTEGER:return this._gl.RGB32I;case e.TEXTUREFORMAT_RGBA_INTEGER:default:return this._gl.RGBA32I}case e.TEXTURETYPE_UNSIGNED_INTEGER:switch(i){case e.TEXTUREFORMAT_RED_INTEGER:return this._gl.R32UI;case e.TEXTUREFORMAT_RG_INTEGER:return this._gl.RG32UI;case e.TEXTUREFORMAT_RGB_INTEGER:return this._gl.RGB32UI;case e.TEXTUREFORMAT_RGBA_INTEGER:default:return this._gl.RGBA32UI}case e.TEXTURETYPE_FLOAT:switch(i){case e.TEXTUREFORMAT_RED:return this._gl.R32F;case e.TEXTUREFORMAT_RG:return this._gl.RG32F;case e.TEXTUREFORMAT_RGB:return this._gl.RGB32F;case e.TEXTUREFORMAT_RGBA:default:return this._gl.RGBA32F}case e.TEXTURETYPE_HALF_FLOAT:switch(i){case e.TEXTUREFORMAT_RED:return this._gl.R16F;case e.TEXTUREFORMAT_RG:return this._gl.RG16F;case e.TEXTUREFORMAT_RGB:return this._gl.RGB16F;case e.TEXTUREFORMAT_RGBA:default:return this._gl.RGBA16F}case e.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:return this._gl.RGB565;case e.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:return this._gl.R11F_G11F_B10F;case e.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:return this._gl.RGB9_E5;case e.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:return this._gl.RGBA4;case e.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:return this._gl.RGB5_A1;case e.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:switch(i){case e.TEXTUREFORMAT_RGBA:return this._gl.RGB10_A2;case e.TEXTUREFORMAT_RGBA_INTEGER:return this._gl.RGB10_A2UI;default:return this._gl.RGB10_A2}}return this._gl.RGBA8},e.prototype._getRGBAMultiSampleBufferFormat=function(t){return t===e.TEXTURETYPE_FLOAT?this._gl.RGBA32F:t===e.TEXTURETYPE_HALF_FLOAT?this._gl.RGBA16F:this._gl.RGBA8},e.prototype._loadFile=function(e,t,i,n,r,o){var s=this,a=c.h.LoadFile(e,t,i,n,r,o);return this._activeRequests.push(a),a.onCompleteObservable.add(function(e){s._activeRequests.splice(s._activeRequests.indexOf(e),1)}),a},e.prototype._loadFileAsync=function(e,t,i){var n=this;return new Promise(function(r,o){n._loadFile(e,function(e){r(e)},void 0,t,i,function(e,t){o(t)})})},e.isSupported=function(){try{var e=document.createElement("canvas");return null!=(e.getContext("webgl")||e.getContext("experimental-webgl"))&&!!window.WebGLRenderingContext}catch(e){return!1}},e.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"]}],e._TextureLoaders=[],e.ALPHA_DISABLE=p.a.ALPHA_DISABLE,e.ALPHA_ADD=p.a.ALPHA_ADD,e.ALPHA_COMBINE=p.a.ALPHA_COMBINE,e.ALPHA_SUBTRACT=p.a.ALPHA_SUBTRACT,e.ALPHA_MULTIPLY=p.a.ALPHA_MULTIPLY,e.ALPHA_MAXIMIZED=p.a.ALPHA_MAXIMIZED,e.ALPHA_ONEONE=p.a.ALPHA_ONEONE,e.ALPHA_PREMULTIPLIED=p.a.ALPHA_PREMULTIPLIED,e.ALPHA_PREMULTIPLIED_PORTERDUFF=p.a.ALPHA_PREMULTIPLIED_PORTERDUFF,e.ALPHA_INTERPOLATE=p.a.ALPHA_INTERPOLATE,e.ALPHA_SCREENMODE=p.a.ALPHA_SCREENMODE,e.DELAYLOADSTATE_NONE=p.a.DELAYLOADSTATE_NONE,e.DELAYLOADSTATE_LOADED=p.a.DELAYLOADSTATE_LOADED,e.DELAYLOADSTATE_LOADING=p.a.DELAYLOADSTATE_LOADING,e.DELAYLOADSTATE_NOTLOADED=p.a.DELAYLOADSTATE_NOTLOADED,e.NEVER=p.a.NEVER,e.ALWAYS=p.a.ALWAYS,e.LESS=p.a.LESS,e.EQUAL=p.a.EQUAL,e.LEQUAL=p.a.LEQUAL,e.GREATER=p.a.GREATER,e.GEQUAL=p.a.GEQUAL,e.NOTEQUAL=p.a.NOTEQUAL,e.KEEP=p.a.KEEP,e.REPLACE=p.a.REPLACE,e.INCR=p.a.INCR,e.DECR=p.a.DECR,e.INVERT=p.a.INVERT,e.INCR_WRAP=p.a.INCR_WRAP,e.DECR_WRAP=p.a.DECR_WRAP,e.TEXTURE_CLAMP_ADDRESSMODE=p.a.TEXTURE_CLAMP_ADDRESSMODE,e.TEXTURE_WRAP_ADDRESSMODE=p.a.TEXTURE_WRAP_ADDRESSMODE,e.TEXTURE_MIRROR_ADDRESSMODE=p.a.TEXTURE_MIRROR_ADDRESSMODE,e.TEXTUREFORMAT_ALPHA=p.a.TEXTUREFORMAT_ALPHA,e.TEXTUREFORMAT_LUMINANCE=p.a.TEXTUREFORMAT_LUMINANCE,e.TEXTUREFORMAT_LUMINANCE_ALPHA=p.a.TEXTUREFORMAT_LUMINANCE_ALPHA,e.TEXTUREFORMAT_RGB=p.a.TEXTUREFORMAT_RGB,e.TEXTUREFORMAT_RGBA=p.a.TEXTUREFORMAT_RGBA,e.TEXTUREFORMAT_RED=p.a.TEXTUREFORMAT_RED,e.TEXTUREFORMAT_R=p.a.TEXTUREFORMAT_R,e.TEXTUREFORMAT_RG=p.a.TEXTUREFORMAT_RG,e.TEXTUREFORMAT_RED_INTEGER=p.a.TEXTUREFORMAT_RED_INTEGER,e.TEXTUREFORMAT_R_INTEGER=p.a.TEXTUREFORMAT_R_INTEGER,e.TEXTUREFORMAT_RG_INTEGER=p.a.TEXTUREFORMAT_RG_INTEGER,e.TEXTUREFORMAT_RGB_INTEGER=p.a.TEXTUREFORMAT_RGB_INTEGER,e.TEXTUREFORMAT_RGBA_INTEGER=p.a.TEXTUREFORMAT_RGBA_INTEGER,e.TEXTURETYPE_UNSIGNED_BYTE=p.a.TEXTURETYPE_UNSIGNED_BYTE,e.TEXTURETYPE_UNSIGNED_INT=p.a.TEXTURETYPE_UNSIGNED_INT,e.TEXTURETYPE_FLOAT=p.a.TEXTURETYPE_FLOAT,e.TEXTURETYPE_HALF_FLOAT=p.a.TEXTURETYPE_HALF_FLOAT,e.TEXTURETYPE_BYTE=p.a.TEXTURETYPE_BYTE,e.TEXTURETYPE_SHORT=p.a.TEXTURETYPE_SHORT,e.TEXTURETYPE_UNSIGNED_SHORT=p.a.TEXTURETYPE_UNSIGNED_SHORT,e.TEXTURETYPE_INT=p.a.TEXTURETYPE_INT,e.TEXTURETYPE_UNSIGNED_INTEGER=p.a.TEXTURETYPE_UNSIGNED_INTEGER,e.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=p.a.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4,e.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=p.a.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1,e.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=p.a.TEXTURETYPE_UNSIGNED_SHORT_5_6_5,e.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=p.a.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV,e.TEXTURETYPE_UNSIGNED_INT_24_8=p.a.TEXTURETYPE_UNSIGNED_INT_24_8,e.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=p.a.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV,e.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=p.a.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV,e.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=p.a.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV,e.TEXTURE_NEAREST_SAMPLINGMODE=p.a.TEXTURE_NEAREST_SAMPLINGMODE,e.TEXTURE_BILINEAR_SAMPLINGMODE=p.a.TEXTURE_BILINEAR_SAMPLINGMODE,e.TEXTURE_TRILINEAR_SAMPLINGMODE=p.a.TEXTURE_TRILINEAR_SAMPLINGMODE,e.TEXTURE_NEAREST_NEAREST_MIPLINEAR=p.a.TEXTURE_NEAREST_NEAREST_MIPLINEAR,e.TEXTURE_LINEAR_LINEAR_MIPNEAREST=p.a.TEXTURE_LINEAR_LINEAR_MIPNEAREST,e.TEXTURE_LINEAR_LINEAR_MIPLINEAR=p.a.TEXTURE_LINEAR_LINEAR_MIPLINEAR,e.TEXTURE_NEAREST_NEAREST_MIPNEAREST=p.a.TEXTURE_NEAREST_NEAREST_MIPNEAREST,e.TEXTURE_NEAREST_LINEAR_MIPNEAREST=p.a.TEXTURE_NEAREST_LINEAR_MIPNEAREST,e.TEXTURE_NEAREST_LINEAR_MIPLINEAR=p.a.TEXTURE_NEAREST_LINEAR_MIPLINEAR,e.TEXTURE_NEAREST_LINEAR=p.a.TEXTURE_NEAREST_LINEAR,e.TEXTURE_NEAREST_NEAREST=p.a.TEXTURE_NEAREST_NEAREST,e.TEXTURE_LINEAR_NEAREST_MIPNEAREST=p.a.TEXTURE_LINEAR_NEAREST_MIPNEAREST,e.TEXTURE_LINEAR_NEAREST_MIPLINEAR=p.a.TEXTURE_LINEAR_NEAREST_MIPLINEAR,e.TEXTURE_LINEAR_LINEAR=p.a.TEXTURE_LINEAR_LINEAR,e.TEXTURE_LINEAR_NEAREST=p.a.TEXTURE_LINEAR_NEAREST,e.TEXTURE_EXPLICIT_MODE=p.a.TEXTURE_EXPLICIT_MODE,e.TEXTURE_SPHERICAL_MODE=p.a.TEXTURE_SPHERICAL_MODE,e.TEXTURE_PLANAR_MODE=p.a.TEXTURE_PLANAR_MODE,e.TEXTURE_CUBIC_MODE=p.a.TEXTURE_CUBIC_MODE,e.TEXTURE_PROJECTION_MODE=p.a.TEXTURE_PROJECTION_MODE,e.TEXTURE_SKYBOX_MODE=p.a.TEXTURE_SKYBOX_MODE,e.TEXTURE_INVCUBIC_MODE=p.a.TEXTURE_INVCUBIC_MODE,e.TEXTURE_EQUIRECTANGULAR_MODE=p.a.TEXTURE_EQUIRECTANGULAR_MODE,e.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=p.a.TEXTURE_FIXED_EQUIRECTANGULAR_MODE,e.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=p.a.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE,e.SCALEMODE_FLOOR=p.a.SCALEMODE_FLOOR,e.SCALEMODE_NEAREST=p.a.SCALEMODE_NEAREST,e.SCALEMODE_CEILING=p.a.SCALEMODE_CEILING,e.CollisionsEpsilon=.001,e._RescalePostProcessFactory=null,e}()},function(e,t,i){"use strict";i.d(t,"c",function(){return m}),i.d(t,"b",function(){return g}),i.d(t,"d",function(){return v}),i.d(t,"e",function(){return y}),i.d(t,"g",function(){return b}),i.d(t,"h",function(){return T}),i.d(t,"f",function(){return E}),i.d(t,"i",function(){return x}),i.d(t,"a",function(){return A});var n=i(1),r=i(0),o=i(13),s=i(9),a=i(60),c=i(3),l=i(35),u=i(7),h=i(22),d=i(33),f=i(48),p=i(19),_=i(61),m=function(){function e(){}return e.prototype.getColorToRef=function(e){this.color2?r.f.LerpToRef(this.color1,this.color2,Math.random(),e):e.copyFrom(this.color1)},e}(),g=function(){return function(){}}(),v=function(){function e(){}return e.prototype.getFactor=function(){return void 0===this.factor2?this.factor1:o.a.Lerp(this.factor1,this.factor2,Math.random())},e}(),y=function(e){function t(i,n){var r=e.call(this,i)||this;return r.request=n,r.name="LoadFileError",t._setPrototypeOf(r,t.prototype),r}return n.d(t,e),t._setPrototypeOf=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},t}(Error),b=function(){function e(){}return e.ExponentialBackoff=function(e,t){return void 0===e&&(e=3),void 0===t&&(t=500),function(i,n,r){return 0!==n.status||r>=e||-1!==i.indexOf("file:")?-1:Math.pow(2,r)*t}},e}(),T=function(){function e(){}return e.FetchToRef=function(e,t,i,n,r,o){var s=4*((Math.abs(e)*i%i|0)+(Math.abs(t)*n%n|0)*i);o.r=r[s]/255,o.g=r[s+1]/255,o.b=r[s+2]/255,o.a=r[s+3]/255},e.Mix=function(e,t,i){return e*(1-i)+t*i},e.Instantiate=function(t){if(e.RegisteredExternalClasses&&e.RegisteredExternalClasses[t])return e.RegisteredExternalClasses[t];var i=h.a.GetClass(t);if(i)return i;u.a.Warn(t+" not found, you may have missed an import.");for(var n=t.split("."),r=window||this,o=0,s=n.length;o>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,++e},e.FloorPOT=function(e){return e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,(e|=e>>16)-(e>>1)},e.NearestPOT=function(t){var i=e.CeilingPOT(t),n=e.FloorPOT(t);return i-t>t-n?n:i},e.GetExponentOfTwo=function(t,i,n){var r;switch(void 0===n&&(n=c.a.SCALEMODE_NEAREST),n){case c.a.SCALEMODE_FLOOR:r=e.FloorPOT(t);break;case c.a.SCALEMODE_NEAREST:r=e.NearestPOT(t);break;case c.a.SCALEMODE_CEILING:default:r=e.CeilingPOT(t)}return Math.min(r,i)},e.GetFilename=function(e){var t=e.lastIndexOf("/");return t<0?e:e.substring(t+1)},e.GetFolderPath=function(e,t){void 0===t&&(t=!1);var i=e.lastIndexOf("/");return i<0?t?e:"":e.substring(0,i+1)},e.ToDegrees=function(e){return 180*e/Math.PI},e.ToRadians=function(e){return e*Math.PI/180},e.EncodeArrayBufferTobase64=function(e){for(var t,i,n,r,o,s,a,c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",l="",u=0,h=new Uint8Array(e);u>2,o=(3&t)<<4|(i=u>4,s=(15&i)<<2|(n=u>6,a=63&n,isNaN(i)?s=a=64:isNaN(n)&&(a=64),l+=c.charAt(r)+c.charAt(o)+c.charAt(s)+c.charAt(a);return"data:image/png;base64,"+l},e.ExtractMinAndMaxIndexed=function(e,t,i,n,o){void 0===o&&(o=null);for(var s=new r.x(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),a=new r.x(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),c=i;c=200&&t.status<300||0===t.status&&(!l.a.IsWindowObjectExist()||e.IsFileURL()))return void i(o?t.response:t.responseText,t.responseURL);var n=e.DefaultRetryStrategy;if(n){var f=n(h,t,a);if(-1!==f)return t.removeEventListener("loadend",u),t=new _.a,void(r=setTimeout(function(){return s(a+1)},f))}var m=new y("Error status: "+t.status+" "+t.statusText+" - Unable to load "+h,t);if(!c)throw m;c(t,m)}};t.addEventListener("readystatechange",p),t.send()};s(0)};if(r&&r.enableSceneOffline){var m=function(e){e&&e.status>400?c&&c(e):d||p()};r.open(function(){d||r&&r.loadFile(t,function(e){d||i(e),f.onCompleteObservable.notifyObservers(f)},n?function(e){d||n(e)}:void 0,m,o)},m)}else p();return f},e.LoadScript=function(e,t,i,n){if(l.a.IsWindowObjectExist()){var r=document.getElementsByTagName("head")[0],o=document.createElement("script");o.setAttribute("type","text/javascript"),o.setAttribute("src",e),n&&(o.id=n),o.onload=function(){t&&t()},o.onerror=function(t){i&&i("Unable to load script '"+e+"'",t)},r.appendChild(o)}},e.LoadScriptAsync=function(e,t){return new Promise(function(i,n){if(l.a.IsWindowObjectExist()){var r=document.getElementsByTagName("head")[0],o=document.createElement("script");o.setAttribute("type","text/javascript"),o.setAttribute("src",e),t&&(o.id=t),o.onload=function(){i(!0)},o.onerror=function(e){i(!1)},r.appendChild(o)}else i(!1)})},e.ReadFileAsDataURL=function(e,t,i){var n=new FileReader,r={onCompleteObservable:new s.c,abort:function(){return n.abort()}};return n.onloadend=function(e){r.onCompleteObservable.notifyObservers(r)},n.onload=function(e){t(e.target.result)},n.onprogress=i,n.readAsDataURL(e),r},e.ReadFile=function(e,t,i,n){var r=new FileReader,o={onCompleteObservable:new s.c,abort:function(){return r.abort()}};return r.onloadend=function(e){return o.onCompleteObservable.notifyObservers(o)},r.onerror=function(i){u.a.Log("Error while reading file: "+e.name),t(JSON.stringify({autoClear:!0,clearColor:[1,0,0],ambientColor:[0,0,0],gravity:[0,-9.807,0],meshes:[],cameras:[],lights:[]}))},r.onload=function(e){t(e.target.result)},i&&(r.onprogress=i),n?r.readAsArrayBuffer(e):r.readAsText(e),o},e.FileAsURL=function(e){var t=new Blob([e]);return(window.URL||window.webkitURL).createObjectURL(t)},e.Format=function(e,t){return void 0===t&&(t=2),e.toFixed(t)},e.CheckExtends=function(e,t,i){t.minimizeInPlace(e),i.maximizeInPlace(e)},e.DeepCopy=function(e,t,i,n){d.a.DeepCopy(e,t,i,n)},e.IsEmpty=function(e){for(var t in e)if(e.hasOwnProperty(t))return!1;return!0},e.EndsWith=function(e,t){return-1!==e.indexOf(t,e.length-t.length)},e.StartsWith=function(e,t){return 0===e.indexOf(t)},e.RegisterTopRootEvents=function(e){for(var t=0;t=r.gradient&&e<=o.gradient)return void i(r,o,(e-r.gradient)/(o.gradient-r.gradient))}var s=t.length-1;i(t[s],t[s],1)},e.BaseUrl="",e.UseCustomRequestHeaders=!1,e.CustomRequestHeaders=_.a.CustomRequestHeaders,e.DefaultRetryStrategy=b.ExponentialBackoff(),e.CorsBehavior="anonymous",e.UseFallbackTexture=!0,e.RegisteredExternalClasses={},e.fallbackTexture="data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z",e._tmpFloatArray=new Float32Array(1),e.GetDOMTextContent=l.a.GetDOMTextContent,e.PreprocessUrl=function(e){return e},e.NoneLogLevel=u.a.NoneLogLevel,e.MessageLogLevel=u.a.MessageLogLevel,e.WarningLogLevel=u.a.WarningLogLevel,e.ErrorLogLevel=u.a.ErrorLogLevel,e.AllLogLevel=u.a.AllLogLevel,e.IsWindowObjectExist=l.a.IsWindowObjectExist,e.PerformanceNoneLogLevel=0,e.PerformanceUserMarkLogLevel=1,e.PerformanceConsoleLogLevel=2,e.StartPerformanceCounter=e._StartPerformanceCounterDisabled,e.EndPerformanceCounter=e._EndPerformanceCounterDisabled,e}(),E=function(){function e(){this._startMonitoringTime=0,this._min=0,this._max=0,this._average=0,this._lastSecAverage=0,this._current=0,this._totalValueCount=0,this._totalAccumulated=0,this._lastSecAccumulated=0,this._lastSecTime=0,this._lastSecValueCount=0}return Object.defineProperty(e.prototype,"min",{get:function(){return this._min},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"max",{get:function(){return this._max},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"average",{get:function(){return this._average},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"lastSecAverage",{get:function(){return this._lastSecAverage},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"current",{get:function(){return this._current},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"total",{get:function(){return this._totalAccumulated},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"count",{get:function(){return this._totalValueCount},enumerable:!0,configurable:!0}),e.prototype.fetchNewFrame=function(){this._totalValueCount++,this._current=0,this._lastSecValueCount++},e.prototype.addCount=function(t,i){e.Enabled&&(this._current+=t,i&&this._fetchResult())},e.prototype.beginMonitoring=function(){e.Enabled&&(this._startMonitoringTime=f.a.Now)},e.prototype.endMonitoring=function(t){if(void 0===t&&(t=!0),e.Enabled){t&&this.fetchNewFrame();var i=f.a.Now;this._current=i-this._startMonitoringTime,t&&this._fetchResult()}},e.prototype._fetchResult=function(){this._totalAccumulated+=this._current,this._lastSecAccumulated+=this._current,this._min=Math.min(this._min,this._current),this._max=Math.max(this._max,this._current),this._average=this._totalAccumulated/this._totalValueCount;var e=f.a.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)},e.Enabled=!0,e}();function x(e,t){return function(i){i.__bjsclassName__=e,i.__bjsmoduleName__=null!=t?t:null}}var A=function(){function e(e,t,i,n){void 0===n&&(n=0),this.iterations=e,this.index=n-1,this._done=!1,this._fn=t,this._successCallback=i}return e.prototype.executeNext=function(){this._done||(this.index+1=t)break;if(n(s),o&&o()){e.breakLoop();break}}e.executeNext()},s)},r)},e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return s});var n=i(0),r=i(4),o=i(19),s=function(){function e(){}return e.prototype.set=function(e,t){switch(t){case r.b.PositionKind:this.positions=e;break;case r.b.NormalKind:this.normals=e;break;case r.b.TangentKind:this.tangents=e;break;case r.b.UVKind:this.uvs=e;break;case r.b.UV2Kind:this.uvs2=e;break;case r.b.UV3Kind:this.uvs3=e;break;case r.b.UV4Kind:this.uvs4=e;break;case r.b.UV5Kind:this.uvs5=e;break;case r.b.UV6Kind:this.uvs6=e;break;case r.b.ColorKind:this.colors=e;break;case r.b.MatricesIndicesKind:this.matricesIndices=e;break;case r.b.MatricesWeightsKind:this.matricesWeights=e;break;case r.b.MatricesIndicesExtraKind:this.matricesIndicesExtra=e;break;case r.b.MatricesWeightsExtraKind:this.matricesWeightsExtra=e}},e.prototype.applyToMesh=function(e,t){return this._applyTo(e,t),this},e.prototype.applyToGeometry=function(e,t){return this._applyTo(e,t),this},e.prototype.updateMesh=function(e){return this._update(e),this},e.prototype.updateGeometry=function(e){return this._update(e),this},e.prototype._applyTo=function(e,t){return void 0===t&&(t=!1),this.positions&&e.setVerticesData(r.b.PositionKind,this.positions,t),this.normals&&e.setVerticesData(r.b.NormalKind,this.normals,t),this.tangents&&e.setVerticesData(r.b.TangentKind,this.tangents,t),this.uvs&&e.setVerticesData(r.b.UVKind,this.uvs,t),this.uvs2&&e.setVerticesData(r.b.UV2Kind,this.uvs2,t),this.uvs3&&e.setVerticesData(r.b.UV3Kind,this.uvs3,t),this.uvs4&&e.setVerticesData(r.b.UV4Kind,this.uvs4,t),this.uvs5&&e.setVerticesData(r.b.UV5Kind,this.uvs5,t),this.uvs6&&e.setVerticesData(r.b.UV6Kind,this.uvs6,t),this.colors&&e.setVerticesData(r.b.ColorKind,this.colors,t),this.matricesIndices&&e.setVerticesData(r.b.MatricesIndicesKind,this.matricesIndices,t),this.matricesWeights&&e.setVerticesData(r.b.MatricesWeightsKind,this.matricesWeights,t),this.matricesIndicesExtra&&e.setVerticesData(r.b.MatricesIndicesExtraKind,this.matricesIndicesExtra,t),this.matricesWeightsExtra&&e.setVerticesData(r.b.MatricesWeightsExtraKind,this.matricesWeightsExtra,t),this.indices?e.setIndices(this.indices,null,t):e.setIndices([],null),this},e.prototype._update=function(e,t,i){return this.positions&&e.updateVerticesData(r.b.PositionKind,this.positions,t,i),this.normals&&e.updateVerticesData(r.b.NormalKind,this.normals,t,i),this.tangents&&e.updateVerticesData(r.b.TangentKind,this.tangents,t,i),this.uvs&&e.updateVerticesData(r.b.UVKind,this.uvs,t,i),this.uvs2&&e.updateVerticesData(r.b.UV2Kind,this.uvs2,t,i),this.uvs3&&e.updateVerticesData(r.b.UV3Kind,this.uvs3,t,i),this.uvs4&&e.updateVerticesData(r.b.UV4Kind,this.uvs4,t,i),this.uvs5&&e.updateVerticesData(r.b.UV5Kind,this.uvs5,t,i),this.uvs6&&e.updateVerticesData(r.b.UV6Kind,this.uvs6,t,i),this.colors&&e.updateVerticesData(r.b.ColorKind,this.colors,t,i),this.matricesIndices&&e.updateVerticesData(r.b.MatricesIndicesKind,this.matricesIndices,t,i),this.matricesWeights&&e.updateVerticesData(r.b.MatricesWeightsKind,this.matricesWeights,t,i),this.matricesIndicesExtra&&e.updateVerticesData(r.b.MatricesIndicesExtraKind,this.matricesIndicesExtra,t,i),this.matricesWeightsExtra&&e.updateVerticesData(r.b.MatricesWeightsExtraKind,this.matricesWeightsExtra,t,i),this.indices&&e.setIndices(this.indices,null),this},e.prototype.transform=function(e){var t,i=e.m[0]*e.m[5]*e.m[10]<0,r=n.x.Zero();if(this.positions){var o=n.x.Zero();for(t=0;tr.bbSize.y?r.bbSize.x:r.bbSize.y;$=$>r.bbSize.z?$:r.bbSize.z,L=r.subDiv.X*O/r.bbSize.x,w=r.subDiv.Y*O/r.bbSize.y,F=r.subDiv.Z*O/r.bbSize.z,N=r.subDiv.max*r.subDiv.max,r.facetPartitioning.length=0}for(o=0;o0?1:-1},e.Clamp=function(e,t,i){return void 0===t&&(t=0),void 0===i&&(i=1),Math.min(i,Math.max(t,e))},e.Log2=function(e){return Math.log(e)*Math.LOG2E},e.Repeat=function(e,t){return e-Math.floor(e/t)*t},e.Normalize=function(e,t,i){return(e-t)/(i-t)},e.Denormalize=function(e,t,i){return e*(i-t)+t},e.DeltaAngle=function(t,i){var n=e.Repeat(i-t,360);return n>180&&(n-=360),n},e.PingPong=function(t,i){var n=e.Repeat(t,2*i);return i-Math.abs(n-i)},e.SmoothStep=function(t,i,n){var r=e.Clamp(n);return i*(r=-2*r*r*r+3*r*r)+t*(1-r)},e.MoveTowards=function(t,i,n){return Math.abs(i-t)<=n?i:t+e.Sign(i-t)*n},e.MoveTowardsAngle=function(t,i,n){var r=e.DeltaAngle(t,i),o=0;return-n180&&(r-=360),t+r*e.Clamp(n)},e.InverseLerp=function(t,i,n){return t!=i?e.Clamp((n-t)/(i-t)):0},e.Hermite=function(e,t,i,n,r){var o=r*r,s=r*o;return e*(2*s-3*o+1)+i*(-2*s+3*o)+t*(s-2*o+r)+n*(s-o)},e.RandomRange=function(e,t){return e===t?e:Math.random()*(t-e)+e},e.RangeToPercent=function(e,t,i){return(e-t)/(i-t)},e.PercentToRange=function(e,t,i){return(i-t)*e+t},e.NormalizeRadians=function(t){return t-=e.TwoPi*Math.floor((t+Math.PI)/e.TwoPi)},e.TwoPi=2*Math.PI,e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return l});var n=i(7),r=i(16),o=i(0),s=i(21),a=i(4),c=i(40),l=function(){function e(){}return e.BindEyePosition=function(e,t){if(t._forcedViewPosition)e.setVector3("vEyePosition",t._forcedViewPosition);else{var i=t.activeCamera.globalPosition;i||(i=t.activeCamera.devicePosition),e.setVector3("vEyePosition",t._mirroredCameraPosition?t._mirroredCameraPosition:i)}},e.PrepareDefinesForMergedUV=function(e,t,i){t._needUVs=!0,t[i]=!0,e.getTextureMatrix().isIdentityAs3x2()?(t[i+"DIRECTUV"]=e.coordinatesIndex+1,0===e.coordinatesIndex?t.MAINUV1=!0:t.MAINUV2=!0):t[i+"DIRECTUV"]=0},e.BindTextureMatrix=function(e,t,i){var n=e.getTextureMatrix();n.isIdentityAs3x2()||t.updateMatrix(i+"Matrix",n)},e.GetFogState=function(e,t){return t.fogEnabled&&e.applyFog&&t.fogMode!==r.a.FOGMODE_NONE},e.PrepareDefinesForMisc=function(e,t,i,n,r,o,s){s._areMiscDirty&&(s.LOGARITHMICDEPTH=i,s.POINTSIZE=n,s.FOG=r&&this.GetFogState(e,t),s.NONUNIFORMSCALING=e.nonUniformScaling,s.ALPHATEST=o)},e.PrepareDefinesForFrameBoundValues=function(e,t,i,n,r){void 0===r&&(r=null);var o,s,a,c,l=!1;o=null==r?void 0!==e.clipPlane&&null!==e.clipPlane:r,s=null==r?void 0!==e.clipPlane2&&null!==e.clipPlane2:r,a=null==r?void 0!==e.clipPlane3&&null!==e.clipPlane3:r,c=null==r?void 0!==e.clipPlane4&&null!==e.clipPlane4:r,i.CLIPPLANE!==o&&(i.CLIPPLANE=o,l=!0),i.CLIPPLANE2!==s&&(i.CLIPPLANE2=s,l=!0),i.CLIPPLANE3!==a&&(i.CLIPPLANE3=a,l=!0),i.CLIPPLANE4!==c&&(i.CLIPPLANE4=c,l=!0),i.DEPTHPREPASS!==!t.getColorWrite()&&(i.DEPTHPREPASS=!i.DEPTHPREPASS,l=!0),i.INSTANCES!==n&&(i.INSTANCES=n,l=!0),l&&i.markAsUnprocessed()},e.PrepareDefinesForBones=function(e,t){if(e.useBones&&e.computeBonesUsingShaders&&e.skeleton){t.NUM_BONE_INFLUENCERS=e.numBoneInfluencers;var i=void 0!==t.BONETEXTURE;e.skeleton.isUsingTextureForMatrices&&i?t.BONETEXTURE=!0:(t.BonesPerMesh=e.skeleton.bones.length+1,t.BONETEXTURE=!i&&void 0)}else t.NUM_BONE_INFLUENCERS=0,t.BonesPerMesh=0},e.PrepareDefinesForMorphTargets=function(e,t){var i=e.morphTargetManager;i?(t.MORPHTARGETS_TANGENT=i.supportsTangents&&t.TANGENT,t.MORPHTARGETS_NORMAL=i.supportsNormals&&t.NORMAL,t.MORPHTARGETS=i.numInfluencers>0,t.NUM_MORPH_INFLUENCERS=i.numInfluencers):(t.MORPHTARGETS_TANGENT=!1,t.MORPHTARGETS_NORMAL=!1,t.MORPHTARGETS=!1,t.NUM_MORPH_INFLUENCERS=0)},e.PrepareDefinesForAttributes=function(e,t,i,n,r,o){if(void 0===r&&(r=!1),void 0===o&&(o=!0),!t._areAttributesDirty&&t._needNormals===t._normals&&t._needUVs===t._uvs)return!1;if(t._normals=t._needNormals,t._uvs=t._needUVs,t.NORMAL=t._needNormals&&e.isVerticesDataPresent(a.b.NormalKind),t._needNormals&&e.isVerticesDataPresent(a.b.TangentKind)&&(t.TANGENT=!0),t._needUVs?(t.UV1=e.isVerticesDataPresent(a.b.UVKind),t.UV2=e.isVerticesDataPresent(a.b.UV2Kind)):(t.UV1=!1,t.UV2=!1),i){var s=e.useVertexColors&&e.isVerticesDataPresent(a.b.ColorKind);t.VERTEXCOLOR=s,t.VERTEXALPHA=e.hasVertexAlpha&&s&&o}return n&&this.PrepareDefinesForBones(e,t),r&&this.PrepareDefinesForMorphTargets(e,t),!0},e.PrepareDefinesForMultiview=function(e,t){if(e.activeCamera){var i=t.MULTIVIEW;t.MULTIVIEW=null!==e.activeCamera.outputRenderTarget&&e.activeCamera.outputRenderTarget.getViewCount()>1,t.MULTIVIEW!=i&&t.markAsUnprocessed()}},e.PrepareDefinesForLights=function(e,t,i,n,r,o){if(void 0===r&&(r=4),void 0===o&&(o=!1),!i._areLightsDirty)return i._needNormals;var s=0,a=!1,l=!1,u=!1,h=!1,d=!1;if(e.lightsEnabled&&!o)for(var f=0,p=t.lightSources;f0&&(h=!0,m.prepareDefines(i,s))}}if(_.lightmapMode!=c.a.LIGHTMAP_DEFAULT?(u=!0,i["LIGHTMAPEXCLUDED"+s]=!0,i["LIGHTMAPNOSPECULAR"+s]=_.lightmapMode==c.a.LIGHTMAP_SHADOWSONLY):(i["LIGHTMAPEXCLUDED"+s]=!1,i["LIGHTMAPNOSPECULAR"+s]=!1),++s===r)break}i.SPECULARTERM=d,i.SHADOWS=h;for(var v=s;v0&&(r=n+o,t.addFallback(r,"LIGHT"+o)),e.SHADOWS||(e["SHADOW"+o]&&t.addFallback(n,"SHADOW"+o),e["SHADOWPCF"+o]&&t.addFallback(n,"SHADOWPCF"+o),e["SHADOWPCSS"+o]&&t.addFallback(n,"SHADOWPCSS"+o),e["SHADOWPOISSON"+o]&&t.addFallback(n,"SHADOWPOISSON"+o),e["SHADOWESM"+o]&&t.addFallback(n,"SHADOWESM"+o));return r++},e.PrepareAttributesForMorphTargets=function(e,t,i){var r=i.NUM_MORPH_INFLUENCERS;if(r>0&&s.a.LastCreatedEngine)for(var o=s.a.LastCreatedEngine.getCaps().maxVertexAttribs,c=t.morphTargetManager,l=c&&c.supportsNormals&&i.NORMAL,u=c&&c.supportsTangents&&i.TANGENT,h=0;ho&&n.a.Error("Cannot add more vertex attributes for mesh "+t.name)},e.PrepareAttributesForBones=function(e,t,i,n){i.NUM_BONE_INFLUENCERS>0&&(n.addCPUSkinningFallback(0,t),e.push(a.b.MatricesIndicesKind),e.push(a.b.MatricesWeightsKind),i.NUM_BONE_INFLUENCERS>4&&(e.push(a.b.MatricesIndicesExtraKind),e.push(a.b.MatricesWeightsExtraKind)))},e.PrepareAttributesForInstances=function(e,t){t.INSTANCES&&this.PushAttributesForInstances(e)},e.PushAttributesForInstances=function(e){e.push("world0"),e.push("world1"),e.push("world2"),e.push("world3")},e.BindLightShadow=function(e,t,i,n){if(e.shadowEnabled&&t.receiveShadows){var r=e.getShadowGenerator();r&&r.bindShadowLight(i,n)}},e.BindLightProperties=function(e,t,i){e.transferToEffect(t,i+"")},e.BindLights=function(t,i,n,r,s,a){void 0===s&&(s=4),void 0===a&&(a=!1);for(var c=Math.min(i.lightSources.length,s),l=0;l-1){var n=i.getTransformMatrixTexture();t.setTexture("boneSampler",n),t.setFloat("boneTextureWidth",4*(i.bones.length+1))}else{var r=i.getTransformMatrices(e);r&&t.setMatrices("mBones",r)}}},e.BindMorphTargetParameters=function(e,t){var i=e.morphTargetManager;e&&i&&t.setFloatArray("morphTargetInfluences",i.influences)},e.BindLogDepth=function(e,t,i){e.LOGARITHMICDEPTH&&t.setFloat("logarithmicDepthConstant",2/(Math.log(i.activeCamera.maxZ+1)/Math.LN2))},e.BindClipPlane=function(e,t){if(t.clipPlane){var i=t.clipPlane;e.setFloat4("vClipPlane",i.normal.x,i.normal.y,i.normal.z,i.d)}if(t.clipPlane2){i=t.clipPlane2;e.setFloat4("vClipPlane2",i.normal.x,i.normal.y,i.normal.z,i.d)}if(t.clipPlane3){i=t.clipPlane3;e.setFloat4("vClipPlane3",i.normal.x,i.normal.y,i.normal.z,i.d)}if(t.clipPlane4){i=t.clipPlane4;e.setFloat4("vClipPlane4",i.normal.x,i.normal.y,i.normal.z,i.d)}},e._tempFogColor=o.e.Black(),e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return r}),i.d(t,"b",function(){return o});var n=i(1),r=function(){function e(){}return e.NAME_EFFECTLAYER="EffectLayer",e.NAME_LAYER="Layer",e.NAME_LENSFLARESYSTEM="LensFlareSystem",e.NAME_BOUNDINGBOXRENDERER="BoundingBoxRenderer",e.NAME_PARTICLESYSTEM="ParticleSystem",e.NAME_GAMEPAD="Gamepad",e.NAME_SIMPLIFICATIONQUEUE="SimplificationQueue",e.NAME_GEOMETRYBUFFERRENDERER="GeometryBufferRenderer",e.NAME_DEPTHRENDERER="DepthRenderer",e.NAME_POSTPROCESSRENDERPIPELINEMANAGER="PostProcessRenderPipelineManager",e.NAME_SPRITE="Sprite",e.NAME_OUTLINERENDERER="Outline",e.NAME_PROCEDURALTEXTURE="ProceduralTexture",e.NAME_SHADOWGENERATOR="ShadowGenerator",e.NAME_OCTREE="Octree",e.NAME_PHYSICSENGINE="PhysicsEngine",e.NAME_AUDIO="Audio",e.STEP_ISREADYFORMESH_EFFECTLAYER=0,e.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER=0,e.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER=0,e.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER=0,e.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER=1,e.STEP_BEFORECAMERADRAW_EFFECTLAYER=0,e.STEP_BEFORECAMERADRAW_LAYER=1,e.STEP_BEFORERENDERTARGETDRAW_LAYER=0,e.STEP_BEFORERENDERINGMESH_OUTLINE=0,e.STEP_AFTERRENDERINGMESH_OUTLINE=0,e.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW=0,e.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER=1,e.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE=0,e.STEP_BEFORECAMERAUPDATE_GAMEPAD=1,e.STEP_BEFORECLEAR_PROCEDURALTEXTURE=0,e.STEP_AFTERRENDERTARGETDRAW_LAYER=0,e.STEP_AFTERCAMERADRAW_EFFECTLAYER=0,e.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM=1,e.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW=2,e.STEP_AFTERCAMERADRAW_LAYER=3,e.STEP_AFTERRENDER_AUDIO=0,e.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR=0,e.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER=1,e.STEP_GATHERRENDERTARGETS_DEPTHRENDERER=2,e.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER=3,e.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER=0,e.STEP_POINTERMOVE_SPRITE=0,e.STEP_POINTERDOWN_SPRITE=0,e.STEP_POINTERUP_SPRITE=0,e}(),o=function(e){function t(t){return e.apply(this,t)||this}return n.d(t,e),t.Create=function(){return Object.create(t.prototype)},t.prototype.registerStep=function(e,t,i){var n=0;for(Number.MAX_VALUE;ne.LongPressDelay&&!n._isPointerSwiping()&&(n._startingPointerTime=0,o.processTrigger(x.a.ACTION_OnLongPressTrigger,y.a.CreateNew(t.pickedMesh,i)))},e.LongPressDelay)}}else for(var s=0,a=r._pointerDownStage;se.DragMovementThreshold||Math.abs(this._startingPointerPosition.y-this._pointerY)>e.DragMovementThreshold},e.prototype.simulatePointerUp=function(e,t,i){var n=new PointerEvent("pointerup",t),r=new I;i?r.doubleClick=!0:r.singleClick=!0,this._checkPrePointerObservable(e,n,C.a.POINTERUP)||this._processPointerUp(e,n,r)},e.prototype._processPointerUp=function(e,t,i){var n=this._scene;if(e&&e&&e.pickedMesh){if(this._pickedUpMesh=e.pickedMesh,this._pickedDownMesh===this._pickedUpMesh&&(n.onPointerPick&&n.onPointerPick(t,e),i.singleClick&&!i.ignore&&n.onPointerObservable.hasObservers())){var r=C.a.POINTERPICK,o=new C.b(r,t,e);this._setRayOnPointerInfo(o),n.onPointerObservable.notifyObservers(o,r)}var s=e.pickedMesh._getActionManagerForTrigger();if(s&&!i.ignore){s.processTrigger(x.a.ACTION_OnPickUpTrigger,y.a.CreateNew(e.pickedMesh,t)),!i.hasSwiped&&i.singleClick&&s.processTrigger(x.a.ACTION_OnPickTrigger,y.a.CreateNew(e.pickedMesh,t));var a=e.pickedMesh._getActionManagerForTrigger(x.a.ACTION_OnDoublePickTrigger);i.doubleClick&&a&&a.processTrigger(x.a.ACTION_OnDoublePickTrigger,y.a.CreateNew(e.pickedMesh,t))}}else if(!i.ignore)for(var c=0,l=n._pointerUpStage;ce.DoubleClickDelay&&!o._doubleClickOccured||t!==o._previousButtonPressed)&&(o._doubleClickOccured=!1,i.singleClick=!0,i.ignore=!1,n(i,o._currentPickResult))},this._initClickEvent=function(t,i,n,r){var s=new I;o._currentPickResult=null;var a=null,c=t.hasSpecificMask(C.a.POINTERPICK)||i.hasSpecificMask(C.a.POINTERPICK)||t.hasSpecificMask(C.a.POINTERTAP)||i.hasSpecificMask(C.a.POINTERTAP)||t.hasSpecificMask(C.a.POINTERDOUBLETAP)||i.hasSpecificMask(C.a.POINTERDOUBLETAP);!c&&M.a&&(a=o._initActionManager(a,s))&&(c=a.hasPickTriggers);var l=!1;if(c){var u=n.button;if(s.hasSwiped=o._isPointerSwiping(),!s.hasSwiped){var h=!e.ExclusiveDoubleClickMode;h||(h=!t.hasSpecificMask(C.a.POINTERDOUBLETAP)&&!i.hasSpecificMask(C.a.POINTERDOUBLETAP))&&!M.a.HasSpecificTrigger(x.a.ACTION_OnDoublePickTrigger)&&(a=o._initActionManager(a,s))&&(h=!a.hasSpecificTrigger(x.a.ACTION_OnDoublePickTrigger)),h?(Date.now()-o._previousStartingPointerTime>e.DoubleClickDelay||u!==o._previousButtonPressed)&&(s.singleClick=!0,r(s,o._currentPickResult),l=!0):(o._previousDelayedSimpleClickTimeout=o._delayedSimpleClickTimeout,o._delayedSimpleClickTimeout=window.setTimeout(o._delayedSimpleClick.bind(o,u,s,r),e.DoubleClickDelay));var d=t.hasSpecificMask(C.a.POINTERDOUBLETAP)||i.hasSpecificMask(C.a.POINTERDOUBLETAP);!d&&M.a.HasSpecificTrigger(x.a.ACTION_OnDoublePickTrigger)&&(a=o._initActionManager(a,s))&&(d=a.hasSpecificTrigger(x.a.ACTION_OnDoublePickTrigger)),d&&(u===o._previousButtonPressed&&Date.now()-o._previousStartingPointerTime0){for(var e=0,t=this._transientComponents;e0)return!1;for(e=0;e0,r=0,o=this._isReadyForMeshStage;r0)for(var s=0,a=this.activeCameras;s0},enumerable:!0,configurable:!0}),t.prototype.executeWhenReady=function(e){var t=this;this.onReadyObservable.add(e),-1===this._executeWhenReadyTimeoutId&&(this._executeWhenReadyTimeoutId=setTimeout(function(){t._checkIsReady()},150))},t.prototype.whenReadyAsync=function(){var e=this;return new Promise(function(t){e.executeWhenReady(function(){t()})})},t.prototype._checkIsReady=function(){var e=this;if(this._registerTransientComponents(),this.isReady())return this.onReadyObservable.notifyObservers(this),this.onReadyObservable.clear(),void(this._executeWhenReadyTimeoutId=-1);this._executeWhenReadyTimeoutId=setTimeout(function(){e._checkIsReady()},150)},Object.defineProperty(t.prototype,"animatables",{get:function(){return this._activeAnimatables},enumerable:!0,configurable:!0}),t.prototype.resetLastAnimationTimeFrame=function(){this._animationTimeLast=o.a.Now},t.prototype.getViewMatrix=function(){return this._viewMatrix},t.prototype.getProjectionMatrix=function(){return this._projectionMatrix},t.prototype.getTransformMatrix=function(){return this._transformMatrix},t.prototype.setTransformMatrix=function(e,t,i,n){this._viewUpdateFlag===e.updateFlag&&this._projectionUpdateFlag===t.updateFlag||(this._viewUpdateFlag=e.updateFlag,this._projectionUpdateFlag=t.updateFlag,this._viewMatrix=e,this._projectionMatrix=t,this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._frustumPlanes?u.i.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=u.i.GetPlanes(this._transformMatrix),this._multiviewSceneUbo&&this._multiviewSceneUbo.useUbo?this._updateMultiviewUbo(i,n):this._sceneUbo.useUbo&&(this._sceneUbo.updateMatrix("viewProjection",this._transformMatrix),this._sceneUbo.updateMatrix("view",this._viewMatrix),this._sceneUbo.update()))},t.prototype.getSceneUniformBuffer=function(){return this._multiviewSceneUbo?this._multiviewSceneUbo:this._sceneUbo},t.prototype.getUniqueId=function(){var e=t._uniqueIdCounter;return t._uniqueIdCounter++,e},t.prototype.addMesh=function(e,t){var i=this;void 0===t&&(t=!1),this.meshes.push(e),e._resyncLightSources(),this.onNewMeshAddedObservable.notifyObservers(e),t&&e.getChildMeshes().forEach(function(e){i.addMesh(e)})},t.prototype.removeMesh=function(e,t){var i=this;void 0===t&&(t=!1);var n=this.meshes.indexOf(e);return-1!==n&&(this.meshes[n]=this.meshes[this.meshes.length-1],this.meshes.pop()),this.onMeshRemovedObservable.notifyObservers(e),t&&e.getChildMeshes().forEach(function(e){i.removeMesh(e)}),n},t.prototype.addTransformNode=function(e){e._indexInSceneTransformNodesArray=this.transformNodes.length,this.transformNodes.push(e),this.onNewTransformNodeAddedObservable.notifyObservers(e)},t.prototype.removeTransformNode=function(e){var t=e._indexInSceneTransformNodesArray;if(-1!==t){if(t!==this.transformNodes.length-1){var i=this.transformNodes[this.transformNodes.length-1];this.transformNodes[t]=i,i._indexInSceneTransformNodesArray=t}e._indexInSceneTransformNodesArray=-1,this.transformNodes.pop()}return this.onTransformNodeRemovedObservable.notifyObservers(e),t},t.prototype.removeSkeleton=function(e){var t=this.skeletons.indexOf(e);return-1!==t&&(this.skeletons.splice(t,1),this.onSkeletonRemovedObservable.notifyObservers(e)),t},t.prototype.removeMorphTargetManager=function(e){var t=this.morphTargetManagers.indexOf(e);return-1!==t&&this.morphTargetManagers.splice(t,1),t},t.prototype.removeLight=function(e){var t=this.lights.indexOf(e);if(-1!==t){for(var i=0,n=this.meshes;i0?this.activeCamera=this.cameras[0]:this.activeCamera=null),this.onCameraRemovedObservable.notifyObservers(e),t},t.prototype.removeParticleSystem=function(e){var t=this.particleSystems.indexOf(e);return-1!==t&&this.particleSystems.splice(t,1),t},t.prototype.removeAnimation=function(e){var t=this.animations.indexOf(e);return-1!==t&&this.animations.splice(t,1),t},t.prototype.stopAnimation=function(e,t,i){},t.prototype.removeAnimationGroup=function(e){var t=this.animationGroups.indexOf(e);return-1!==t&&this.animationGroups.splice(t,1),t},t.prototype.removeMultiMaterial=function(e){var t=this.multiMaterials.indexOf(e);return-1!==t&&this.multiMaterials.splice(t,1),t},t.prototype.removeMaterial=function(e){var t=e._indexInSceneMaterialArray;if(-1!==t&&t=0;t--)if(this.meshes[t].id===e)return this.meshes[t];return null},t.prototype.getLastEntryByID=function(e){var t;for(t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];for(t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];for(t=this.cameras.length-1;t>=0;t--)if(this.cameras[t].id===e)return this.cameras[t];for(t=this.lights.length-1;t>=0;t--)if(this.lights[t].id===e)return this.lights[t];return null},t.prototype.getNodeByID=function(e){var t=this.getMeshByID(e);if(t)return t;var i=this.getTransformNodeByID(e);if(i)return i;var n=this.getLightByID(e);if(n)return n;var r=this.getCameraByID(e);if(r)return r;var o=this.getBoneByID(e);return o||null},t.prototype.getNodeByName=function(e){var t=this.getMeshByName(e);if(t)return t;var i=this.getTransformNodeByName(e);if(i)return i;var n=this.getLightByName(e);if(n)return n;var r=this.getCameraByName(e);if(r)return r;var o=this.getBoneByName(e);return o||null},t.prototype.getMeshByName=function(e){for(var t=0;t=0;t--)if(this.skeletons[t].id===e)return this.skeletons[t];return null},t.prototype.getSkeletonByUniqueId=function(e){for(var t=0;t0&&0!=(s.layerMask&this.activeCamera.layerMask)&&(s.alwaysSelectAsActiveMesh||s.isInFrustum(this._frustumPlanes))&&(this._activeMeshes.push(s),this.activeCamera._activeMeshes.push(s),a!==s&&a._activate(this._renderId,!1),s._activate(this._renderId,!1)&&(s.isAnInstance||(a._internalAbstractMeshDataInfo._onlyForInstances=!1),a._internalAbstractMeshDataInfo._isActive=!0,this._activeMesh(s,a)),s._postActivate()))}}if(this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this),this.particlesEnabled){this.onBeforeParticlesRenderingObservable.notifyObservers(this);for(var c=0;c0)for(var r=this.getActiveSubMeshCandidates(t),o=r.length,s=0;s1)this.activeCamera.outputRenderTarget._bindFrameBuffer();else{var e=this.activeCamera.outputRenderTarget.getInternalTexture();e?this.getEngine().bindFramebuffer(e):P.a.Error("Camera contains invalid customDefaultRenderTarget")}}else this.getEngine().restoreDefaultFramebuffer()},t.prototype._renderForCamera=function(e,t){if(!e||!e._skipRendering){var i=this._engine;if(this._activeCamera=e,!this.activeCamera)throw new Error("Active camera not set");i.setViewport(this.activeCamera.viewport),this.resetCachedMaterial(),this._renderId++,this.getEngine().getCaps().multiview&&e.outputRenderTarget&&e.outputRenderTarget.getViewCount()>1?this.setTransformMatrix(e._rigCameras[0].getViewMatrix(),e._rigCameras[0].getProjectionMatrix(),e._rigCameras[1].getViewMatrix(),e._rigCameras[1].getProjectionMatrix()):this.updateTransformMatrix(),this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera),this._evaluateActiveMeshes();for(var n=0;n0&&this._renderTargets.concatWithNoDuplicate(e.customRenderTargets),t&&t.customRenderTargets&&t.customRenderTargets.length>0&&this._renderTargets.concatWithNoDuplicate(t.customRenderTargets);for(var s=0,a=this._gatherActiveCameraRenderTargetsStage;s0){r.h.StartPerformanceCounter("Render targets",this._renderTargets.length>0);for(var l=0;l0),this._renderId++}for(var d=0,f=this._cameraDrawRenderTargetStage;d1&&this.getEngine().getCaps().multiview)return this._renderForCamera(e),void this.onAfterRenderCameraObservable.notifyObservers(e);if(e._useMultiviewToSingleView)this._renderMultiviewToSingleView(e);else for(var t=0;t-1&&(n.trigger===x.a.ACTION_OnIntersectionExitTrigger&&n._executeCurrent(y.a.CreateNew(t,void 0,o)),t.actionManager.hasSpecificTrigger(x.a.ACTION_OnIntersectionExitTrigger,function(e){var t=e instanceof d.a?e:e.mesh;return o===t})&&n.trigger!==x.a.ACTION_OnIntersectionExitTrigger||t._intersectionsInProgress.splice(a,1))}}}},t.prototype._advancePhysicsEngineStep=function(e){},t.prototype._animate=function(){},t.prototype.animate=function(){if(this._engine.isDeterministicLockStep()){var e=Math.max(t.MinDeltaTime,Math.min(this._engine.getDeltaTime(),t.MaxDeltaTime))+this._timeAccumulator,i=this.getDeterministicFrameTime(),n=0,r=this._engine.getLockstepMaxSteps(),o=Math.floor(e/60);o=Math.min(o,r);do{this.onBeforeStepObservable.notifyObservers(this),this._animationRatio=.06*i,this._animate(),this.onAfterAnimationsObservable.notifyObservers(this),this._advancePhysicsEngineStep(i),this.onAfterStepObservable.notifyObservers(this),this._currentStepId++,n++,e-=i}while(e>0&&n0)for(var o=0;o0),this._intermediateRendering=!0;for(var u=0;u0),this._intermediateRendering=!1,this._renderId++}this.activeCamera=l,this._bindFrameBuffer(),this.onAfterRenderTargetsRenderObservable.notifyObservers(this);for(var d=0,p=this._beforeClearStage;d0)for(o=0;o0&&this._engine.clear(null,!1,!0,!0),this._processSubCameras(this.activeCameras[o]);else{if(!this.activeCamera)throw new Error("No camera defined");this._processSubCameras(this.activeCamera)}this._checkIntersections();for(var g=0,v=this._afterRenderStage;g-1&&this._engine.scenes.splice(r,1),this._engine.wipeCaches(!0),this._isDisposed=!0},Object.defineProperty(t.prototype,"isDisposed",{get:function(){return this._isDisposed},enumerable:!0,configurable:!0}),t.prototype.clearCachedVertexData=function(){for(var e=0;e-1?(u.a.Error("You're trying to reuse a post process not defined as reusable."),0):(null==t||t<0?this._postProcesses.push(e):null===this._postProcesses[t]?this._postProcesses[t]=e:this._postProcesses.splice(t,0,e),this._cascadePostProcessesToRigCams(),this._postProcesses.indexOf(e))},t.prototype.detachPostProcess=function(e){var t=this._postProcesses.indexOf(e);-1!==t&&(this._postProcesses[t]=null),this._cascadePostProcessesToRigCams()},t.prototype.getWorldMatrix=function(){return this._isSynchronizedViewMatrix()?this._worldMatrix:(this.getViewMatrix(),this._worldMatrix)},t.prototype._getViewMatrix=function(){return c.j.Identity()},t.prototype.getViewMatrix=function(e){return!e&&this._isSynchronizedViewMatrix()?this._computedViewMatrix:(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)},t.prototype.freezeProjectionMatrix=function(e){this._doNotComputeProjectionMatrix=!0,void 0!==e&&(this._projectionMatrix=e)},t.prototype.unfreezeProjectionMatrix=function(){this._doNotComputeProjectionMatrix=!1},t.prototype.getProjectionMatrix=function(e){if(this._doNotComputeProjectionMatrix||!e&&this._isSynchronizedProjectionMatrix())return this._projectionMatrix;this._cache.mode=this.mode,this._cache.minZ=this.minZ,this._cache.maxZ=this.maxZ,this._refreshFrustumPlanes=!0;var i=this.getEngine(),n=this.getScene();if(this.mode===t.PERSPECTIVE_CAMERA)this._cache.fov=this.fov,this._cache.fovMode=this.fovMode,this._cache.aspectRatio=i.getAspectRatio(this),this.minZ<=0&&(this.minZ=.1),n.useRightHandedSystem?c.j.PerspectiveFovRHToRef(this.fov,i.getAspectRatio(this),this.minZ,this.maxZ,this._projectionMatrix,this.fovMode===t.FOVMODE_VERTICAL_FIXED):c.j.PerspectiveFovLHToRef(this.fov,i.getAspectRatio(this),this.minZ,this.maxZ,this._projectionMatrix,this.fovMode===t.FOVMODE_VERTICAL_FIXED);else{var r=i.getRenderWidth()/2,o=i.getRenderHeight()/2;n.useRightHandedSystem?c.j.OrthoOffCenterRHToRef(this.orthoLeft||-r,this.orthoRight||r,this.orthoBottom||-o,this.orthoTop||o,this.minZ,this.maxZ,this._projectionMatrix):c.j.OrthoOffCenterLHToRef(this.orthoLeft||-r,this.orthoRight||r,this.orthoBottom||-o,this.orthoTop||o,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=i.getRenderWidth(),this._cache.renderHeight=i.getRenderHeight()}return this.onProjectionMatrixChangedObservable.notifyObservers(this),this._projectionMatrix},t.prototype.getTransformationMatrix=function(){return this._computedViewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._transformMatrix},t.prototype._updateFrustumPlanes=function(){this._refreshFrustumPlanes&&(this.getTransformationMatrix(),this._frustumPlanes?c.i.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=c.i.GetPlanes(this._transformMatrix),this._refreshFrustumPlanes=!1)},t.prototype.isInFrustum=function(e,t){if(void 0===t&&(t=!1),this._updateFrustumPlanes(),t&&this.rigCameras.length>0){var i=!1;return this.rigCameras.forEach(function(t){t._updateFrustumPlanes(),i=i||e.isInFrustum(t._frustumPlanes)}),i}return e.isInFrustum(this._frustumPlanes)},t.prototype.isCompletelyInFrustum=function(e){return this._updateFrustumPlanes(),e.isCompletelyInFrustum(this._frustumPlanes)},t.prototype.getForwardRay=function(e,t,i){throw void 0===e&&(e=100),d.a.WarnImport("Ray")},t.prototype.dispose=function(i,n){for(void 0===n&&(n=!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 r=this._rigCameras.pop();r&&r.dispose()}if(this._rigPostProcess)this._rigPostProcess.dispose(this),this._rigPostProcess=null,this._postProcesses=[];else if(this.cameraRigMode!==t.RIG_MODE_NONE)this._rigPostProcess=null,this._postProcesses=[];else for(var o=this._postProcesses.length;--o>=0;){var s=this._postProcesses[o];s&&s.dispose(this)}for(o=this.customRenderTargets.length;--o>=0;)this.customRenderTargets[o].dispose();this.customRenderTargets=[],this._activeMeshes.dispose(),e.prototype.dispose.call(this,i,n)},Object.defineProperty(t.prototype,"isLeftCamera",{get:function(){return this._isLeftCamera},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isRightCamera",{get:function(){return this._isRightCamera},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"leftCamera",{get:function(){return this._rigCameras.length<1?null:this._rigCameras[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rightCamera",{get:function(){return this._rigCameras.length<2?null:this._rigCameras[1]},enumerable:!0,configurable:!0}),t.prototype.getLeftTarget=function(){return this._rigCameras.length<1?null:this._rigCameras[0].getTarget()},t.prototype.getRightTarget=function(){return this._rigCameras.length<2?null:this._rigCameras[1].getTarget()},t.prototype.setCameraRigMode=function(e,i){if(this.cameraRigMode!==e){for(;this._rigCameras.length>0;){var n=this._rigCameras.pop();n&&n.dispose()}if(this.cameraRigMode=e,this._cameraRigParams={},this._cameraRigParams.interaxialDistance=i.interaxialDistance||.0637,this._cameraRigParams.stereoHalfAngle=s.h.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==t.RIG_MODE_NONE){var r=this.createRigCamera(this.name+"_L",0);r&&(r._isLeftCamera=!0);var o=this.createRigCamera(this.name+"_R",1);o&&(o._isRightCamera=!0),r&&o&&(this._rigCameras.push(r),this._rigCameras.push(o))}switch(this.cameraRigMode){case t.RIG_MODE_STEREOSCOPIC_ANAGLYPH:t._setStereoscopicAnaglyphRigMode(this);break;case t.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case t.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:case t.RIG_MODE_STEREOSCOPIC_OVERUNDER:t._setStereoscopicRigMode(this);break;case t.RIG_MODE_VR:t._setVRRigMode(this,i);break;case t.RIG_MODE_WEBVR:t._setWebVRRigMode(this,i)}this._cascadePostProcessesToRigCams(),this.update()}},t._setStereoscopicRigMode=function(e){throw"Import Cameras/RigModes/stereoscopicRigMode before using stereoscopic rig mode"},t._setStereoscopicAnaglyphRigMode=function(e){throw"Import Cameras/RigModes/stereoscopicAnaglyphRigMode before using stereoscopic anaglyph rig mode"},t._setVRRigMode=function(e,t){throw"Import Cameras/RigModes/vrRigMode before using VR rig mode"},t._setWebVRRigMode=function(e,t){throw"Import Cameras/RigModes/WebVRRigMode before using Web VR rig mode"},t.prototype._getVRProjectionMatrix=function(){return c.j.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},t.prototype._updateCameraRotationMatrix=function(){},t.prototype._updateWebVRCameraRotationMatrix=function(){},t.prototype._getWebVRProjectionMatrix=function(){return c.j.Identity()},t.prototype._getWebVRViewMatrix=function(){return c.j.Identity()},t.prototype.setCameraRigParameter=function(e,t){this._cameraRigParams||(this._cameraRigParams={}),this._cameraRigParams[e]=t,"interaxialDistance"===e&&(this._cameraRigParams.stereoHalfAngle=s.h.ToRadians(t/.0637))},t.prototype.createRigCamera=function(e,t){return null},t.prototype._updateRigCameras=function(){for(var e=0;ea.b.CollisionsEpsilon&&r.position.addInPlace(r._meshCollisionData._diffPositionForCollisions),i&&r.onCollideObservable.notifyObservers(i),r.onCollisionPositionChangeObservable.notifyObservers(r.position)},r.getScene().addMesh(r),r._resyncLightSources(),r}return n.d(t,e),Object.defineProperty(t,"BILLBOARDMODE_NONE",{get:function(){return u.a.BILLBOARDMODE_NONE},enumerable:!0,configurable:!0}),Object.defineProperty(t,"BILLBOARDMODE_X",{get:function(){return u.a.BILLBOARDMODE_X},enumerable:!0,configurable:!0}),Object.defineProperty(t,"BILLBOARDMODE_Y",{get:function(){return u.a.BILLBOARDMODE_Y},enumerable:!0,configurable:!0}),Object.defineProperty(t,"BILLBOARDMODE_Z",{get:function(){return u.a.BILLBOARDMODE_Z},enumerable:!0,configurable:!0}),Object.defineProperty(t,"BILLBOARDMODE_ALL",{get:function(){return u.a.BILLBOARDMODE_ALL},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"facetNb",{get:function(){return this._internalAbstractMeshDataInfo._facetData.facetNb},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"partitioningSubdivisions",{get:function(){return this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions},set:function(e){this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"partitioningBBoxRatio",{get:function(){return this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio},set:function(e){this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"mustDepthSortFacets",{get:function(){return this._internalAbstractMeshDataInfo._facetData.facetDepthSort},set:function(e){this._internalAbstractMeshDataInfo._facetData.facetDepthSort=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"facetDepthSortFrom",{get:function(){return this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom},set:function(e){this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isFacetDataEnabled",{get:function(){return this._internalAbstractMeshDataInfo._facetData.facetDataEnabled},enumerable:!0,configurable:!0}),t.prototype._updateNonUniformScalingState=function(t){return!!e.prototype._updateNonUniformScalingState.call(this,t)&&(this._markSubMeshesAsMiscDirty(),!0)},Object.defineProperty(t.prototype,"onCollide",{set:function(e){this._meshCollisionData._onCollideObserver&&this.onCollideObservable.remove(this._meshCollisionData._onCollideObserver),this._meshCollisionData._onCollideObserver=this.onCollideObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"onCollisionPositionChange",{set:function(e){this._meshCollisionData._onCollisionPositionChangeObserver&&this.onCollisionPositionChangeObservable.remove(this._meshCollisionData._onCollisionPositionChangeObserver),this._meshCollisionData._onCollisionPositionChangeObserver=this.onCollisionPositionChangeObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"visibility",{get:function(){return this._internalAbstractMeshDataInfo._visibility},set:function(e){this._internalAbstractMeshDataInfo._visibility!==e&&(this._internalAbstractMeshDataInfo._visibility=e,this._markSubMeshesAsMiscDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"material",{get:function(){return this._material},set:function(e){this._material!==e&&(this._material&&this._material.meshMap&&(this._material.meshMap[this.uniqueId]=void 0),this._material=e,e&&e.meshMap&&(e.meshMap[this.uniqueId]=this),this.onMaterialChangedObservable.hasObservers&&this.onMaterialChangedObservable.notifyObservers(this),this.subMeshes&&this._unBindEffect())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"receiveShadows",{get:function(){return this._internalAbstractMeshDataInfo._receiveShadows},set:function(e){this._internalAbstractMeshDataInfo._receiveShadows!==e&&(this._internalAbstractMeshDataInfo._receiveShadows=e,this._markSubMeshesAsLightDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"hasVertexAlpha",{get:function(){return this._internalAbstractMeshDataInfo._hasVertexAlpha},set:function(e){this._internalAbstractMeshDataInfo._hasVertexAlpha!==e&&(this._internalAbstractMeshDataInfo._hasVertexAlpha=e,this._markSubMeshesAsAttributesDirty(),this._markSubMeshesAsMiscDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"useVertexColors",{get:function(){return this._internalAbstractMeshDataInfo._useVertexColors},set:function(e){this._internalAbstractMeshDataInfo._useVertexColors!==e&&(this._internalAbstractMeshDataInfo._useVertexColors=e,this._markSubMeshesAsAttributesDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"computeBonesUsingShaders",{get:function(){return this._internalAbstractMeshDataInfo._computeBonesUsingShaders},set:function(e){this._internalAbstractMeshDataInfo._computeBonesUsingShaders!==e&&(this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"numBoneInfluencers",{get:function(){return this._internalAbstractMeshDataInfo._numBoneInfluencers},set:function(e){this._internalAbstractMeshDataInfo._numBoneInfluencers!==e&&(this._internalAbstractMeshDataInfo._numBoneInfluencers=e,this._markSubMeshesAsAttributesDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"applyFog",{get:function(){return this._internalAbstractMeshDataInfo._applyFog},set:function(e){this._internalAbstractMeshDataInfo._applyFog!==e&&(this._internalAbstractMeshDataInfo._applyFog=e,this._markSubMeshesAsMiscDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"layerMask",{get:function(){return this._internalAbstractMeshDataInfo._layerMask},set:function(e){e!==this._internalAbstractMeshDataInfo._layerMask&&(this._internalAbstractMeshDataInfo._layerMask=e,this._resyncLightSources())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"collisionMask",{get:function(){return this._meshCollisionData._collisionMask},set:function(e){this._meshCollisionData._collisionMask=isNaN(e)?-1:e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"collisionGroup",{get:function(){return this._meshCollisionData._collisionGroup},set:function(e){this._meshCollisionData._collisionGroup=isNaN(e)?-1:e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"lightSources",{get:function(){return this._lightSources},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"_positions",{get:function(){return null},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"skeleton",{get:function(){return this._internalAbstractMeshDataInfo._skeleton},set:function(e){var t=this._internalAbstractMeshDataInfo._skeleton;t&&t.needInitialSkinMatrix&&t._unregisterMeshWithPoseMatrix(this),e&&e.needInitialSkinMatrix&&e._registerMeshWithPoseMatrix(this),this._internalAbstractMeshDataInfo._skeleton=e,this._internalAbstractMeshDataInfo._skeleton||(this._bonesTransformMatrices=null),this._markSubMeshesAsAttributesDirty()},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"AbstractMesh"},t.prototype.toString=function(e){var t="Name: "+this.name+", isInstance: "+("InstancedMesh"!==this.getClassName()?"YES":"NO");t+=", # of submeshes: "+(this.subMeshes?this.subMeshes.length:0);var i=this._internalAbstractMeshDataInfo._skeleton;return i&&(t+=", skeleton: "+i.name),e&&(t+=", billboard mode: "+["NONE","X","Y",null,"Z",null,null,"ALL"][this.billboardMode],t+=", freeze wrld mat: "+(this._isWorldMatrixFrozen||this._waitingData.freezeWorldMatrix?"YES":"NO")),t},t.prototype._getEffectiveParent=function(){return this._masterMesh&&this.billboardMode!==u.a.BILLBOARDMODE_NONE?this._masterMesh:e.prototype._getEffectiveParent.call(this)},t.prototype._getActionManagerForTrigger=function(e,t){if(void 0===t&&(t=!0),this.actionManager&&(t||this.actionManager.isRecursive)){if(!e)return this.actionManager;if(this.actionManager.hasSpecificTrigger(e))return this.actionManager}return this.parent?this.parent._getActionManagerForTrigger(e,!1):null},t.prototype._rebuild=function(){if(this.onRebuildObservable.notifyObservers(this),this._occlusionQuery&&(this._occlusionQuery=null),this.subMeshes)for(var e=0,t=this.subMeshes;e4,a=o?this.getVerticesData(c.b.MatricesIndicesExtraKind):null,l=o?this.getVerticesData(c.b.MatricesWeightsExtraKind):null;this.skeleton.prepare();for(var u=this.skeleton.getTransformMatrices(this),h=s.t.Vector3[0],d=s.t.Matrix[0],f=s.t.Matrix[1],p=0,_=0;_0&&(s.j.FromFloat32ArrayToRefScaled(u,Math.floor(16*i[p+m]),g,f),d.addToSelf(f));if(o)for(m=0;m<4;m++)(g=l[p+m])>0&&(s.j.FromFloat32ArrayToRefScaled(u,Math.floor(16*a[p+m]),g,f),d.addToSelf(f));s.x.TransformCoordinatesFromFloatsToRef(t[_],t[_+1],t[_+2],d,h),h.toArray(t,_),this._positions&&this._positions[_/3].copyFrom(h)}}}return t},t.prototype._updateBoundingInfo=function(){var e=this._effectiveMesh;return this._boundingInfo?this._boundingInfo.update(e.worldMatrixFromCache):this._boundingInfo=new d.a(this.absolutePosition,this.absolutePosition,e.worldMatrixFromCache),this._updateSubMeshesBoundingInfo(e.worldMatrixFromCache),this},t.prototype._updateSubMeshesBoundingInfo=function(e){if(!this.subMeshes)return this;for(var t=this.subMeshes.length,i=0;i1||!n.IsGlobal)&&n.updateBoundingInfo(e)}return this},t.prototype._afterComputeWorldMatrix=function(){this.doNotSyncBoundingInfo||this._updateBoundingInfo()},Object.defineProperty(t.prototype,"_effectiveMesh",{get:function(){return this.skeleton&&this.skeleton.overrideMesh||this},enumerable:!0,configurable:!0}),t.prototype.isInFrustum=function(e){return null!==this._boundingInfo&&this._boundingInfo.isInFrustum(e,this.cullingStrategy)},t.prototype.isCompletelyInFrustum=function(e){return null!==this._boundingInfo&&this._boundingInfo.isCompletelyInFrustum(e)},t.prototype.intersectsMesh=function(e,t,i){if(void 0===t&&(t=!1),!this._boundingInfo||!e._boundingInfo)return!1;if(this._boundingInfo.intersects(e._boundingInfo,t))return!0;if(i)for(var n=0,r=this.getChildMeshes();n1&&!o._checkCollision(e)||this._collideForSubMesh(o,t,e)}return this},t.prototype._checkCollision=function(e){if(!this._boundingInfo||!this._boundingInfo._checkCollision(e))return this;var t=s.t.Matrix[0],i=s.t.Matrix[1];return s.j.ScalingToRef(1/e._radius.x,1/e._radius.y,1/e._radius.z,t),this.worldMatrixFromCache.multiplyToRef(t,i),this._processCollisionsForSubMeshes(e,i),this},t.prototype._generatePointsArray=function(){return!1},t.prototype.intersects=function(e,t,i){var n=new h.a,r="InstancedLinesMesh"===this.getClassName()||"LinesMesh"===this.getClassName()?this.intersectionThreshold:0,o=this._boundingInfo;if(!(this.subMeshes&&o&&e.intersectsSphere(o.boundingSphere,r)&&e.intersectsBox(o.boundingBox,r)))return n;if(!this._generatePointsArray())return n;for(var a=null,c=this._scene.getIntersectingSubMeshCandidates(this,e),l=c.length,u=0;u1)||d.canIntersects(e)){var f=d.intersects(e,this._positions,this.getIndices(),t,i);if(f&&(t||!a||f.distance65535){o=!0;break}e.depthSortedIndices=o?new Uint32Array(i):new Uint16Array(i)}if(e.facetDepthSortFunction=function(e,t){return t.sqDistance-e.sqDistance},!e.facetDepthSortFrom){var u=this.getScene().activeCamera;e.facetDepthSortFrom=u?u.position:s.x.Zero()}e.depthSortedFacets=[];for(var h=0;hs.h?r.maximum.x-r.minimum.x:s.h,e.bbSize.y=r.maximum.y-r.minimum.y>s.h?r.maximum.y-r.minimum.y:s.h,e.bbSize.z=r.maximum.z-r.minimum.z>s.h?r.maximum.z-r.minimum.z:s.h;var f=e.bbSize.x>e.bbSize.y?e.bbSize.x:e.bbSize.y;if(f=f>e.bbSize.z?f:e.bbSize.z,e.subDiv.max=e.partitioningSubdivisions,e.subDiv.X=Math.floor(e.subDiv.max*e.bbSize.x/f),e.subDiv.Y=Math.floor(e.subDiv.max*e.bbSize.y/f),e.subDiv.Z=Math.floor(e.subDiv.max*e.bbSize.z/f),e.subDiv.X=e.subDiv.X<1?1:e.subDiv.X,e.subDiv.Y=e.subDiv.Y<1?1:e.subDiv.Y,e.subDiv.Z=e.subDiv.Z<1?1:e.subDiv.Z,e.facetParameters.facetNormals=this.getFacetLocalNormals(),e.facetParameters.facetPositions=this.getFacetLocalPositions(),e.facetParameters.facetPartitioning=this.getFacetLocalPartitioning(),e.facetParameters.bInfo=r,e.facetParameters.bbSize=e.bbSize,e.facetParameters.subDiv=e.subDiv,e.facetParameters.ratio=this.partitioningBBoxRatio,e.facetParameters.depthSort=e.facetDepthSort,e.facetDepthSort&&e.facetDepthSortEnabled&&(this.computeWorldMatrix(!0),this._worldMatrix.invertToRef(e.invertedMatrix),s.x.TransformCoordinatesToRef(e.facetDepthSortFrom,e.invertedMatrix,e.facetDepthSortOrigin),e.facetParameters.distanceTo=e.facetDepthSortOrigin),e.facetParameters.depthSortedFacets=e.depthSortedFacets,l.a.ComputeNormals(t,i,n,e.facetParameters),e.facetDepthSort&&e.facetDepthSortEnabled){e.depthSortedFacets.sort(e.facetDepthSortFunction);var p=e.depthSortedIndices.length/3|0;for(h=0;hr.subDiv.max||s<0||s>r.subDiv.max||a<0||a>r.subDiv.max?null:r.facetPartitioning[o+r.subDiv.max*s+r.subDiv.max*r.subDiv.max*a]},t.prototype.getClosestFacetAtCoordinates=function(e,t,i,n,r,o){void 0===r&&(r=!1),void 0===o&&(o=!0);var a=this.getWorldMatrix(),c=s.t.Matrix[5];a.invertToRef(c);var l=s.t.Vector3[8];s.x.TransformCoordinatesFromFloatsToRef(e,t,i,c,l);var u=this.getClosestFacetAtLocalCoordinates(l.x,l.y,l.z,n,r,o);return n&&s.x.TransformCoordinatesFromFloatsToRef(n.x,n.y,n.z,a,n),u},t.prototype.getClosestFacetAtLocalCoordinates=function(e,t,i,n,r,o){void 0===r&&(r=!1),void 0===o&&(o=!0);var s=null,a=0,c=0,l=0,u=0,h=0,d=0,f=0,p=0,_=this.getFacetLocalPositions(),m=this.getFacetLocalNormals(),g=this.getFacetsAtLocalCoordinates(e,t,i);if(!g)return null;for(var v,y,b,T=Number.MAX_VALUE,E=T,x=0;x=0||r&&!o&&u<=0)&&(u=y.x*b.x+y.y*b.y+y.z*b.z,h=-(y.x*e+y.y*t+y.z*i-u)/(y.x*y.x+y.y*y.y+y.z*y.z),(E=(a=(d=e+y.x*h)-e)*a+(c=(f=t+y.y*h)-t)*c+(l=(p=i+y.z*h)-i)*l)100&&(this.soft=!0),this._physicsEngine=this._scene.getPhysicsEngine(),this._physicsEngine?(this.object.rotationQuaternion||(this.object.rotation?this.object.rotationQuaternion=o.q.RotationYawPitchRoll(this.object.rotation.y,this.object.rotation.x,this.object.rotation.z):this.object.rotationQuaternion=new o.q),this._options.mass=void 0===i.mass?0:i.mass,this._options.friction=void 0===i.friction?.2:i.friction,this._options.restitution=void 0===i.restitution?.2:i.restitution,this.soft&&(this._options.mass=this._options.mass>0?this._options.mass:1,this._options.pressure=void 0===i.pressure?200:i.pressure,this._options.stiffness=void 0===i.stiffness?1:i.stiffness,this._options.velocityIterations=void 0===i.velocityIterations?20:i.velocityIterations,this._options.positionIterations=void 0===i.positionIterations?20:i.positionIterations,this._options.fixedPoints=void 0===i.fixedPoints?0:i.fixedPoints,this._options.margin=void 0===i.margin?0:i.margin,this._options.damping=void 0===i.damping?0:i.damping,this._options.path=void 0===i.path?null:i.path,this._options.shape=void 0===i.shape?null:i.shape),this._joints=[],!this.object.parent||this._options.ignoreParent?this._init():this.object.parent.physicsImpostor&&n.a.Warn("You must affect impostors to children before affecting impostor to parent.")):n.a.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors."))):n.a.Error("No object was provided. A physics object is obligatory")}return Object.defineProperty(e.prototype,"isDisposed",{get:function(){return this._isDisposed},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"mass",{get:function(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyMass(this):0},set:function(e){this.setMass(e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"friction",{get:function(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyFriction(this):0},set:function(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyFriction(this,e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"restitution",{get:function(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this):0},set:function(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this,e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"pressure",{get:function(){if(!this._physicsEngine)return 0;var e=this._physicsEngine.getPhysicsPlugin();return e.setBodyPressure?e.getBodyPressure(this):0},set:function(e){if(this._physicsEngine){var t=this._physicsEngine.getPhysicsPlugin();t.setBodyPressure&&t.setBodyPressure(this,e)}},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"stiffness",{get:function(){if(!this._physicsEngine)return 0;var e=this._physicsEngine.getPhysicsPlugin();return e.getBodyStiffness?e.getBodyStiffness(this):0},set:function(e){if(this._physicsEngine){var t=this._physicsEngine.getPhysicsPlugin();t.setBodyStiffness&&t.setBodyStiffness(this,e)}},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"velocityIterations",{get:function(){if(!this._physicsEngine)return 0;var e=this._physicsEngine.getPhysicsPlugin();return e.getBodyVelocityIterations?e.getBodyVelocityIterations(this):0},set:function(e){if(this._physicsEngine){var t=this._physicsEngine.getPhysicsPlugin();t.setBodyVelocityIterations&&t.setBodyVelocityIterations(this,e)}},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"positionIterations",{get:function(){if(!this._physicsEngine)return 0;var e=this._physicsEngine.getPhysicsPlugin();return e.getBodyPositionIterations?e.getBodyPositionIterations(this):0},set:function(e){if(this._physicsEngine){var t=this._physicsEngine.getPhysicsPlugin();t.setBodyPositionIterations&&t.setBodyPositionIterations(this,e)}},enumerable:!0,configurable:!0}),e.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))},e.prototype._getPhysicsParent=function(){return this.object.parent instanceof s.a?this.object.parent.physicsImpostor:null},e.prototype.isBodyInitRequired=function(){return this._bodyUpdateRequired||!this._physicsBody&&!this._parent},e.prototype.setScalingUpdated=function(){this.forceUpdate()},e.prototype.forceUpdate=function(){this._init(),this.parent&&!this._options.ignoreParent&&this.parent.forceUpdate()},Object.defineProperty(e.prototype,"physicsBody",{get:function(){return this._parent&&!this._options.ignoreParent?this._parent.physicsBody:this._physicsBody},set:function(e){this._physicsBody&&this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this),this._physicsBody=e,this.resetUpdateFlags()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"parent",{get:function(){return!this._options.ignoreParent&&this._parent?this._parent:null},set:function(e){this._parent=e},enumerable:!0,configurable:!0}),e.prototype.resetUpdateFlags=function(){this._bodyUpdateRequired=!1},e.prototype.getObjectExtendSize=function(){if(this.object.getBoundingInfo){var t=this.object.rotationQuaternion;this.object.rotationQuaternion=e.IDENTITY_QUATERNION,this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0);var i=this.object.getBoundingInfo().boundingBox.extendSizeWorld.scale(2);return this.object.rotationQuaternion=t,this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0),i}return e.DEFAULT_OBJECT_SIZE},e.prototype.getObjectCenter=function(){return this.object.getBoundingInfo?this.object.getBoundingInfo().boundingBox.centerWorld:this.object.position},e.prototype.getParam=function(e){return this._options[e]},e.prototype.setParam=function(e,t){this._options[e]=t,this._bodyUpdateRequired=!0},e.prototype.setMass=function(e){this.getParam("mass")!==e&&this.setParam("mass",e),this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyMass(this,e)},e.prototype.getLinearVelocity=function(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this):o.x.Zero()},e.prototype.setLinearVelocity=function(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this,e)},e.prototype.getAngularVelocity=function(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this):o.x.Zero()},e.prototype.setAngularVelocity=function(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this,e)},e.prototype.executeNativeFunction=function(e){this._physicsEngine&&e(this._physicsEngine.getPhysicsPlugin().world,this.physicsBody)},e.prototype.registerBeforePhysicsStep=function(e){this._onBeforePhysicsStepCallbacks.push(e)},e.prototype.unregisterBeforePhysicsStep=function(e){var t=this._onBeforePhysicsStepCallbacks.indexOf(e);t>-1?this._onBeforePhysicsStepCallbacks.splice(t,1):n.a.Warn("Function to remove was not found")},e.prototype.registerAfterPhysicsStep=function(e){this._onAfterPhysicsStepCallbacks.push(e)},e.prototype.unregisterAfterPhysicsStep=function(e){var t=this._onAfterPhysicsStepCallbacks.indexOf(e);t>-1?this._onAfterPhysicsStepCallbacks.splice(t,1):n.a.Warn("Function to remove was not found")},e.prototype.registerOnPhysicsCollide=function(e,t){var i=e instanceof Array?e:[e];this._onPhysicsCollideCallbacks.push({callback:t,otherImpostors:i})},e.prototype.unregisterOnPhysicsCollide=function(e,t){var i=e instanceof Array?e:[e],r=-1;this._onPhysicsCollideCallbacks.some(function(e,n){if(e.callback===t&&e.otherImpostors.length===i.length){var o=e.otherImpostors.every(function(e){return i.indexOf(e)>-1});return o&&(r=n),o}return!1})?this._onPhysicsCollideCallbacks.splice(r,1):n.a.Warn("Function to remove was not found")},e.prototype.getParentsRotation=function(){var e=this.object.parent;for(this._tmpQuat.copyFromFloats(0,0,0,1);e;)e.rotationQuaternion?this._tmpQuat2.copyFrom(e.rotationQuaternion):o.q.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,e.rotation.z,this._tmpQuat2),this._tmpQuat.multiplyToRef(this._tmpQuat2,this._tmpQuat),e=e.parent;return this._tmpQuat},e.prototype.applyForce=function(e,t){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyForce(this,e,t),this},e.prototype.applyImpulse=function(e,t){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyImpulse(this,e,t),this},e.prototype.createJoint=function(e,t,i){var n=new c.e(t,i);return this.addJoint(e,n),this},e.prototype.addJoint=function(e,t){return this._joints.push({otherImpostor:e,joint:t}),this._physicsEngine&&this._physicsEngine.addJoint(this,e,t),this},e.prototype.addAnchor=function(e,t,i,n,r){if(!this._physicsEngine)return this;var o=this._physicsEngine.getPhysicsPlugin();return o.appendAnchor?(this._physicsEngine&&o.appendAnchor(this,e,t,i,n,r),this):this},e.prototype.addHook=function(e,t,i,n){if(!this._physicsEngine)return this;var r=this._physicsEngine.getPhysicsPlugin();return r.appendAnchor?(this._physicsEngine&&r.appendHook(this,e,t,i,n),this):this},e.prototype.sleep=function(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().sleepBody(this),this},e.prototype.wakeUp=function(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().wakeUpBody(this),this},e.prototype.clone=function(t){return t?new e(t,this.type,this._options,this._scene):null},e.prototype.dispose=function(){var e=this;this._physicsEngine&&(this._joints.forEach(function(t){e._physicsEngine&&e._physicsEngine.removeJoint(e,t.otherImpostor,t.joint)}),this._physicsEngine.removeImpostor(this),this.parent&&this.parent.forceUpdate(),this._isDisposed=!0)},e.prototype.setDeltaPosition=function(e){this._deltaPosition.copyFrom(e)},e.prototype.setDeltaRotation=function(e){this._deltaRotation||(this._deltaRotation=new o.q),this._deltaRotation.copyFrom(e),this._deltaRotationConjugated=this._deltaRotation.conjugate()},e.prototype.getBoxSizeToRef=function(e){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this,e),this},e.prototype.getRadius=function(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getRadius(this):0},e.prototype.syncBoneWithImpostor=function(t,i,n,r,s){var a=e._tmpVecs[0],c=this.object;if(c.rotationQuaternion)if(s){var l=e._tmpQuat;c.rotationQuaternion.multiplyToRef(s,l),t.setRotationQuaternion(l,o.s.WORLD,i)}else t.setRotationQuaternion(c.rotationQuaternion,o.s.WORLD,i);a.x=0,a.y=0,a.z=0,n&&(a.x=n.x,a.y=n.y,a.z=n.z,t.getDirectionToRef(a,i,a),null==r&&(r=n.length()),a.x*=r,a.y*=r,a.z*=r),t.getParent()?(a.addInPlace(c.getAbsolutePosition()),t.setAbsolutePosition(a,i)):(i.setAbsolutePosition(c.getAbsolutePosition()),i.position.x-=a.x,i.position.y-=a.y,i.position.z-=a.z)},e.prototype.syncImpostorWithBone=function(t,i,n,r,s,a){var c=this.object;if(c.rotationQuaternion)if(s){var l=e._tmpQuat;t.getRotationQuaternionToRef(o.s.WORLD,i,l),l.multiplyToRef(s,c.rotationQuaternion)}else t.getRotationQuaternionToRef(o.s.WORLD,i,c.rotationQuaternion);var u=e._tmpVecs[0],h=e._tmpVecs[1];a||((a=e._tmpVecs[2]).x=0,a.y=1,a.z=0),t.getDirectionToRef(a,i,h),t.getAbsolutePositionToRef(i,u),null==r&&n&&(r=n.length()),null!=r&&(u.x+=h.x*r,u.y+=h.y*r,u.z+=h.z*r),c.setAbsolutePosition(u)},e.DEFAULT_OBJECT_SIZE=new o.x(1,1,1),e.IDENTITY_QUATERNION=o.q.Identity(),e._tmpVecs=r.a.BuildArray(3,o.x.Zero),e._tmpQuat=o.q.Identity(),e.NoImpostor=0,e.SphereImpostor=1,e.BoxImpostor=2,e.PlaneImpostor=3,e.MeshImpostor=4,e.CylinderImpostor=7,e.ParticleImpostor=8,e.HeightmapImpostor=9,e.ConvexHullImpostor=10,e.RopeImpostor=101,e.ClothImpostor=102,e.SoftbodyImpostor=103,e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return r}),i.d(t,"b",function(){return o});var n=i(1),r=function(){function e(t){this.length=0,this.data=new Array(t),this._id=e._GlobalId++}return e.prototype.push=function(e){this.data[this.length++]=e,this.length>this.data.length&&(this.data.length*=2)},e.prototype.forEach=function(e){for(var t=0;tthis.data.length&&(this.data.length=2*(this.length+e.length));for(var t=0;t=this.length?-1:t},e.prototype.contains=function(e){return-1!==this.indexOf(e)},e._GlobalId=0,e}(),o=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t._duplicateId=0,t}return n.d(t,e),t.prototype.push=function(t){e.prototype.push.call(this,t),t.__smartArrayFlags||(t.__smartArrayFlags={}),t.__smartArrayFlags[this._id]=this._duplicateId},t.prototype.pushNoDuplicate=function(e){return(!e.__smartArrayFlags||e.__smartArrayFlags[this._id]!==this._duplicateId)&&(this.push(e),!0)},t.prototype.reset=function(){e.prototype.reset.call(this),this._duplicateId++},t.prototype.concatWithNoDuplicate=function(e){if(0!==e.length){this.length+e.length>this.data.length&&(this.data.length=2*(this.length+e.length));for(var t=0;t0,o.REFLECTIONOVERALPHA=this._useReflectionOverAlpha,o.INVERTCUBICMAP=this._reflectionTexture.coordinatesMode===p.a.INVCUBIC_MODE,o.REFLECTIONMAP_3D=this._reflectionTexture.isCube,this._reflectionTexture.coordinatesMode){case p.a.EXPLICIT_MODE:o.setReflectionMode("REFLECTIONMAP_EXPLICIT");break;case p.a.PLANAR_MODE:o.setReflectionMode("REFLECTIONMAP_PLANAR");break;case p.a.PROJECTION_MODE:o.setReflectionMode("REFLECTIONMAP_PROJECTION");break;case p.a.SKYBOX_MODE:o.setReflectionMode("REFLECTIONMAP_SKYBOX"),o.REFLECTIONMAP_SKYBOX_TRANSFORMED=!this._reflectionTexture.getReflectionTextureMatrix().isIdentity();break;case p.a.SPHERICAL_MODE:o.setReflectionMode("REFLECTIONMAP_SPHERICAL");break;case p.a.EQUIRECTANGULAR_MODE:o.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");break;case p.a.FIXED_EQUIRECTANGULAR_MODE:o.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");break;case p.a.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:o.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");break;case p.a.CUBIC_MODE:case p.a.INVCUBIC_MODE:default:o.setReflectionMode("REFLECTIONMAP_CUBIC")}o.USE_LOCAL_REFLECTIONMAP_CUBIC=!!this._reflectionTexture.boundingBoxSize}else o.REFLECTION=!1;if(this._emissiveTexture&&t.EmissiveTextureEnabled){if(!this._emissiveTexture.isReadyOrNotBlocking())return!1;f.a.PrepareDefinesForMergedUV(this._emissiveTexture,o,"EMISSIVE")}else o.EMISSIVE=!1;if(this._lightmapTexture&&t.LightmapTextureEnabled){if(!this._lightmapTexture.isReadyOrNotBlocking())return!1;f.a.PrepareDefinesForMergedUV(this._lightmapTexture,o,"LIGHTMAP"),o.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap}else o.LIGHTMAP=!1;if(this._specularTexture&&t.SpecularTextureEnabled){if(!this._specularTexture.isReadyOrNotBlocking())return!1;f.a.PrepareDefinesForMergedUV(this._specularTexture,o,"SPECULAR"),o.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha}else o.SPECULAR=!1;if(r.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&t.BumpTextureEnabled){if(!this._bumpTexture.isReady())return!1;f.a.PrepareDefinesForMergedUV(this._bumpTexture,o,"BUMP"),o.PARALLAX=this._useParallax,o.PARALLAXOCCLUSION=this._useParallaxOcclusion,o.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap}else o.BUMP=!1;if(this._refractionTexture&&t.RefractionTextureEnabled){if(!this._refractionTexture.isReadyOrNotBlocking())return!1;o._needUVs=!0,o.REFRACTION=!0,o.REFRACTIONMAP_3D=this._refractionTexture.isCube}else o.REFRACTION=!1;o.TWOSIDEDLIGHTING=!this._backFaceCulling&&this._twoSidedLighting}else o.DIFFUSE=!1,o.AMBIENT=!1,o.OPACITY=!1,o.REFLECTION=!1,o.EMISSIVE=!1,o.LIGHTMAP=!1,o.BUMP=!1,o.REFRACTION=!1;o.ALPHAFROMDIFFUSE=this._shouldUseAlphaFromDiffuseTexture(),o.EMISSIVEASILLUMINATION=this._useEmissiveAsIllumination,o.LINKEMISSIVEWITHDIFFUSE=this._linkEmissiveWithDiffuse,o.SPECULAROVERALPHA=this._useSpecularOverAlpha,o.PREMULTIPLYALPHA=this.alphaMode===x.a.ALPHA_PREMULTIPLIED||this.alphaMode===x.a.ALPHA_PREMULTIPLIED_PORTERDUFF}if(o._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(o),o.IS_REFLECTION_LINEAR=null!=this.reflectionTexture&&!this.reflectionTexture.gammaSpace,o.IS_REFRACTION_LINEAR=null!=this.refractionTexture&&!this.refractionTexture.gammaSpace}if(o._areFresnelDirty&&(t.FresnelEnabled?(this._diffuseFresnelParameters||this._opacityFresnelParameters||this._emissiveFresnelParameters||this._refractionFresnelParameters||this._reflectionFresnelParameters)&&(o.DIFFUSEFRESNEL=this._diffuseFresnelParameters&&this._diffuseFresnelParameters.isEnabled,o.OPACITYFRESNEL=this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled,o.REFLECTIONFRESNEL=this._reflectionFresnelParameters&&this._reflectionFresnelParameters.isEnabled,o.REFLECTIONFRESNELFROMSPECULAR=this._useReflectionFresnelFromSpecular,o.REFRACTIONFRESNEL=this._refractionFresnelParameters&&this._refractionFresnelParameters.isEnabled,o.EMISSIVEFRESNEL=this._emissiveFresnelParameters&&this._emissiveFresnelParameters.isEnabled,o._needNormals=!0,o.FRESNEL=!0):o.FRESNEL=!1),f.a.PrepareDefinesForMisc(e,r,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),o),f.a.PrepareDefinesForAttributes(e,o,!0,!0,!0),f.a.PrepareDefinesForFrameBoundValues(r,s,o,n),o.isDirty){o.markAsProcessed();var a=new u.c;o.REFLECTION&&a.addFallback(0,"REFLECTION"),o.SPECULAR&&a.addFallback(0,"SPECULAR"),o.BUMP&&a.addFallback(0,"BUMP"),o.PARALLAX&&a.addFallback(1,"PARALLAX"),o.PARALLAXOCCLUSION&&a.addFallback(0,"PARALLAXOCCLUSION"),o.SPECULAROVERALPHA&&a.addFallback(0,"SPECULAROVERALPHA"),o.FOG&&a.addFallback(1,"FOG"),o.POINTSIZE&&a.addFallback(0,"POINTSIZE"),o.LOGARITHMICDEPTH&&a.addFallback(0,"LOGARITHMICDEPTH"),f.a.HandleFallbacksForShadows(o,a,this._maxSimultaneousLights),o.SPECULARTERM&&a.addFallback(0,"SPECULARTERM"),o.DIFFUSEFRESNEL&&a.addFallback(1,"DIFFUSEFRESNEL"),o.OPACITYFRESNEL&&a.addFallback(2,"OPACITYFRESNEL"),o.REFLECTIONFRESNEL&&a.addFallback(3,"REFLECTIONFRESNEL"),o.EMISSIVEFRESNEL&&a.addFallback(4,"EMISSIVEFRESNEL"),o.FRESNEL&&a.addFallback(4,"FRESNEL"),o.MULTIVIEW&&a.addFallback(0,"MULTIVIEW");var h=[c.b.PositionKind];o.NORMAL&&h.push(c.b.NormalKind),o.UV1&&h.push(c.b.UVKind),o.UV2&&h.push(c.b.UV2Kind),o.VERTEXCOLOR&&h.push(c.b.ColorKind),f.a.PrepareAttributesForBones(h,e,o,a),f.a.PrepareAttributesForInstances(h,o),f.a.PrepareAttributesForMorphTargets(h,e,o);var d="default",_=["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","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"],m=["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler","boneSampler"],g=["Material","Scene"];l.a&&(l.a.PrepareUniforms(_,o),l.a.PrepareSamplers(m,o)),f.a.PrepareUniformsAndSamplersList({uniformsNames:_,uniformBuffersNames:g,samplers:m,defines:o,maxSimultaneousLights:this._maxSimultaneousLights}),this.customShaderNameResolve&&(d=this.customShaderNameResolve(d,_,g,m,o));var v=o.toString(),y=i.effect,b=r.getEngine().createEffect(d,{attributes:h,uniformsNames:_,uniformBuffersNames:g,samplers:m,defines:v,fallbacks:a,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:o.NUM_MORPH_INFLUENCERS}},s);b&&(this.allowShaderHotSwapping&&y&&!b.isReady()?(b=y,o.markAsUnprocessed()):(r.resetCachedMaterial(),i.setEffect(b,o),this.buildUniformLayout()))}return!(!i.effect||!i.effect.isReady())&&(o._renderId=r.getRenderId(),this._wasPreviouslyReady=!0,!0)},t.prototype.buildUniformLayout=function(){var e=this._uniformBuffer;e.addUniform("diffuseLeftColor",4),e.addUniform("diffuseRightColor",4),e.addUniform("opacityParts",4),e.addUniform("reflectionLeftColor",4),e.addUniform("reflectionRightColor",4),e.addUniform("refractionLeftColor",4),e.addUniform("refractionRightColor",4),e.addUniform("emissiveLeftColor",4),e.addUniform("emissiveRightColor",4),e.addUniform("vDiffuseInfos",2),e.addUniform("vAmbientInfos",2),e.addUniform("vOpacityInfos",2),e.addUniform("vReflectionInfos",2),e.addUniform("vReflectionPosition",3),e.addUniform("vReflectionSize",3),e.addUniform("vEmissiveInfos",2),e.addUniform("vLightmapInfos",2),e.addUniform("vSpecularInfos",2),e.addUniform("vBumpInfos",3),e.addUniform("diffuseMatrix",16),e.addUniform("ambientMatrix",16),e.addUniform("opacityMatrix",16),e.addUniform("reflectionMatrix",16),e.addUniform("emissiveMatrix",16),e.addUniform("lightmapMatrix",16),e.addUniform("specularMatrix",16),e.addUniform("bumpMatrix",16),e.addUniform("vTangentSpaceParams",2),e.addUniform("pointSize",1),e.addUniform("refractionMatrix",16),e.addUniform("vRefractionInfos",4),e.addUniform("vSpecularColor",4),e.addUniform("vEmissiveColor",3),e.addUniform("visibility",1),e.addUniform("vDiffuseColor",4),e.create()},t.prototype.unbind=function(){if(this._activeEffect){var t=!1;this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&(this._activeEffect.setTexture("reflection2DSampler",null),t=!0),this._refractionTexture&&this._refractionTexture.isRenderTarget&&(this._activeEffect.setTexture("refraction2DSampler",null),t=!0),t&&this._markAllSubMeshesAsTexturesDirty()}e.prototype.unbind.call(this)},t.prototype.bindForSubMesh=function(e,i,n){var r=this.getScene(),o=n._materialDefines;if(o){var c=n.effect;if(c){this._activeEffect=c,o.INSTANCES||this.bindOnlyWorldMatrix(e),o.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));var l=this._mustRebind(r,c,i.visibility);f.a.BindBonesParameters(i,c);var u=this._uniformBuffer;if(l){if(u.bindToEffect(c,"Material"),this.bindViewProjection(c),!u.useUbo||!this.isFrozen||!u.isSync){if(t.FresnelEnabled&&o.FRESNEL&&(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled&&(u.updateColor4("diffuseLeftColor",this.diffuseFresnelParameters.leftColor,this.diffuseFresnelParameters.power),u.updateColor4("diffuseRightColor",this.diffuseFresnelParameters.rightColor,this.diffuseFresnelParameters.bias)),this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&u.updateColor4("opacityParts",new a.e(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),this.opacityFresnelParameters.power),this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(u.updateColor4("reflectionLeftColor",this.reflectionFresnelParameters.leftColor,this.reflectionFresnelParameters.power),u.updateColor4("reflectionRightColor",this.reflectionFresnelParameters.rightColor,this.reflectionFresnelParameters.bias)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(u.updateColor4("refractionLeftColor",this.refractionFresnelParameters.leftColor,this.refractionFresnelParameters.power),u.updateColor4("refractionRightColor",this.refractionFresnelParameters.rightColor,this.refractionFresnelParameters.bias)),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(u.updateColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),u.updateColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))),r.texturesEnabled){if(this._diffuseTexture&&t.DiffuseTextureEnabled&&(u.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),f.a.BindTextureMatrix(this._diffuseTexture,u,"diffuse"),this._diffuseTexture.hasAlpha&&c.setFloat("alphaCutOff",this.alphaCutOff)),this._ambientTexture&&t.AmbientTextureEnabled&&(u.updateFloat2("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level),f.a.BindTextureMatrix(this._ambientTexture,u,"ambient")),this._opacityTexture&&t.OpacityTextureEnabled&&(u.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),f.a.BindTextureMatrix(this._opacityTexture,u,"opacity")),this._reflectionTexture&&t.ReflectionTextureEnabled&&(u.updateFloat2("vReflectionInfos",this._reflectionTexture.level,this.roughness),u.updateMatrix("reflectionMatrix",this._reflectionTexture.getReflectionTextureMatrix()),this._reflectionTexture.boundingBoxSize)){var h=this._reflectionTexture;u.updateVector3("vReflectionPosition",h.boundingBoxPosition),u.updateVector3("vReflectionSize",h.boundingBoxSize)}if(this._emissiveTexture&&t.EmissiveTextureEnabled&&(u.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),f.a.BindTextureMatrix(this._emissiveTexture,u,"emissive")),this._lightmapTexture&&t.LightmapTextureEnabled&&(u.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),f.a.BindTextureMatrix(this._lightmapTexture,u,"lightmap")),this._specularTexture&&t.SpecularTextureEnabled&&(u.updateFloat2("vSpecularInfos",this._specularTexture.coordinatesIndex,this._specularTexture.level),f.a.BindTextureMatrix(this._specularTexture,u,"specular")),this._bumpTexture&&r.getEngine().getCaps().standardDerivatives&&t.BumpTextureEnabled&&(u.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,1/this._bumpTexture.level,this.parallaxScaleBias),f.a.BindTextureMatrix(this._bumpTexture,u,"bump"),r._mirroredCameraPosition?u.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):u.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),this._refractionTexture&&t.RefractionTextureEnabled){var d=1;this._refractionTexture.isCube||(u.updateMatrix("refractionMatrix",this._refractionTexture.getReflectionTextureMatrix()),this._refractionTexture.depth&&(d=this._refractionTexture.depth)),u.updateFloat4("vRefractionInfos",this._refractionTexture.level,this.indexOfRefraction,d,this.invertRefractionY?-1:1)}}this.pointsCloud&&u.updateFloat("pointSize",this.pointSize),o.SPECULARTERM&&u.updateColor4("vSpecularColor",this.specularColor,this.specularPower),u.updateColor3("vEmissiveColor",t.EmissiveTextureEnabled?this.emissiveColor:a.e.BlackReadOnly),u.updateFloat("visibility",i.visibility),u.updateColor4("vDiffuseColor",this.diffuseColor,this.alpha)}if(r.texturesEnabled&&(this._diffuseTexture&&t.DiffuseTextureEnabled&&c.setTexture("diffuseSampler",this._diffuseTexture),this._ambientTexture&&t.AmbientTextureEnabled&&c.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&t.OpacityTextureEnabled&&c.setTexture("opacitySampler",this._opacityTexture),this._reflectionTexture&&t.ReflectionTextureEnabled&&(this._reflectionTexture.isCube?c.setTexture("reflectionCubeSampler",this._reflectionTexture):c.setTexture("reflection2DSampler",this._reflectionTexture)),this._emissiveTexture&&t.EmissiveTextureEnabled&&c.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&t.LightmapTextureEnabled&&c.setTexture("lightmapSampler",this._lightmapTexture),this._specularTexture&&t.SpecularTextureEnabled&&c.setTexture("specularSampler",this._specularTexture),this._bumpTexture&&r.getEngine().getCaps().standardDerivatives&&t.BumpTextureEnabled&&c.setTexture("bumpSampler",this._bumpTexture),this._refractionTexture&&t.RefractionTextureEnabled)){d=1;this._refractionTexture.isCube?c.setTexture("refractionCubeSampler",this._refractionTexture):c.setTexture("refraction2DSampler",this._refractionTexture)}f.a.BindClipPlane(c,r),r.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),f.a.BindEyePosition(c,r),c.setColor3("vAmbientColor",this._globalAmbientColor)}!l&&this.isFrozen||(r.lightsEnabled&&!this._disableLighting&&f.a.BindLights(r,i,c,o,this._maxSimultaneousLights),(r.fogEnabled&&i.applyFog&&r.fogMode!==s.a.FOGMODE_NONE||this._reflectionTexture||this._refractionTexture)&&this.bindView(c),f.a.BindFogParameters(r,i,c),o.NUM_MORPH_INFLUENCERS&&f.a.BindMorphTargetParameters(i,c),f.a.BindLogDepth(o,c,r),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect)),u.update(),this._afterBind(i,this._activeEffect)}}},t.prototype.getAnimatables=function(){var e=[];return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._specularTexture&&this._specularTexture.animations&&this._specularTexture.animations.length>0&&e.push(this._specularTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture),e},t.prototype.getActiveTextures=function(){var t=e.prototype.getActiveTextures.call(this);return this._diffuseTexture&&t.push(this._diffuseTexture),this._ambientTexture&&t.push(this._ambientTexture),this._opacityTexture&&t.push(this._opacityTexture),this._reflectionTexture&&t.push(this._reflectionTexture),this._emissiveTexture&&t.push(this._emissiveTexture),this._specularTexture&&t.push(this._specularTexture),this._bumpTexture&&t.push(this._bumpTexture),this._lightmapTexture&&t.push(this._lightmapTexture),this._refractionTexture&&t.push(this._refractionTexture),t},t.prototype.hasTexture=function(t){return!!e.prototype.hasTexture.call(this,t)||(this._diffuseTexture===t||(this._ambientTexture===t||(this._opacityTexture===t||(this._reflectionTexture===t||(this._emissiveTexture===t||(this._specularTexture===t||(this._bumpTexture===t||(this._lightmapTexture===t||this._refractionTexture===t))))))))},t.prototype.dispose=function(t,i){i&&(this._diffuseTexture&&this._diffuseTexture.dispose(),this._ambientTexture&&this._ambientTexture.dispose(),this._opacityTexture&&this._opacityTexture.dispose(),this._reflectionTexture&&this._reflectionTexture.dispose(),this._emissiveTexture&&this._emissiveTexture.dispose(),this._specularTexture&&this._specularTexture.dispose(),this._bumpTexture&&this._bumpTexture.dispose(),this._lightmapTexture&&this._lightmapTexture.dispose(),this._refractionTexture&&this._refractionTexture.dispose()),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e.prototype.dispose.call(this,t,i)},t.prototype.clone=function(e){var i=this,n=r.a.Clone(function(){return new t(e,i.getScene())},this);return n.name=e,n.id=e,n},t.prototype.serialize=function(){return r.a.Serialize(this)},t.Parse=function(e,i,n){return r.a.Parse(function(){return new t(e.name,i)},e,i,n)},Object.defineProperty(t,"DiffuseTextureEnabled",{get:function(){return m.a.DiffuseTextureEnabled},set:function(e){m.a.DiffuseTextureEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(t,"AmbientTextureEnabled",{get:function(){return m.a.AmbientTextureEnabled},set:function(e){m.a.AmbientTextureEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(t,"OpacityTextureEnabled",{get:function(){return m.a.OpacityTextureEnabled},set:function(e){m.a.OpacityTextureEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(t,"ReflectionTextureEnabled",{get:function(){return m.a.ReflectionTextureEnabled},set:function(e){m.a.ReflectionTextureEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(t,"EmissiveTextureEnabled",{get:function(){return m.a.EmissiveTextureEnabled},set:function(e){m.a.EmissiveTextureEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(t,"SpecularTextureEnabled",{get:function(){return m.a.SpecularTextureEnabled},set:function(e){m.a.SpecularTextureEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(t,"BumpTextureEnabled",{get:function(){return m.a.BumpTextureEnabled},set:function(e){m.a.BumpTextureEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(t,"LightmapTextureEnabled",{get:function(){return m.a.LightmapTextureEnabled},set:function(e){m.a.LightmapTextureEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(t,"RefractionTextureEnabled",{get:function(){return m.a.RefractionTextureEnabled},set:function(e){m.a.RefractionTextureEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(t,"ColorGradingTextureEnabled",{get:function(){return m.a.ColorGradingTextureEnabled},set:function(e){m.a.ColorGradingTextureEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(t,"FresnelEnabled",{get:function(){return m.a.FresnelEnabled},set:function(e){m.a.FresnelEnabled=e},enumerable:!0,configurable:!0}),n.c([Object(r.m)("diffuseTexture")],t.prototype,"_diffuseTexture",void 0),n.c([Object(r.b)("_markAllSubMeshesAsTexturesAndMiscDirty")],t.prototype,"diffuseTexture",void 0),n.c([Object(r.m)("ambientTexture")],t.prototype,"_ambientTexture",void 0),n.c([Object(r.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"ambientTexture",void 0),n.c([Object(r.m)("opacityTexture")],t.prototype,"_opacityTexture",void 0),n.c([Object(r.b)("_markAllSubMeshesAsTexturesAndMiscDirty")],t.prototype,"opacityTexture",void 0),n.c([Object(r.m)("reflectionTexture")],t.prototype,"_reflectionTexture",void 0),n.c([Object(r.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"reflectionTexture",void 0),n.c([Object(r.m)("emissiveTexture")],t.prototype,"_emissiveTexture",void 0),n.c([Object(r.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"emissiveTexture",void 0),n.c([Object(r.m)("specularTexture")],t.prototype,"_specularTexture",void 0),n.c([Object(r.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"specularTexture",void 0),n.c([Object(r.m)("bumpTexture")],t.prototype,"_bumpTexture",void 0),n.c([Object(r.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"bumpTexture",void 0),n.c([Object(r.m)("lightmapTexture")],t.prototype,"_lightmapTexture",void 0),n.c([Object(r.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"lightmapTexture",void 0),n.c([Object(r.m)("refractionTexture")],t.prototype,"_refractionTexture",void 0),n.c([Object(r.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"refractionTexture",void 0),n.c([Object(r.e)("ambient")],t.prototype,"ambientColor",void 0),n.c([Object(r.e)("diffuse")],t.prototype,"diffuseColor",void 0),n.c([Object(r.e)("specular")],t.prototype,"specularColor",void 0),n.c([Object(r.e)("emissive")],t.prototype,"emissiveColor",void 0),n.c([Object(r.c)()],t.prototype,"specularPower",void 0),n.c([Object(r.c)("useAlphaFromDiffuseTexture")],t.prototype,"_useAlphaFromDiffuseTexture",void 0),n.c([Object(r.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useAlphaFromDiffuseTexture",void 0),n.c([Object(r.c)("useEmissiveAsIllumination")],t.prototype,"_useEmissiveAsIllumination",void 0),n.c([Object(r.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useEmissiveAsIllumination",void 0),n.c([Object(r.c)("linkEmissiveWithDiffuse")],t.prototype,"_linkEmissiveWithDiffuse",void 0),n.c([Object(r.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"linkEmissiveWithDiffuse",void 0),n.c([Object(r.c)("useSpecularOverAlpha")],t.prototype,"_useSpecularOverAlpha",void 0),n.c([Object(r.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useSpecularOverAlpha",void 0),n.c([Object(r.c)("useReflectionOverAlpha")],t.prototype,"_useReflectionOverAlpha",void 0),n.c([Object(r.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useReflectionOverAlpha",void 0),n.c([Object(r.c)("disableLighting")],t.prototype,"_disableLighting",void 0),n.c([Object(r.b)("_markAllSubMeshesAsLightsDirty")],t.prototype,"disableLighting",void 0),n.c([Object(r.c)("useObjectSpaceNormalMap")],t.prototype,"_useObjectSpaceNormalMap",void 0),n.c([Object(r.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useObjectSpaceNormalMap",void 0),n.c([Object(r.c)("useParallax")],t.prototype,"_useParallax",void 0),n.c([Object(r.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useParallax",void 0),n.c([Object(r.c)("useParallaxOcclusion")],t.prototype,"_useParallaxOcclusion",void 0),n.c([Object(r.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useParallaxOcclusion",void 0),n.c([Object(r.c)()],t.prototype,"parallaxScaleBias",void 0),n.c([Object(r.c)("roughness")],t.prototype,"_roughness",void 0),n.c([Object(r.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"roughness",void 0),n.c([Object(r.c)()],t.prototype,"indexOfRefraction",void 0),n.c([Object(r.c)()],t.prototype,"invertRefractionY",void 0),n.c([Object(r.c)()],t.prototype,"alphaCutOff",void 0),n.c([Object(r.c)("useLightmapAsShadowmap")],t.prototype,"_useLightmapAsShadowmap",void 0),n.c([Object(r.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useLightmapAsShadowmap",void 0),n.c([Object(r.h)("diffuseFresnelParameters")],t.prototype,"_diffuseFresnelParameters",void 0),n.c([Object(r.b)("_markAllSubMeshesAsFresnelDirty")],t.prototype,"diffuseFresnelParameters",void 0),n.c([Object(r.h)("opacityFresnelParameters")],t.prototype,"_opacityFresnelParameters",void 0),n.c([Object(r.b)("_markAllSubMeshesAsFresnelAndMiscDirty")],t.prototype,"opacityFresnelParameters",void 0),n.c([Object(r.h)("reflectionFresnelParameters")],t.prototype,"_reflectionFresnelParameters",void 0),n.c([Object(r.b)("_markAllSubMeshesAsFresnelDirty")],t.prototype,"reflectionFresnelParameters",void 0),n.c([Object(r.h)("refractionFresnelParameters")],t.prototype,"_refractionFresnelParameters",void 0),n.c([Object(r.b)("_markAllSubMeshesAsFresnelDirty")],t.prototype,"refractionFresnelParameters",void 0),n.c([Object(r.h)("emissiveFresnelParameters")],t.prototype,"_emissiveFresnelParameters",void 0),n.c([Object(r.b)("_markAllSubMeshesAsFresnelDirty")],t.prototype,"emissiveFresnelParameters",void 0),n.c([Object(r.c)("useReflectionFresnelFromSpecular")],t.prototype,"_useReflectionFresnelFromSpecular",void 0),n.c([Object(r.b)("_markAllSubMeshesAsFresnelDirty")],t.prototype,"useReflectionFresnelFromSpecular",void 0),n.c([Object(r.c)("useGlossinessFromSpecularMapAlpha")],t.prototype,"_useGlossinessFromSpecularMapAlpha",void 0),n.c([Object(r.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useGlossinessFromSpecularMapAlpha",void 0),n.c([Object(r.c)("maxSimultaneousLights")],t.prototype,"_maxSimultaneousLights",void 0),n.c([Object(r.b)("_markAllSubMeshesAsLightsDirty")],t.prototype,"maxSimultaneousLights",void 0),n.c([Object(r.c)("invertNormalMapX")],t.prototype,"_invertNormalMapX",void 0),n.c([Object(r.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"invertNormalMapX",void 0),n.c([Object(r.c)("invertNormalMapY")],t.prototype,"_invertNormalMapY",void 0),n.c([Object(r.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"invertNormalMapY",void 0),n.c([Object(r.c)("twoSidedLighting")],t.prototype,"_twoSidedLighting",void 0),n.c([Object(r.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"twoSidedLighting",void 0),n.c([Object(r.c)()],t.prototype,"useLogarithmicDepth",null),t}(d.a);_.a.RegisteredTypes["BABYLON.StandardMaterial"]=P,s.a.DefaultMaterialFactory=function(e){return new P("default material",e)}},function(e,t,i){"use strict";i.d(t,"a",function(){return n});var n=function(){function e(){this.rootNodes=new Array,this.cameras=new Array,this.lights=new Array,this.meshes=new Array,this.skeletons=new Array,this.particleSystems=new Array,this.animations=[],this.animationGroups=new Array,this.multiMaterials=new Array,this.materials=new Array,this.morphTargetManagers=new Array,this.geometries=new Array,this.transformNodes=new Array,this.actionManagers=new Array,this.textures=new Array,this.environmentTexture=null}return e.AddParser=function(e,t){this._BabylonFileParsers[e]=t},e.GetParser=function(e){return this._BabylonFileParsers[e]?this._BabylonFileParsers[e]:null},e.AddIndividualParser=function(e,t){this._IndividualBabylonFileParsers[e]=t},e.GetIndividualParser=function(e){return this._IndividualBabylonFileParsers[e]?this._IndividualBabylonFileParsers[e]:null},e.Parse=function(e,t,i,n){for(var r in this._BabylonFileParsers)this._BabylonFileParsers.hasOwnProperty(r)&&this._BabylonFileParsers[r](e,t,i,n)},e._BabylonFileParsers={},e._IndividualBabylonFileParsers={},e}()},function(e,t,i){"use strict";i.d(t,"b",function(){return u}),i.d(t,"a",function(){return h});var n=i(1),r=i(2),o=i(9),s=i(11),a=i(0),c=i(59),l=i(94),u=function(e){function t(){var t=e.call(this)||this;return t.IMAGEPROCESSING=!1,t.VIGNETTE=!1,t.VIGNETTEBLENDMODEMULTIPLY=!1,t.VIGNETTEBLENDMODEOPAQUE=!1,t.TONEMAPPING=!1,t.TONEMAPPING_ACES=!1,t.CONTRAST=!1,t.COLORCURVES=!1,t.COLORGRADING=!1,t.COLORGRADING3D=!1,t.SAMPLER3DGREENDEPTH=!1,t.SAMPLER3DBGRMAP=!1,t.IMAGEPROCESSINGPOSTPROCESS=!1,t.EXPOSURE=!1,t.rebuild(),t}return n.d(t,e),t}(c.a),h=function(){function e(){this.colorCurves=new l.a,this._colorCurvesEnabled=!1,this._colorGradingEnabled=!1,this._colorGradingWithGreenDepth=!0,this._colorGradingBGR=!0,this._exposure=1,this._toneMappingEnabled=!1,this._toneMappingType=e.TONEMAPPING_STANDARD,this._contrast=1,this.vignetteStretch=0,this.vignetteCentreX=0,this.vignetteCentreY=0,this.vignetteWeight=1.5,this.vignetteColor=new a.f(0,0,0,0),this.vignetteCameraFov=.5,this._vignetteBlendMode=e.VIGNETTEMODE_MULTIPLY,this._vignetteEnabled=!1,this._applyByPostProcess=!1,this._isEnabled=!0,this.onUpdateParameters=new o.c}return Object.defineProperty(e.prototype,"colorCurvesEnabled",{get:function(){return this._colorCurvesEnabled},set:function(e){this._colorCurvesEnabled!==e&&(this._colorCurvesEnabled=e,this._updateParameters())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"colorGradingTexture",{get:function(){return this._colorGradingTexture},set:function(e){this._colorGradingTexture!==e&&(this._colorGradingTexture=e,this._updateParameters())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"colorGradingEnabled",{get:function(){return this._colorGradingEnabled},set:function(e){this._colorGradingEnabled!==e&&(this._colorGradingEnabled=e,this._updateParameters())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"colorGradingWithGreenDepth",{get:function(){return this._colorGradingWithGreenDepth},set:function(e){this._colorGradingWithGreenDepth!==e&&(this._colorGradingWithGreenDepth=e,this._updateParameters())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"colorGradingBGR",{get:function(){return this._colorGradingBGR},set:function(e){this._colorGradingBGR!==e&&(this._colorGradingBGR=e,this._updateParameters())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"exposure",{get:function(){return this._exposure},set:function(e){this._exposure!==e&&(this._exposure=e,this._updateParameters())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"toneMappingEnabled",{get:function(){return this._toneMappingEnabled},set:function(e){this._toneMappingEnabled!==e&&(this._toneMappingEnabled=e,this._updateParameters())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"toneMappingType",{get:function(){return this._toneMappingType},set:function(e){this._toneMappingType!==e&&(this._toneMappingType=e,this._updateParameters())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"contrast",{get:function(){return this._contrast},set:function(e){this._contrast!==e&&(this._contrast=e,this._updateParameters())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"vignetteBlendMode",{get:function(){return this._vignetteBlendMode},set:function(e){this._vignetteBlendMode!==e&&(this._vignetteBlendMode=e,this._updateParameters())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"vignetteEnabled",{get:function(){return this._vignetteEnabled},set:function(e){this._vignetteEnabled!==e&&(this._vignetteEnabled=e,this._updateParameters())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"applyByPostProcess",{get:function(){return this._applyByPostProcess},set:function(e){this._applyByPostProcess!==e&&(this._applyByPostProcess=e,this._updateParameters())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isEnabled",{get:function(){return this._isEnabled},set:function(e){this._isEnabled!==e&&(this._isEnabled=e,this._updateParameters())},enumerable:!0,configurable:!0}),e.prototype._updateParameters=function(){this.onUpdateParameters.notifyObservers(this)},e.prototype.getClassName=function(){return"ImageProcessingConfiguration"},e.PrepareUniforms=function(e,t){t.EXPOSURE&&e.push("exposureLinear"),t.CONTRAST&&e.push("contrast"),t.COLORGRADING&&e.push("colorTransformSettings"),t.VIGNETTE&&(e.push("vInverseScreenSize"),e.push("vignetteSettings1"),e.push("vignetteSettings2")),t.COLORCURVES&&l.a.PrepareUniforms(e)},e.PrepareSamplers=function(e,t){t.COLORGRADING&&e.push("txColorTransform")},e.prototype.prepareDefines=function(t,i){if(void 0===i&&(i=!1),i!==this.applyByPostProcess||!this._isEnabled)return t.VIGNETTE=!1,t.TONEMAPPING=!1,t.TONEMAPPING_ACES=!1,t.CONTRAST=!1,t.EXPOSURE=!1,t.COLORCURVES=!1,t.COLORGRADING=!1,t.COLORGRADING3D=!1,t.IMAGEPROCESSING=!1,void(t.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess&&this._isEnabled);switch(t.VIGNETTE=this.vignetteEnabled,t.VIGNETTEBLENDMODEMULTIPLY=this.vignetteBlendMode===e._VIGNETTEMODE_MULTIPLY,t.VIGNETTEBLENDMODEOPAQUE=!t.VIGNETTEBLENDMODEMULTIPLY,t.TONEMAPPING=this.toneMappingEnabled,this._toneMappingType){case e.TONEMAPPING_ACES:t.TONEMAPPING_ACES=!0;break;default:t.TONEMAPPING_ACES=!1}t.CONTRAST=1!==this.contrast,t.EXPOSURE=1!==this.exposure,t.COLORCURVES=this.colorCurvesEnabled&&!!this.colorCurves,t.COLORGRADING=this.colorGradingEnabled&&!!this.colorGradingTexture,t.COLORGRADING?t.COLORGRADING3D=this.colorGradingTexture.is3D:t.COLORGRADING3D=!1,t.SAMPLER3DGREENDEPTH=this.colorGradingWithGreenDepth,t.SAMPLER3DBGRMAP=this.colorGradingBGR,t.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess,t.IMAGEPROCESSING=t.VIGNETTE||t.TONEMAPPING||t.CONTRAST||t.EXPOSURE||t.COLORCURVES||t.COLORGRADING},e.prototype.isReady=function(){return!this.colorGradingEnabled||!this.colorGradingTexture||this.colorGradingTexture.isReady()},e.prototype.bind=function(e,t){if(void 0===t&&(t=1),this._colorCurvesEnabled&&this.colorCurves&&l.a.Bind(this.colorCurves,e),this._vignetteEnabled){var i=1/e.getEngine().getRenderWidth(),n=1/e.getEngine().getRenderHeight();e.setFloat2("vInverseScreenSize",i,n);var r=Math.tan(.5*this.vignetteCameraFov),o=r*t,a=Math.sqrt(o*r);o=s.h.Mix(o,a,this.vignetteStretch),r=s.h.Mix(r,a,this.vignetteStretch),e.setFloat4("vignetteSettings1",o,r,-o*this.vignetteCentreX,-r*this.vignetteCentreY);var c=-2*this.vignetteWeight;e.setFloat4("vignetteSettings2",this.vignetteColor.r,this.vignetteColor.g,this.vignetteColor.b,c)}if(e.setFloat("exposureLinear",this.exposure),e.setFloat("contrast",this.contrast),this.colorGradingTexture){e.setTexture("txColorTransform",this.colorGradingTexture);var u=this.colorGradingTexture.getSize().height;e.setFloat4("colorTransformSettings",(u-1)/u,.5/u,u,this.colorGradingTexture.level)}},e.prototype.clone=function(){return r.a.Clone(function(){return new e},this)},e.prototype.serialize=function(){return r.a.Serialize(this)},e.Parse=function(t){return r.a.Parse(function(){return new e},t,null,null)},Object.defineProperty(e,"VIGNETTEMODE_MULTIPLY",{get:function(){return this._VIGNETTEMODE_MULTIPLY},enumerable:!0,configurable:!0}),Object.defineProperty(e,"VIGNETTEMODE_OPAQUE",{get:function(){return this._VIGNETTEMODE_OPAQUE},enumerable:!0,configurable:!0}),e.TONEMAPPING_STANDARD=0,e.TONEMAPPING_ACES=1,e._VIGNETTEMODE_MULTIPLY=0,e._VIGNETTEMODE_OPAQUE=1,n.c([Object(r.g)()],e.prototype,"colorCurves",void 0),n.c([Object(r.c)()],e.prototype,"_colorCurvesEnabled",void 0),n.c([Object(r.m)("colorGradingTexture")],e.prototype,"_colorGradingTexture",void 0),n.c([Object(r.c)()],e.prototype,"_colorGradingEnabled",void 0),n.c([Object(r.c)()],e.prototype,"_colorGradingWithGreenDepth",void 0),n.c([Object(r.c)()],e.prototype,"_colorGradingBGR",void 0),n.c([Object(r.c)()],e.prototype,"_exposure",void 0),n.c([Object(r.c)()],e.prototype,"_toneMappingEnabled",void 0),n.c([Object(r.c)()],e.prototype,"_toneMappingType",void 0),n.c([Object(r.c)()],e.prototype,"_contrast",void 0),n.c([Object(r.c)()],e.prototype,"vignetteStretch",void 0),n.c([Object(r.c)()],e.prototype,"vignetteCentreX",void 0),n.c([Object(r.c)()],e.prototype,"vignetteCentreY",void 0),n.c([Object(r.c)()],e.prototype,"vignetteWeight",void 0),n.c([Object(r.f)()],e.prototype,"vignetteColor",void 0),n.c([Object(r.c)()],e.prototype,"vignetteCameraFov",void 0),n.c([Object(r.c)()],e.prototype,"_vignetteBlendMode",void 0),n.c([Object(r.c)()],e.prototype,"_vignetteEnabled",void 0),n.c([Object(r.c)()],e.prototype,"_applyByPostProcess",void 0),n.c([Object(r.c)()],e.prototype,"_isEnabled",void 0),e}();r.a._ImageProcessingConfigurationParser=h.Parse},function(e,t,i){"use strict";i.d(t,"a",function(){return r});var n=function(e,t){return e?e.getClassName&&"Mesh"===e.getClassName()?null:e.getClassName&&"SubMesh"===e.getClassName()?e.clone(t):e.clone?e.clone():null:null},r=function(){function e(){}return e.DeepCopy=function(e,t,i,r){for(var o in e)if(("_"!==o[0]||r&&-1!==r.indexOf(o))&&(!i||-1===i.indexOf(o))){var s=e[o],a=typeof s;if("function"!==a)try{if("object"===a)if(s instanceof Array){if(t[o]=[],s.length>0)if("object"==typeof s[0])for(var c=0;c0)):!i._pointerCaptures[c.pointerId]&&s.distance>a.distance&&(i.mainSceneTrackerPredicate&&i.mainSceneTrackerPredicate(a.pickedMesh)?(i._notifyObservers(t,a,c),t.skipOnPointerObservable=!0):i._lastPointerEvents[c.pointerId]&&(i.onPointerOutObservable.notifyObservers(c.pointerId),delete i._lastPointerEvents[c.pointerId])),t.type===o.a.POINTERUP&&i._pointerCaptures[c.pointerId]&&(i._pointerCaptures[c.pointerId]=!1))}}}}),this._originalPointerObserver&&e.onPrePointerObservable.makeObserverTopPriority(this._originalPointerObserver)),this.utilityLayerScene.autoClear=!1,this._afterRenderObserver=this.originalScene.onAfterCameraRenderObservable.add(function(e){i.shouldRender&&e==i.getRenderCamera()&&i.render()}),this._sceneDisposeObserver=this.originalScene.onDisposeObservable.add(function(){i.dispose()}),this._updateCamera()}return e.prototype.getRenderCamera=function(){return this._renderCamera?this._renderCamera:this.originalScene.activeCameras.length>1?this.originalScene.activeCameras[this.originalScene.activeCameras.length-1]:this.originalScene.activeCamera},e.prototype.setRenderCamera=function(e){this._renderCamera=e},e.prototype._getSharedGizmoLight=function(){return this._sharedGizmoLight||(this._sharedGizmoLight=new a.a("shared gizmo light",new c.x(0,1,0),this.utilityLayerScene),this._sharedGizmoLight.intensity=2,this._sharedGizmoLight.groundColor=c.e.Gray()),this._sharedGizmoLight},Object.defineProperty(e,"DefaultUtilityLayer",{get:function(){return null==e._DefaultUtilityLayer&&(e._DefaultUtilityLayer=new e(s.a.LastCreatedScene),e._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function(){e._DefaultUtilityLayer=null})),e._DefaultUtilityLayer},enumerable:!0,configurable:!0}),Object.defineProperty(e,"DefaultKeepDepthUtilityLayer",{get:function(){return null==e._DefaultKeepDepthUtilityLayer&&(e._DefaultKeepDepthUtilityLayer=new e(s.a.LastCreatedScene),e._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,e._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function(){e._DefaultKeepDepthUtilityLayer=null})),e._DefaultKeepDepthUtilityLayer},enumerable:!0,configurable:!0}),e.prototype._notifyObservers=function(e,t,i){e.skipOnPointerObservable||(this.utilityLayerScene.onPointerObservable.notifyObservers(new o.b(e.type,e.event,t)),this._lastPointerEvents[i.pointerId]=!0)},e.prototype.render=function(){if(this._updateCamera(),this.utilityLayerScene.activeCamera){var e=this.utilityLayerScene.activeCamera.getScene(),t=this.utilityLayerScene.activeCamera;t._scene=this.utilityLayerScene,t.leftCamera&&(t.leftCamera._scene=this.utilityLayerScene),t.rightCamera&&(t.rightCamera._scene=this.utilityLayerScene),this.utilityLayerScene.render(!1),t._scene=e,t.leftCamera&&(t.leftCamera._scene=e),t.rightCamera&&(t.rightCamera._scene=e)}},e.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()},e.prototype._updateCamera=function(){this.utilityLayerScene.cameraToUseForPointers=this.getRenderCamera(),this.utilityLayerScene.activeCamera=this.getRenderCamera()},e._DefaultUtilityLayer=null,e._DefaultKeepDepthUtilityLayer=null,e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return a});var n=i(1),r=i(2),o=i(9),s=i(0),a=function(e){function t(i,n,r){void 0===n&&(n=null),void 0===r&&(r=!0);var a=e.call(this,i,n)||this;return a._forward=new s.x(0,0,1),a._forwardInverted=new s.x(0,0,-1),a._up=new s.x(0,1,0),a._right=new s.x(1,0,0),a._rightInverted=new s.x(-1,0,0),a._position=s.x.Zero(),a._rotation=s.x.Zero(),a._rotationQuaternion=null,a._scaling=s.x.One(),a._isDirty=!1,a._transformToBoneReferal=null,a._billboardMode=t.BILLBOARDMODE_NONE,a._preserveParentRotationForBillboard=!1,a.scalingDeterminant=1,a._infiniteDistance=!1,a.ignoreNonUniformScaling=!1,a.reIntegrateRotationIntoRotationQuaternion=!1,a._poseMatrix=null,a._localMatrix=s.j.Zero(),a._usePivotMatrix=!1,a._absolutePosition=s.x.Zero(),a._pivotMatrix=s.j.Identity(),a._postMultiplyPivotMatrix=!1,a._isWorldMatrixFrozen=!1,a._indexInSceneTransformNodesArray=-1,a.onAfterWorldMatrixUpdateObservable=new o.c,a._nonUniformScaling=!1,r&&a.getScene().addTransformNode(a),a}return n.d(t,e),Object.defineProperty(t.prototype,"billboardMode",{get:function(){return this._billboardMode},set:function(e){this._billboardMode!==e&&(this._billboardMode=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"preserveParentRotationForBillboard",{get:function(){return this._preserveParentRotationForBillboard},set:function(e){e!==this._preserveParentRotationForBillboard&&(this._preserveParentRotationForBillboard=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"infiniteDistance",{get:function(){return this._infiniteDistance},set:function(e){this._infiniteDistance!==e&&(this._infiniteDistance=e)},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"TransformNode"},Object.defineProperty(t.prototype,"position",{get:function(){return this._position},set:function(e){this._position=e,this._isDirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rotation",{get:function(){return this._rotation},set:function(e){this._rotation=e,this._rotationQuaternion=null,this._isDirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"scaling",{get:function(){return this._scaling},set:function(e){this._scaling=e,this._isDirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rotationQuaternion",{get:function(){return this._rotationQuaternion},set:function(e){this._rotationQuaternion=e,e&&this._rotation.setAll(0),this._isDirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"forward",{get:function(){return s.x.Normalize(s.x.TransformNormal(this.getScene().useRightHandedSystem?this._forwardInverted:this._forward,this.getWorldMatrix()))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"up",{get:function(){return s.x.Normalize(s.x.TransformNormal(this._up,this.getWorldMatrix()))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"right",{get:function(){return s.x.Normalize(s.x.TransformNormal(this.getScene().useRightHandedSystem?this._rightInverted:this._right,this.getWorldMatrix()))},enumerable:!0,configurable:!0}),t.prototype.updatePoseMatrix=function(e){return this._poseMatrix?(this._poseMatrix.copyFrom(e),this):(this._poseMatrix=e.clone(),this)},t.prototype.getPoseMatrix=function(){return this._poseMatrix||(this._poseMatrix=s.j.Identity()),this._poseMatrix},t.prototype._isSynchronized=function(){var e=this._cache;if(this.billboardMode!==e.billboardMode||this.billboardMode!==t.BILLBOARDMODE_NONE)return!1;if(e.pivotMatrixUpdated)return!1;if(this.infiniteDistance)return!1;if(!e.position.equals(this._position))return!1;if(this._rotationQuaternion){if(!e.rotationQuaternion.equals(this._rotationQuaternion))return!1}else if(!e.rotation.equals(this._rotation))return!1;return!!e.scaling.equals(this._scaling)},t.prototype._initCache=function(){e.prototype._initCache.call(this);var t=this._cache;t.localMatrixUpdated=!1,t.position=s.x.Zero(),t.scaling=s.x.Zero(),t.rotation=s.x.Zero(),t.rotationQuaternion=new s.q(0,0,0,0),t.billboardMode=-1,t.infiniteDistance=!1},t.prototype.markAsDirty=function(e){return this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this},Object.defineProperty(t.prototype,"absolutePosition",{get:function(){return this._absolutePosition},enumerable:!0,configurable:!0}),t.prototype.setPreTransformMatrix=function(e){return this.setPivotMatrix(e,!1)},t.prototype.setPivotMatrix=function(e,t){return void 0===t&&(t=!0),this._pivotMatrix.copyFrom(e),this._usePivotMatrix=!this._pivotMatrix.isIdentity(),this._cache.pivotMatrixUpdated=!0,this._postMultiplyPivotMatrix=t,this._postMultiplyPivotMatrix&&(this._pivotMatrixInverse?this._pivotMatrix.invertToRef(this._pivotMatrixInverse):this._pivotMatrixInverse=s.j.Invert(this._pivotMatrix)),this},t.prototype.getPivotMatrix=function(){return this._pivotMatrix},t.prototype.freezeWorldMatrix=function(){return this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0),this._isWorldMatrixFrozen=!0,this},t.prototype.unfreezeWorldMatrix=function(){return this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0),this},Object.defineProperty(t.prototype,"isWorldMatrixFrozen",{get:function(){return this._isWorldMatrixFrozen},enumerable:!0,configurable:!0}),t.prototype.getAbsolutePosition=function(){return this.computeWorldMatrix(),this._absolutePosition},t.prototype.setAbsolutePosition=function(e){if(!e)return this;var t,i,n;if(void 0===e.x){if(arguments.length<3)return this;t=arguments[0],i=arguments[1],n=arguments[2]}else t=e.x,i=e.y,n=e.z;if(this.parent){var r=s.t.Matrix[0];this.parent.getWorldMatrix().invertToRef(r),s.x.TransformCoordinatesFromFloatsToRef(t,i,n,r,this.position)}else this.position.x=t,this.position.y=i,this.position.z=n;return this},t.prototype.setPositionWithLocalVector=function(e){return this.computeWorldMatrix(),this.position=s.x.TransformNormal(e,this._localMatrix),this},t.prototype.getPositionExpressedInLocalSpace=function(){this.computeWorldMatrix();var e=s.t.Matrix[0];return this._localMatrix.invertToRef(e),s.x.TransformNormal(this.position,e)},t.prototype.locallyTranslate=function(e){return this.computeWorldMatrix(!0),this.position=s.x.TransformCoordinates(e,this._localMatrix),this},t.prototype.lookAt=function(e,i,n,r,o){void 0===i&&(i=0),void 0===n&&(n=0),void 0===r&&(r=0),void 0===o&&(o=s.s.LOCAL);var a=t._lookAtVectorCache,c=o===s.s.LOCAL?this.position:this.getAbsolutePosition();if(e.subtractToRef(c,a),this.setDirection(a,i,n,r),o===s.s.WORLD&&this.parent)if(this.rotationQuaternion){var l=s.t.Matrix[0];this.rotationQuaternion.toRotationMatrix(l);var u=s.t.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(u),u.invert(),l.multiplyToRef(u,l),this.rotationQuaternion.fromRotationMatrix(l)}else{var h=s.t.Quaternion[0];s.q.FromEulerVectorToRef(this.rotation,h);l=s.t.Matrix[0];h.toRotationMatrix(l);u=s.t.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(u),u.invert(),l.multiplyToRef(u,l),h.fromRotationMatrix(l),h.toEulerAnglesToRef(this.rotation)}return this},t.prototype.getDirection=function(e){var t=s.x.Zero();return this.getDirectionToRef(e,t),t},t.prototype.getDirectionToRef=function(e,t){return s.x.TransformNormalToRef(e,this.getWorldMatrix(),t),this},t.prototype.setDirection=function(e,t,i,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0);var r=-Math.atan2(e.z,e.x)+Math.PI/2,o=Math.sqrt(e.x*e.x+e.z*e.z),a=-Math.atan2(e.y,o);return this.rotationQuaternion?s.q.RotationYawPitchRollToRef(r+t,a+i,n,this.rotationQuaternion):(this.rotation.x=a+i,this.rotation.y=r+t,this.rotation.z=n),this},t.prototype.setPivotPoint=function(e,t){void 0===t&&(t=s.s.LOCAL),0==this.getScene().getRenderId()&&this.computeWorldMatrix(!0);var i=this.getWorldMatrix();if(t==s.s.WORLD){var n=s.t.Matrix[0];i.invertToRef(n),e=s.x.TransformCoordinates(e,n)}return this.setPivotMatrix(s.j.Translation(-e.x,-e.y,-e.z),!0)},t.prototype.getPivotPoint=function(){var e=s.x.Zero();return this.getPivotPointToRef(e),e},t.prototype.getPivotPointToRef=function(e){return e.x=-this._pivotMatrix.m[12],e.y=-this._pivotMatrix.m[13],e.z=-this._pivotMatrix.m[14],this},t.prototype.getAbsolutePivotPoint=function(){var e=s.x.Zero();return this.getAbsolutePivotPointToRef(e),e},t.prototype.getAbsolutePivotPointToRef=function(e){return e.x=this._pivotMatrix.m[12],e.y=this._pivotMatrix.m[13],e.z=this._pivotMatrix.m[14],this.getPivotPointToRef(e),s.x.TransformCoordinatesToRef(e,this.getWorldMatrix(),e),this},t.prototype.setParent=function(e){if(!e&&!this.parent)return this;var t=s.t.Quaternion[0],i=s.t.Vector3[0],n=s.t.Vector3[1];if(e){var r=s.t.Matrix[0],o=s.t.Matrix[1];this.computeWorldMatrix(!0),e.computeWorldMatrix(!0),e.getWorldMatrix().invertToRef(o),this.getWorldMatrix().multiplyToRef(o,r),r.decompose(n,t,i)}else this.parent&&this.parent.computeWorldMatrix&&this.parent.computeWorldMatrix(!0),this.computeWorldMatrix(!0),this.getWorldMatrix().decompose(n,t,i);return this.rotationQuaternion?this.rotationQuaternion.copyFrom(t):t.toEulerAnglesToRef(this.rotation),this.scaling.copyFrom(n),this.position.copyFrom(i),this.parent=e,this},Object.defineProperty(t.prototype,"nonUniformScaling",{get:function(){return this._nonUniformScaling},enumerable:!0,configurable:!0}),t.prototype._updateNonUniformScalingState=function(e){return this._nonUniformScaling!==e&&(this._nonUniformScaling=e,!0)},t.prototype.attachToBone=function(e,t){return this._transformToBoneReferal=t,this.parent=e,e.getWorldMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this},t.prototype.detachFromBone=function(){return this.parent?(this.parent.getWorldMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this._transformToBoneReferal=null,this.parent=null,this):this},t.prototype.rotate=function(e,i,n){var r;if(e.normalize(),this.rotationQuaternion||(this.rotationQuaternion=this.rotation.toQuaternion(),this.rotation.setAll(0)),n&&n!==s.s.LOCAL){if(this.parent){var o=s.t.Matrix[0];this.parent.getWorldMatrix().invertToRef(o),e=s.x.TransformNormal(e,o)}(r=s.q.RotationAxisToRef(e,i,t._rotationAxisCache)).multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}else r=s.q.RotationAxisToRef(e,i,t._rotationAxisCache),this.rotationQuaternion.multiplyToRef(r,this.rotationQuaternion);return this},t.prototype.rotateAround=function(e,t,i){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=s.q.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.setAll(0));var n=s.t.Vector3[0],r=s.t.Vector3[1],o=s.t.Vector3[2],a=s.t.Quaternion[0],c=s.t.Matrix[0],l=s.t.Matrix[1],u=s.t.Matrix[2],h=s.t.Matrix[3];return e.subtractToRef(this.position,n),s.j.TranslationToRef(n.x,n.y,n.z,c),s.j.TranslationToRef(-n.x,-n.y,-n.z,l),s.j.RotationAxisToRef(t,i,u),l.multiplyToRef(u,h),h.multiplyToRef(c,h),h.decompose(r,a,o),this.position.addInPlace(o),a.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion),this},t.prototype.translate=function(e,t,i){var n=e.scale(t);if(i&&i!==s.s.LOCAL)this.setAbsolutePosition(this.getAbsolutePosition().add(n));else{var r=this.getPositionExpressedInLocalSpace().add(n);this.setPositionWithLocalVector(r)}return this},t.prototype.addRotation=function(e,t,i){var n;this.rotationQuaternion?n=this.rotationQuaternion:(n=s.t.Quaternion[1],s.q.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,n));var r=s.t.Quaternion[0];return s.q.RotationYawPitchRollToRef(t,e,i,r),n.multiplyInPlace(r),this.rotationQuaternion||n.toEulerAnglesToRef(this.rotation),this},t.prototype._getEffectiveParent=function(){return this.parent},t.prototype.computeWorldMatrix=function(e){if(this._isWorldMatrixFrozen&&!this._isDirty)return this._worldMatrix;var i=this.getScene().getRenderId();if(!this._isDirty&&!e&&this.isSynchronized())return this._currentRenderId=i,this._worldMatrix;this._updateCache();var n=this._cache;n.pivotMatrixUpdated=!1,n.billboardMode=this.billboardMode,n.infiniteDistance=this.infiniteDistance,this._currentRenderId=i,this._childUpdateId++,this._isDirty=!1;var r=this._getEffectiveParent(),o=this._billboardMode!==t.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard,a=this.getScene().activeCamera,c=n.scaling,l=n.position;if(this._infiniteDistance)if(!this.parent&&a){var u=a.getWorldMatrix(),h=new s.x(u.m[12],u.m[13],u.m[14]);l.copyFromFloats(this._position.x+h.x,this._position.y+h.y,this._position.z+h.z)}else l.copyFrom(this._position);else l.copyFrom(this._position);c.copyFromFloats(this._scaling.x*this.scalingDeterminant,this._scaling.y*this.scalingDeterminant,this._scaling.z*this.scalingDeterminant);var d=n.rotationQuaternion;if(this._rotationQuaternion){if(this.reIntegrateRotationIntoRotationQuaternion)this.rotation.lengthSquared()&&(this._rotationQuaternion.multiplyInPlace(s.q.RotationYawPitchRoll(this._rotation.y,this._rotation.x,this._rotation.z)),this._rotation.copyFromFloats(0,0,0));d.copyFrom(this._rotationQuaternion)}else s.q.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,d),n.rotation.copyFrom(this._rotation);if(this._usePivotMatrix){var f=s.t.Matrix[1];s.j.ScalingToRef(c.x,c.y,c.z,f);var p=s.t.Matrix[0];d.toRotationMatrix(p),this._pivotMatrix.multiplyToRef(f,s.t.Matrix[4]),s.t.Matrix[4].multiplyToRef(p,this._localMatrix),this._postMultiplyPivotMatrix&&this._localMatrix.multiplyToRef(this._pivotMatrixInverse,this._localMatrix),this._localMatrix.addTranslationFromFloats(l.x,l.y,l.z)}else s.j.ComposeToRef(c,d,l,this._localMatrix);if(r&&r.getWorldMatrix){if(o){this._transformToBoneReferal?r.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),s.t.Matrix[7]):s.t.Matrix[7].copyFrom(r.getWorldMatrix());var _=s.t.Vector3[5],m=s.t.Vector3[6];s.t.Matrix[7].decompose(m,void 0,_),s.j.ScalingToRef(m.x,m.y,m.z,s.t.Matrix[7]),s.t.Matrix[7].setTranslation(_),this._localMatrix.multiplyToRef(s.t.Matrix[7],this._worldMatrix)}else this._transformToBoneReferal?(this._localMatrix.multiplyToRef(r.getWorldMatrix(),s.t.Matrix[6]),s.t.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),this._worldMatrix)):this._localMatrix.multiplyToRef(r.getWorldMatrix(),this._worldMatrix);this._markSyncedWithParent()}else this._worldMatrix.copyFrom(this._localMatrix);if(o&&a){var g=s.t.Vector3[0];if(this._worldMatrix.getTranslationToRef(g),s.t.Matrix[1].copyFrom(a.getViewMatrix()),s.t.Matrix[1].setTranslationFromFloats(0,0,0),s.t.Matrix[1].invertToRef(s.t.Matrix[0]),(this.billboardMode&t.BILLBOARDMODE_ALL)!==t.BILLBOARDMODE_ALL){s.t.Matrix[0].decompose(void 0,s.t.Quaternion[0],void 0);var v=s.t.Vector3[1];s.t.Quaternion[0].toEulerAnglesToRef(v),(this.billboardMode&t.BILLBOARDMODE_X)!==t.BILLBOARDMODE_X&&(v.x=0),(this.billboardMode&t.BILLBOARDMODE_Y)!==t.BILLBOARDMODE_Y&&(v.y=0),(this.billboardMode&t.BILLBOARDMODE_Z)!==t.BILLBOARDMODE_Z&&(v.z=0),s.j.RotationYawPitchRollToRef(v.y,v.x,v.z,s.t.Matrix[0])}this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(s.t.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(s.t.Vector3[0])}return this.ignoreNonUniformScaling?this._updateNonUniformScalingState(!1):this._scaling.isNonUniform?this._updateNonUniformScalingState(!0):r&&r._nonUniformScaling?this._updateNonUniformScalingState(r._nonUniformScaling):this._updateNonUniformScalingState(!1),this._afterComputeWorldMatrix(),this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this.onAfterWorldMatrixUpdateObservable.notifyObservers(this),this._poseMatrix||(this._poseMatrix=s.j.Invert(this._worldMatrix)),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix},t.prototype._afterComputeWorldMatrix=function(){},t.prototype.registerAfterWorldMatrixUpdate=function(e){return this.onAfterWorldMatrixUpdateObservable.add(e),this},t.prototype.unregisterAfterWorldMatrixUpdate=function(e){return this.onAfterWorldMatrixUpdateObservable.removeCallback(e),this},t.prototype.getPositionInCameraSpace=function(e){return void 0===e&&(e=null),e||(e=this.getScene().activeCamera),s.x.TransformCoordinates(this.absolutePosition,e.getViewMatrix())},t.prototype.getDistanceToCamera=function(e){return void 0===e&&(e=null),e||(e=this.getScene().activeCamera),this.absolutePosition.subtract(e.globalPosition).length()},t.prototype.clone=function(e,i,n){var o=this,s=r.a.Clone(function(){return new t(e,o.getScene())},this);if(s.name=e,s.id=e,i&&(s.parent=i),!n)for(var a=this.getDescendants(!0),c=0;c0&&-1===this.includedOnlyMeshes.indexOf(e))&&(!(this.excludedMeshes&&this.excludedMeshes.length>0&&-1!==this.excludedMeshes.indexOf(e))&&((0===this.includeOnlyWithLayerMask||0!=(this.includeOnlyWithLayerMask&e.layerMask))&&!(0!==this.excludeWithLayerMask&&this.excludeWithLayerMask&e.layerMask)))},t.CompareLightsPriority=function(e,t){return e.shadowEnabled!==t.shadowEnabled?(t.shadowEnabled?1:0)-(e.shadowEnabled?1:0):t.renderPriority-e.renderPriority},t.prototype.dispose=function(t,i){void 0===i&&(i=!1),this._shadowGenerator&&(this._shadowGenerator.dispose(),this._shadowGenerator=null),this.getScene().stopAnimation(this);for(var n=0,r=this.getScene().meshes;n0&&(e.excludedMeshesIds=[],this.excludedMeshes.forEach(function(t){e.excludedMeshesIds.push(t.id)})),this.includedOnlyMeshes.length>0&&(e.includedOnlyMeshesIds=[],this.includedOnlyMeshes.forEach(function(t){e.includedOnlyMeshesIds.push(t.id)})),r.a.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e},t.GetConstructorFromName=function(e,t,i){var n=s.a.Construct("Light_Type_"+e,t,i);return n||null},t.Parse=function(e,i){var n=t.GetConstructorFromName(e.type,e.name,i);if(!n)return null;var o=r.a.Parse(n,e,i);if(e.excludedMeshesIds&&(o._excludedMeshesIds=e.excludedMeshesIds),e.includedOnlyMeshesIds&&(o._includedOnlyMeshesIds=e.includedOnlyMeshesIds),e.parentId&&(o._waitingParentId=e.parentId),void 0!==e.falloffType&&(o.falloffType=e.falloffType),void 0!==e.lightmapMode&&(o.lightmapMode=e.lightmapMode),e.animations){for(var a=0;al.x)return!1}else if(r=1/this.direction.x,o=(c.x-this.origin.x)*r,(s=(l.x-this.origin.x)*r)===-1/0&&(s=1/0),o>s&&(a=o,o=s,s=a),(u=Math.max(o,u))>(h=Math.min(s,h)))return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.yl.y)return!1}else if(r=1/this.direction.y,o=(c.y-this.origin.y)*r,(s=(l.y-this.origin.y)*r)===-1/0&&(s=1/0),o>s&&(a=o,o=s,s=a),(u=Math.max(o,u))>(h=Math.min(s,h)))return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.zl.z)return!1}else if(r=1/this.direction.z,o=(c.z-this.origin.z)*r,(s=(l.z-this.origin.z)*r)===-1/0&&(s=1/0),o>s&&(a=o,o=s,s=a),(u=Math.max(o,u))>(h=Math.min(s,h)))return!1;return!0},e.prototype.intersectsBox=function(e,t){return void 0===t&&(t=0),this.intersectsBoxMinMax(e.minimum,e.maximum,t)},e.prototype.intersectsSphere=function(e,t){void 0===t&&(t=0);var i=e.center.x-this.origin.x,n=e.center.y-this.origin.y,r=e.center.z-this.origin.z,o=i*i+n*n+r*r,s=e.radius+t,a=s*s;if(o<=a)return!0;var c=i*this.direction.x+n*this.direction.y+r*this.direction.z;return!(c<0)&&o-c*c<=a},e.prototype.intersectsTriangle=function(t,i,n){var o=e.TmpVector3[0],a=e.TmpVector3[1],c=e.TmpVector3[2],l=e.TmpVector3[3],u=e.TmpVector3[4];i.subtractToRef(t,o),n.subtractToRef(t,a),r.x.CrossToRef(this.direction,a,c);var h=r.x.Dot(o,c);if(0===h)return null;var d=1/h;this.origin.subtractToRef(t,l);var f=r.x.Dot(l,c)*d;if(f<0||f>1)return null;r.x.CrossToRef(l,o,u);var p=r.x.Dot(this.direction,u)*d;if(p<0||f+p>1)return null;var _=r.x.Dot(a,u)*d;return _>this.length?null:new s.a(1-f-p,f,_)},e.prototype.intersectsPlane=function(e){var t,i=r.x.Dot(e.normal,this.direction);if(Math.abs(i)<9.99999997475243e-7)return null;var n=r.x.Dot(e.normal,this.origin);return(t=(-e.d-n)/i)<0?t<-9.99999997475243e-7?null:0:t},e.prototype.intersectsMesh=function(t,i){var n=r.t.Matrix[0];return t.getWorldMatrix().invertToRef(n),this._tmpRay?e.TransformToRef(this,n,this._tmpRay):this._tmpRay=e.Transform(this,n),t.intersects(this._tmpRay,i)},e.prototype.intersectsMeshes=function(e,t,i){i?i.length=0:i=[];for(var n=0;nt.distance?1:0},e.prototype.intersectionSegment=function(t,i,n){var o=this.origin,s=r.t.Vector3[0],a=r.t.Vector3[1],c=r.t.Vector3[2],l=r.t.Vector3[3];i.subtractToRef(t,s),this.direction.scaleToRef(e.rayl,c),o.addToRef(c,a),t.subtractToRef(o,l);var u,h,d,f,p=r.x.Dot(s,s),_=r.x.Dot(s,c),m=r.x.Dot(c,c),g=r.x.Dot(s,l),v=r.x.Dot(c,l),y=p*m-_*_,b=y,T=y;yb&&(h=b,f=v+_,T=m)),f<0?(f=0,-g<0?h=0:-g>p?h=b:(h=-g,b=p)):f>T&&(f=T,-g+_<0?h=0:-g+_>p?h=b:(h=-g+_,b=p)),u=Math.abs(h)0&&d<=this.length&&A.lengthSquared()=r.distance))&&(r=l,i)))break}return r||new o.a},a.a.prototype._internalMultiPick=function(e,t,i){if(!o.a)return null;for(var n=new Array,r=0;r0&&(t.push(a-1),t.push(a)),a++}var d=new o.a;return d.indices=t,d.positions=i,r&&(d.colors=s),d},o.a.CreateDashedLines=function(e){var t,i,r=e.dashSize||3,s=e.gapSize||1,a=e.dashNb||200,c=e.points,l=new Array,u=new Array,h=n.x.Zero(),d=0,f=0,p=0,_=0,m=0;for(m=0;ml.max||l.min>c.max)},d=function(){function e(e,t,i){this._isLocked=!1,this.boundingBox=new s.a(e,t,i),this.boundingSphere=new a.a(e,t,i)}return e.prototype.reConstruct=function(e,t,i){this.boundingBox.reConstruct(e,t,i),this.boundingSphere.reConstruct(e,t,i)},Object.defineProperty(e.prototype,"minimum",{get:function(){return this.boundingBox.minimum},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"maximum",{get:function(){return this.boundingBox.maximum},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isLocked",{get:function(){return this._isLocked},set:function(e){this._isLocked=e},enumerable:!0,configurable:!0}),e.prototype.update=function(e){this._isLocked||(this.boundingBox._update(e),this.boundingSphere._update(e))},e.prototype.centerOn=function(t,i){var n=e.TmpVector3[0].copyFrom(t).subtractInPlace(i),r=e.TmpVector3[1].copyFrom(t).addInPlace(i);return this.boundingBox.reConstruct(n,r,this.boundingBox.getWorldMatrix()),this.boundingSphere.reConstruct(n,r,this.boundingBox.getWorldMatrix()),this},e.prototype.scale=function(e){return this.boundingBox.scale(e),this.boundingSphere.scale(e),this},e.prototype.isInFrustum=function(e,t){return void 0===t&&(t=o.a.MESHES_CULLINGSTRATEGY_STANDARD),!(t!==o.a.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION&&t!==o.a.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY||!this.boundingSphere.isCenterInFrustum(e))||!!this.boundingSphere.isInFrustum(e)&&(!(t!==o.a.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY&&t!==o.a.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY)||this.boundingBox.isInFrustum(e))},Object.defineProperty(e.prototype,"diagonalLength",{get:function(){var t=this.boundingBox;return t.maximumWorld.subtractToRef(t.minimumWorld,e.TmpVector3[0]).length()},enumerable:!0,configurable:!0}),e.prototype.isCompletelyInFrustum=function(e){return this.boundingBox.isCompletelyInFrustum(e)},e.prototype._checkCollision=function(e){return e._canDoCollision(this.boundingSphere.centerWorld,this.boundingSphere.radiusWorld,this.boundingBox.minimumWorld,this.boundingBox.maximumWorld)},e.prototype.intersectsPoint=function(e){return!!this.boundingSphere.centerWorld&&(!!this.boundingSphere.intersectsPoint(e)&&!!this.boundingBox.intersectsPoint(e))},e.prototype.intersects=function(e,t){if(!a.a.Intersects(this.boundingSphere,e.boundingSphere))return!1;if(!s.a.Intersects(this.boundingBox,e.boundingBox))return!1;if(!t)return!0;var i=this.boundingBox,n=e.boundingBox;return!!h(i.directions[0],i,n)&&(!!h(i.directions[1],i,n)&&(!!h(i.directions[2],i,n)&&(!!h(n.directions[0],i,n)&&(!!h(n.directions[1],i,n)&&(!!h(n.directions[2],i,n)&&(!!h(r.x.Cross(i.directions[0],n.directions[0]),i,n)&&(!!h(r.x.Cross(i.directions[0],n.directions[1]),i,n)&&(!!h(r.x.Cross(i.directions[0],n.directions[2]),i,n)&&(!!h(r.x.Cross(i.directions[1],n.directions[0]),i,n)&&(!!h(r.x.Cross(i.directions[1],n.directions[1]),i,n)&&(!!h(r.x.Cross(i.directions[1],n.directions[2]),i,n)&&(!!h(r.x.Cross(i.directions[2],n.directions[0]),i,n)&&(!!h(r.x.Cross(i.directions[2],n.directions[1]),i,n)&&!!h(r.x.Cross(i.directions[2],n.directions[2]),i,n))))))))))))))},e.TmpVector3=n.a.BuildArray(2,r.x.Zero),e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return h});var n=i(1),r=i(2),o=i(9),s=i(11),a=i(74),c=i(0),l=i(21),u=i(3),h=function(){function e(t){this.metadata=null,this.reservedDataStore=null,this._hasAlpha=!1,this.getAlphaFromRGB=!1,this.level=1,this.coordinatesIndex=0,this._coordinatesMode=u.a.TEXTURE_EXPLICIT_MODE,this.wrapU=u.a.TEXTURE_WRAP_ADDRESSMODE,this.wrapV=u.a.TEXTURE_WRAP_ADDRESSMODE,this.wrapR=u.a.TEXTURE_WRAP_ADDRESSMODE,this.anisotropicFilteringLevel=e.DEFAULT_ANISOTROPIC_FILTERING_LEVEL,this.gammaSpace=!0,this.invertZ=!1,this.lodLevelInAlpha=!1,this.isRenderTarget=!1,this.animations=new Array,this.onDisposeObservable=new o.c,this._onDisposeObserver=null,this.delayLoadState=u.a.DELAYLOADSTATE_NONE,this._scene=null,this._texture=null,this._uid=null,this._cachedSize=c.r.Zero(),this._scene=t||l.a.LastCreatedScene,this._scene&&(this.uniqueId=this._scene.getUniqueId(),this._scene.addTexture(this)),this._uid=null}return Object.defineProperty(e.prototype,"hasAlpha",{get:function(){return this._hasAlpha},set:function(e){this._hasAlpha!==e&&(this._hasAlpha=e,this._scene&&this._scene.markAllMaterialsAsDirty(u.a.MATERIAL_TextureDirtyFlag|u.a.MATERIAL_MiscDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"coordinatesMode",{get:function(){return this._coordinatesMode},set:function(e){this._coordinatesMode!==e&&(this._coordinatesMode=e,this._scene&&this._scene.markAllMaterialsAsDirty(u.a.MATERIAL_TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isCube",{get:function(){return!!this._texture&&this._texture.isCube},set:function(e){this._texture&&(this._texture.isCube=e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"is3D",{get:function(){return!!this._texture&&this._texture.is3D},set:function(e){this._texture&&(this._texture.is3D=e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isRGBD",{get:function(){return null!=this._texture&&this._texture._isRGBD},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"noMipmap",{get:function(){return!1},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"lodGenerationOffset",{get:function(){return this._texture?this._texture._lodGenerationOffset:0},set:function(e){this._texture&&(this._texture._lodGenerationOffset=e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"lodGenerationScale",{get:function(){return this._texture?this._texture._lodGenerationScale:0},set:function(e){this._texture&&(this._texture._lodGenerationScale=e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"linearSpecularLOD",{get:function(){return!!this._texture&&this._texture._linearSpecularLOD},set:function(e){this._texture&&(this._texture._linearSpecularLOD=e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"irradianceTexture",{get:function(){return this._texture?this._texture._irradianceTexture:null},set:function(e){this._texture&&(this._texture._irradianceTexture=e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"uid",{get:function(){return this._uid||(this._uid=s.h.RandomId()),this._uid},enumerable:!0,configurable:!0}),e.prototype.toString=function(){return this.name},e.prototype.getClassName=function(){return"BaseTexture"},Object.defineProperty(e.prototype,"onDispose",{set:function(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isBlocking",{get:function(){return!0},enumerable:!0,configurable:!0}),e.prototype.getScene=function(){return this._scene},e.prototype.getTextureMatrix=function(){return c.j.IdentityReadOnly},e.prototype.getReflectionTextureMatrix=function(){return c.j.IdentityReadOnly},e.prototype.getInternalTexture=function(){return this._texture},e.prototype.isReadyOrNotBlocking=function(){return!this.isBlocking||this.isReady()},e.prototype.isReady=function(){return this.delayLoadState===u.a.DELAYLOADSTATE_NOTLOADED?(this.delayLoad(),!1):!!this._texture&&this._texture.isReady},e.prototype.getSize=function(){if(this._texture){if(this._texture.width)return this._cachedSize.width=this._texture.width,this._cachedSize.height=this._texture.height,this._cachedSize;if(this._texture._size)return this._cachedSize.width=this._texture._size,this._cachedSize.height=this._texture._size,this._cachedSize}return this._cachedSize},e.prototype.getBaseSize=function(){return this.isReady()&&this._texture?this._texture._size?new c.r(this._texture._size,this._texture._size):new c.r(this._texture.baseWidth,this._texture.baseHeight):c.r.Zero()},e.prototype.updateSamplingMode=function(e){if(this._texture){var t=this.getScene();t&&t.getEngine().updateTextureSamplingMode(e,this._texture)}},e.prototype.scale=function(e){},Object.defineProperty(e.prototype,"canRescale",{get:function(){return!1},enumerable:!0,configurable:!0}),e.prototype._getFromCache=function(e,t,i,n){if(!this._scene)return null;for(var r=this._scene.getEngine().getLoadedTexturesCache(),o=0;o=0&&this._scene.textures.splice(e,1),this._scene.onTextureRemovedObservable.notifyObservers(this),void 0!==this._texture&&(this.releaseInternalTexture(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear())}},e.prototype.serialize=function(){if(!this.name)return null;var e=r.a.Serialize(this);return r.a.AppendSerializedAnimations(this,e),e},e.WhenAllReady=function(e,t){var i=e.length;if(0!==i)for(var n,r,o=function(){if((n=e[s]).isReady())0==--i&&t();else{r=n.onLoadObservable;var o=function(){r.removeCallback(o),0==--i&&t()};r.add(o)}},s=0;s1)?1:e.arc||1,c=e.slice&&e.slice<=0?1:e.slice||1,l=0===e.sideOrientation?0:e.sideOrientation||o.a.DEFAULTSIDE,u=new n.x(i/2,r/2,s/2),h=2+t,d=2*h,f=[],p=[],_=[],m=[],g=0;g<=h;g++){for(var v=g/h,y=v*Math.PI*c,b=0;b<=d;b++){var T=b/d,E=T*Math.PI*2*a,x=n.j.RotationZ(-y),A=n.j.RotationY(E),P=n.x.TransformCoordinates(n.x.Up(),x),R=n.x.TransformCoordinates(P,A),S=R.multiply(u),C=R.divide(u).normalize();p.push(S.x,S.y,S.z),_.push(C.x,C.y,C.z),m.push(T,v)}if(g>0)for(var M=p.length/3,O=M-2*(d+1);O+d+2a&&(a=u)}return new t(e,s,a-s+1,i,n,r,o)},t}(l)},function(e,t,i){"use strict";i.d(t,"a",function(){return u});var n=i(5),r=i(16),o=i(9),s=i(0),a=i(17),c=i(41),l=i(45),u=(i(73),function(){function e(e){this._useAlternatePickedPointAboveMaxDragAngleDragSpeed=-1.1,this.maxDragAngle=0,this._useAlternatePickedPointAboveMaxDragAngle=!1,this.currentDraggingPointerID=-1,this.dragging=!1,this.dragDeltaRatio=.2,this.updateDragPlane=!0,this._debugMode=!1,this._moving=!1,this.onDragObservable=new o.c,this.onDragStartObservable=new o.c,this.onDragEndObservable=new o.c,this.moveAttached=!0,this.enabled=!0,this.detachCameraControls=!0,this.useObjectOrienationForDragging=!0,this.validateDrag=function(e){return!0},this._tmpVector=new s.x(0,0,0),this._alternatePickedPoint=new s.x(0,0,0),this._worldDragAxis=new s.x(0,0,0),this._targetPosition=new s.x(0,0,0),this._attachedElement=null,this._startDragRay=new c.a(new s.x,new s.x),this._lastPointerRay={},this._dragDelta=new s.x,this._pointA=new s.x(0,0,0),this._pointB=new s.x(0,0,0),this._pointC=new s.x(0,0,0),this._lineA=new s.x(0,0,0),this._lineB=new s.x(0,0,0),this._localAxis=new s.x(0,0,0),this._lookAt=new s.x(0,0,0),this._options=e||{};var t=0;if(this._options.dragAxis&&t++,this._options.dragPlaneNormal&&t++,t>1)throw"Multiple drag modes specified in dragBehavior options. Only one expected"}return Object.defineProperty(e.prototype,"name",{get:function(){return"PointerDrag"},enumerable:!0,configurable:!0}),e.prototype.init=function(){},e.prototype.attach=function(t){var i=this;this._scene=t.getScene(),this.attachedNode=t,e._planeScene||(this._debugMode?e._planeScene=this._scene:(e._planeScene=new r.a(this._scene.getEngine(),{virtual:!0}),e._planeScene.detachControl(),this._scene.onDisposeObservable.addOnce(function(){e._planeScene.dispose(),e._planeScene=null}))),this._dragPlane=n.a.CreatePlane("pointerDragPlane",this._debugMode?1:1e4,e._planeScene,!1,n.a.DOUBLESIDE),this.lastDragPosition=new s.x(0,0,0);this._pointerObserver=this._scene.onPointerObservable.add(function(t,n){var r;if(i.enabled)if(t.type==a.a.POINTERDOWN)!i.dragging&&t.pickInfo&&t.pickInfo.hit&&t.pickInfo.pickedMesh&&t.pickInfo.pickedPoint&&t.pickInfo.ray&&(r=t.pickInfo.pickedMesh,i.attachedNode==r||r.isDescendantOf(i.attachedNode))&&i._startDrag(t.event.pointerId,t.pickInfo.ray,t.pickInfo.pickedPoint);else if(t.type==a.a.POINTERUP)i.currentDraggingPointerID==t.event.pointerId&&i.releaseDrag();else if(t.type==a.a.POINTERMOVE){var o=t.event.pointerId;i.currentDraggingPointerID===e._AnyMouseID&&o!==e._AnyMouseID&&"mouse"==t.event.pointerType&&(i._lastPointerRay[i.currentDraggingPointerID]&&(i._lastPointerRay[o]=i._lastPointerRay[i.currentDraggingPointerID],delete i._lastPointerRay[i.currentDraggingPointerID]),i.currentDraggingPointerID=o),i._lastPointerRay[o]||(i._lastPointerRay[o]=new c.a(new s.x,new s.x)),t.pickInfo&&t.pickInfo.ray&&(i._lastPointerRay[o].origin.copyFrom(t.pickInfo.ray.origin),i._lastPointerRay[o].direction.copyFrom(t.pickInfo.ray.direction),i.currentDraggingPointerID==o&&i.dragging&&i._moveDrag(t.pickInfo.ray))}}),this._beforeRenderObserver=this._scene.onBeforeRenderObservable.add(function(){i._moving&&i.moveAttached&&(l.a._RemoveAndStorePivotPoint(i.attachedNode),i._targetPosition.subtractToRef(i.attachedNode.absolutePosition,i._tmpVector),i._tmpVector.scaleInPlace(i.dragDeltaRatio),i.attachedNode.getAbsolutePosition().addToRef(i._tmpVector,i._tmpVector),i.validateDrag(i._tmpVector)&&i.attachedNode.setAbsolutePosition(i._tmpVector),l.a._RestorePivotPoint(i.attachedNode))})},e.prototype.releaseDrag=function(){this.dragging=!1,this.onDragEndObservable.notifyObservers({dragPlanePoint:this.lastDragPosition,pointerId:this.currentDraggingPointerID}),this.currentDraggingPointerID=-1,this._moving=!1,this.detachCameraControls&&this._attachedElement&&this._scene.activeCamera&&!this._scene.activeCamera.leftCamera&&this._scene.activeCamera.attachControl(this._attachedElement,!0)},e.prototype.startDrag=function(t,i,n){void 0===t&&(t=e._AnyMouseID),this._startDrag(t,i,n);var r=this._lastPointerRay[t];t===e._AnyMouseID&&(r=this._lastPointerRay[Object.keys(this._lastPointerRay)[0]]),r&&this._moveDrag(r)},e.prototype._startDrag=function(e,t,i){if(this._scene.activeCamera&&!this.dragging&&this.attachedNode){l.a._RemoveAndStorePivotPoint(this.attachedNode),t?(this._startDragRay.direction.copyFrom(t.direction),this._startDragRay.origin.copyFrom(t.origin)):(this._startDragRay.origin.copyFrom(this._scene.activeCamera.position),this.attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector),this._tmpVector.subtractToRef(this._scene.activeCamera.position,this._startDragRay.direction)),this._updateDragPlanePosition(this._startDragRay,i||this._tmpVector);var n=this._pickWithRayOnDragPlane(this._startDragRay);n&&(this.dragging=!0,this.currentDraggingPointerID=e,this.lastDragPosition.copyFrom(n),this.onDragStartObservable.notifyObservers({dragPlanePoint:n,pointerId:this.currentDraggingPointerID}),this._targetPosition.copyFrom(this.attachedNode.absolutePosition),this.detachCameraControls&&this._scene.activeCamera&&!this._scene.activeCamera.leftCamera&&(this._scene.activeCamera.inputs.attachedElement?(this._attachedElement=this._scene.activeCamera.inputs.attachedElement,this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement)):this._attachedElement=null)),l.a._RestorePivotPoint(this.attachedNode)}},e.prototype._moveDrag=function(e){this._moving=!0;var t=this._pickWithRayOnDragPlane(e);if(t){this.updateDragPlane&&this._updateDragPlanePosition(e,t);var i=0;this._options.dragAxis?(s.x.TransformCoordinatesToRef(this._options.dragAxis,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._worldDragAxis),t.subtractToRef(this.lastDragPosition,this._tmpVector),i=s.x.Dot(this._tmpVector,this._worldDragAxis),this._worldDragAxis.scaleToRef(i,this._dragDelta)):(i=this._dragDelta.length(),t.subtractToRef(this.lastDragPosition,this._dragDelta)),this._targetPosition.addInPlace(this._dragDelta),this.onDragObservable.notifyObservers({dragDistance:i,delta:this._dragDelta,dragPlanePoint:t,dragPlaneNormal:this._dragPlane.forward,pointerId:this.currentDraggingPointerID}),this.lastDragPosition.copyFrom(t)}},e.prototype._pickWithRayOnDragPlane=function(t){var i=this;if(!t)return null;var n=Math.acos(s.x.Dot(this._dragPlane.forward,t.direction));if(n>Math.PI/2&&(n=Math.PI-n),this.maxDragAngle>0&&n>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*s.x.Dot(this._alternatePickedPoint,this._tmpVector)),this._tmpVector.addInPlace(this._alternatePickedPoint);var r=s.x.Dot(this._dragPlane.forward,this._tmpVector);return this._dragPlane.forward.scaleToRef(-r,this._alternatePickedPoint),this._alternatePickedPoint.addInPlace(this._tmpVector),this._alternatePickedPoint.addInPlace(this.attachedNode.absolutePosition),this._alternatePickedPoint}return null}var o=e._planeScene.pickWithRay(t,function(e){return e==i._dragPlane});return o&&o.hit&&o.pickedMesh&&o.pickedPoint?o.pickedPoint:null},e.prototype._updateDragPlanePosition=function(e,t){this._pointA.copyFrom(t),this._options.dragAxis?(this.useObjectOrienationForDragging?s.x.TransformCoordinatesToRef(this._options.dragAxis,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._localAxis):this._localAxis.copyFrom(this._options.dragAxis),this._pointA.addToRef(this._localAxis,this._pointB),e.origin.subtractToRef(this._pointA,this._pointC),this._pointA.addToRef(this._pointC.normalize(),this._pointC),this._pointB.subtractToRef(this._pointA,this._lineA),this._pointC.subtractToRef(this._pointA,this._lineB),s.x.CrossToRef(this._lineA,this._lineB,this._lookAt),s.x.CrossToRef(this._lineA,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.useObjectOrienationForDragging?s.x.TransformCoordinatesToRef(this._options.dragPlaneNormal,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._localAxis):this._localAxis.copyFrom(this._options.dragPlaneNormal),this._dragPlane.position.copyFrom(this._pointA),this._pointA.addToRef(this._localAxis,this._lookAt),this._dragPlane.lookAt(this._lookAt)):(this._dragPlane.position.copyFrom(this._pointA),this._dragPlane.lookAt(e.origin)),this._dragPlane.position.copyFrom(this.attachedNode.absolutePosition),this._dragPlane.computeWorldMatrix(!0)},e.prototype.detach=function(){this._pointerObserver&&this._scene.onPointerObservable.remove(this._pointerObserver),this._beforeRenderObserver&&this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver),this.releaseDrag()},e._AnyMouseID=-2,e}())},function(e,t,i){"use strict";i.d(t,"a",function(){return o});var n=i(0),r=i(4),o=function(){function e(){this._pickingUnavailable=!1,this.hit=!1,this.distance=0,this.pickedPoint=null,this.pickedMesh=null,this.bu=0,this.bv=0,this.faceId=-1,this.subMeshId=0,this.pickedSprite=null,this.originMesh=null,this.ray=null}return e.prototype.getNormal=function(e,t){if(void 0===e&&(e=!1),void 0===t&&(t=!0),!this.pickedMesh||!this.pickedMesh.isVerticesDataPresent(r.b.NormalKind))return null;var i,o=this.pickedMesh.getIndices();if(!o)return null;if(t){var s=this.pickedMesh.getVerticesData(r.b.NormalKind),a=n.x.FromArray(s,3*o[3*this.faceId]),c=n.x.FromArray(s,3*o[3*this.faceId+1]),l=n.x.FromArray(s,3*o[3*this.faceId+2]);a=a.scale(this.bu),c=c.scale(this.bv),l=l.scale(1-this.bu-this.bv),i=new n.x(a.x+c.x+l.x,a.y+c.y+l.y,a.z+c.z+l.z)}else{var u=this.pickedMesh.getVerticesData(r.b.PositionKind),h=n.x.FromArray(u,3*o[3*this.faceId]),d=n.x.FromArray(u,3*o[3*this.faceId+1]),f=n.x.FromArray(u,3*o[3*this.faceId+2]),p=h.subtract(d),_=f.subtract(d);i=n.x.Cross(p,_)}if(e){var m=this.pickedMesh.getWorldMatrix();this.pickedMesh.nonUniformScaling&&(n.t.Matrix[0].copyFrom(m),(m=n.t.Matrix[0]).setTranslationFromFloats(0,0,0),m.invert(),m.transposeToRef(n.t.Matrix[1]),m=n.t.Matrix[1]),i=n.x.TransformNormal(i,m)}return i.normalize(),i},e.prototype.getTextureCoordinates=function(){if(!this.pickedMesh||!this.pickedMesh.isVerticesDataPresent(r.b.UVKind))return null;var e=this.pickedMesh.getIndices();if(!e)return null;var t=this.pickedMesh.getVerticesData(r.b.UVKind);if(!t)return null;var i=n.w.FromArray(t,2*e[3*this.faceId]),o=n.w.FromArray(t,2*e[3*this.faceId+1]),s=n.w.FromArray(t,2*e[3*this.faceId+2]);return i=i.scale(1-this.bu-this.bv),o=o.scale(this.bu),s=s.scale(this.bv),new n.w(i.x+o.x+s.x,i.y+o.y+s.y)},e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return r}),i.d(t,"b",function(){return o}),i.d(t,"c",function(){return s});var n=i(1),r=function(){function e(){}return e.KEYDOWN=1,e.KEYUP=2,e}(),o=function(){return function(e,t){this.type=e,this.event=t}}(),s=function(e){function t(t,i){var n=e.call(this,t,i)||this;return n.type=t,n.event=i,n.skipOnPointerObservable=!1,n}return n.d(t,e),t}(o)},function(e,t,i){"use strict";i.d(t,"a",function(){return s});var n=i(0),r=i(5),o=i(12);o.a.CreateBox=function(e){var t,i=[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],r=[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],s=[],a=e.width||e.size||1,c=e.height||e.size||1,l=e.depth||e.size||1,u=e.wrap||!1,h=void 0===e.topBaseAt?1:e.topBaseAt,d=void 0===e.bottomBaseAt?0:e.bottomBaseAt,f=[2,0,3,1][h=(h+4)%4],p=[2,0,1,3][d=(d+4)%4],_=[1,-1,1,-1,-1,1,-1,1,1,1,1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,-1,1,-1,1,1,1,1,-1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-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(u){i=[2,3,0,2,0,1,4,5,6,4,6,7,9,10,11,9,11,8,12,14,15,12,13,14],_=[-1,1,1,1,1,1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,1,1,1,-1,1,-1,-1,1,-1,1,-1,1,-1,-1,1,1,-1,-1,1,-1,-1,-1];for(var m=[[1,1,1],[-1,1,1],[-1,1,-1],[1,1,-1]],g=[[-1,-1,1],[1,-1,1],[1,-1,-1],[-1,-1,-1]],v=[17,18,19,16],y=[22,23,20,21];f>0;)m.unshift(m.pop()),v.unshift(v.pop()),f--;for(;p>0;)g.unshift(g.pop()),y.unshift(y.pop()),p--;m=m.flat(),g=g.flat(),_=_.concat(m).concat(g),i.push(v[0],v[2],v[3],v[0],v[1],v[2]),i.push(y[0],y[2],y[3],y[0],y[1],y[2])}var b=[a/2,c/2,l/2];t=_.reduce(function(e,t,i){return e.concat(t*b[i%3])},[]);for(var T=0===e.sideOrientation?0:e.sideOrientation||o.a.DEFAULTSIDE,E=e.faceUV||new Array(6),x=e.faceColors,A=[],P=0;P<6;P++)void 0===E[P]&&(E[P]=new n.y(0,0,1,1)),x&&void 0===x[P]&&(x[P]=new n.f(1,1,1,1));for(var R=0;R<6;R++)if(s.push(E[R].z,E[R].w),s.push(E[R].x,E[R].w),s.push(E[R].x,E[R].y),s.push(E[R].z,E[R].y),x)for(var S=0;S<4;S++)A.push(x[R].r,x[R].g,x[R].b,x[R].a);o.a._ComputeSides(T,t,i,r,s,e.frontUVs,e.backUVs);var C=new o.a;if(C.indices=i,C.positions=t,C.normals=r,C.uvs=s,x){var M=T===o.a.DOUBLESIDE?A.concat(A):A;C.colors=M}return C},r.a.CreateBox=function(e,t,i,n,r){void 0===i&&(i=null);var o={size:t,sideOrientation:r,updatable:n};return s.CreateBox(e,o,i)};var s=function(){function e(){}return e.CreateBox=function(e,t,i){void 0===i&&(i=null);var n=new r.a(e,i);return t.sideOrientation=r.a._GetDefaultSideOrientation(t.sideOrientation),n._originalBuilderSideOrientation=t.sideOrientation,o.a.CreateBox(t).applyToMesh(n,t.updatable),n},e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return a});var n=i(0),r=i(5),o=i(12),s=i(16);o.a.CreateCylinder=function(e){var t,i=e.height||2,s=0===e.diameterTop?0:e.diameterTop||e.diameter||1,a=0===e.diameterBottom?0:e.diameterBottom||e.diameter||1,c=e.tessellation||24,l=e.subdivisions||1,u=!!e.hasRings,h=!!e.enclose,d=e.cap||r.a.CAP_ALL,f=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,p=0===e.sideOrientation?0:e.sideOrientation||o.a.DEFAULTSIDE,_=e.faceUV||new Array(3),m=e.faceColors,g=2+(1+(1!==f&&h?2:0))*(u?l:1);for(t=0;t0&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices)),this._indexBuffer&&(this._indexBuffer.references=t),e._syncGeometryWithMorphTargetManager(),e.synchronizeInstances()},e.prototype.notifyUpdate=function(e){this.onGeometryUpdated&&this.onGeometryUpdated(this,e);for(var t=0,i=this._meshes;t0){for(var t=0;t0){for(t=0;t0){for(t=0;t0){var u=new Float32Array(t,l.positionsAttrDesc.offset,l.positionsAttrDesc.count);i.setVerticesData(o.b.PositionKind,u,!1)}if(l.normalsAttrDesc&&l.normalsAttrDesc.count>0){var h=new Float32Array(t,l.normalsAttrDesc.offset,l.normalsAttrDesc.count);i.setVerticesData(o.b.NormalKind,h,!1)}if(l.tangetsAttrDesc&&l.tangetsAttrDesc.count>0){var d=new Float32Array(t,l.tangetsAttrDesc.offset,l.tangetsAttrDesc.count);i.setVerticesData(o.b.TangentKind,d,!1)}if(l.uvsAttrDesc&&l.uvsAttrDesc.count>0){var f=new Float32Array(t,l.uvsAttrDesc.offset,l.uvsAttrDesc.count);i.setVerticesData(o.b.UVKind,f,!1)}if(l.uvs2AttrDesc&&l.uvs2AttrDesc.count>0){var p=new Float32Array(t,l.uvs2AttrDesc.offset,l.uvs2AttrDesc.count);i.setVerticesData(o.b.UV2Kind,p,!1)}if(l.uvs3AttrDesc&&l.uvs3AttrDesc.count>0){var _=new Float32Array(t,l.uvs3AttrDesc.offset,l.uvs3AttrDesc.count);i.setVerticesData(o.b.UV3Kind,_,!1)}if(l.uvs4AttrDesc&&l.uvs4AttrDesc.count>0){var m=new Float32Array(t,l.uvs4AttrDesc.offset,l.uvs4AttrDesc.count);i.setVerticesData(o.b.UV4Kind,m,!1)}if(l.uvs5AttrDesc&&l.uvs5AttrDesc.count>0){var g=new Float32Array(t,l.uvs5AttrDesc.offset,l.uvs5AttrDesc.count);i.setVerticesData(o.b.UV5Kind,g,!1)}if(l.uvs6AttrDesc&&l.uvs6AttrDesc.count>0){var v=new Float32Array(t,l.uvs6AttrDesc.offset,l.uvs6AttrDesc.count);i.setVerticesData(o.b.UV6Kind,v,!1)}if(l.colorsAttrDesc&&l.colorsAttrDesc.count>0){var y=new Float32Array(t,l.colorsAttrDesc.offset,l.colorsAttrDesc.count);i.setVerticesData(o.b.ColorKind,y,!1,l.colorsAttrDesc.stride)}if(l.matricesIndicesAttrDesc&&l.matricesIndicesAttrDesc.count>0){for(var b=new Int32Array(t,l.matricesIndicesAttrDesc.offset,l.matricesIndicesAttrDesc.count),T=[],E=0;E>8),T.push((16711680&x)>>16),T.push(x>>24)}i.setVerticesData(o.b.MatricesIndicesKind,T,!1)}if(l.matricesWeightsAttrDesc&&l.matricesWeightsAttrDesc.count>0){var A=new Float32Array(t,l.matricesWeightsAttrDesc.offset,l.matricesWeightsAttrDesc.count);i.setVerticesData(o.b.MatricesWeightsKind,A,!1)}if(l.indicesAttrDesc&&l.indicesAttrDesc.count>0){var P=new Int32Array(t,l.indicesAttrDesc.offset,l.indicesAttrDesc.count);i.setIndices(P,null)}if(l.subMeshesAttrDesc&&l.subMeshesAttrDesc.count>0){var R=new Int32Array(t,l.subMeshesAttrDesc.offset,5*l.subMeshesAttrDesc.count);i.subMeshes=[];for(E=0;E>8),T.push((16711680&D)>>16),T.push(D>>24)}i.setVerticesData(o.b.MatricesIndicesKind,T,t.matricesIndices._updatable)}if(t.matricesIndicesExtra)if(t.matricesIndicesExtra._isExpanded)delete t.matricesIndices._isExpanded,i.setVerticesData(o.b.MatricesIndicesExtraKind,t.matricesIndicesExtra,t.matricesIndicesExtra._updatable);else{for(T=[],E=0;E>8),T.push((16711680&D)>>16),T.push(D>>24)}i.setVerticesData(o.b.MatricesIndicesExtraKind,T,t.matricesIndicesExtra._updatable)}t.matricesWeights&&(e._CleanMatricesWeights(t,i),i.setVerticesData(o.b.MatricesWeightsKind,t.matricesWeights,t.matricesWeights._updatable)),t.matricesWeightsExtra&&i.setVerticesData(o.b.MatricesWeightsExtraKind,t.matricesWeightsExtra,t.matricesWeights._updatable),i.setIndices(t.indices,null)}if(t.subMeshes){i.subMeshes=[];for(var L=0;L-1){var n=t.getScene().getLastSkeletonByID(e.skeletonId);if(n){i=n.bones.length;for(var r=t.getVerticesData(o.b.MatricesIndicesKind),s=t.getVerticesData(o.b.MatricesIndicesExtraKind),c=e.matricesWeights,l=e.matricesWeightsExtra,u=e.numBoneInfluencer,h=c.length,d=0;du-1)&&(p=u-1),f>.001){var g=1/f;for(_=0;_<4;_++)c[d+_]*=g;if(l)for(_=0;_<4;_++)l[d+_]*=g}else p>=4?(l[d+p-4]=1-f,s[d+p-4]=i):(c[d+p]=1-f,r[d+p]=i)}t.setVerticesData(o.b.MatricesIndicesKind,r),e.matricesWeightsExtra&&t.setVerticesData(o.b.MatricesIndicesExtraKind,s)}}}},e.Parse=function(t,i,s){if(i.getGeometryByID(t.id))return null;var a=new e(t.id,i,void 0,t.updatable);return h.a&&h.a.AddTagsTo(a,t.tags),t.delayLoadingFile?(a.delayLoadState=l.a.DELAYLOADSTATE_NOTLOADED,a.delayLoadingFile=s+t.delayLoadingFile,a._boundingInfo=new c.a(n.x.FromArray(t.boundingBoxMinimum),n.x.FromArray(t.boundingBoxMaximum)),a._delayInfo=[],t.hasUVs&&a._delayInfo.push(o.b.UVKind),t.hasUVs2&&a._delayInfo.push(o.b.UV2Kind),t.hasUVs3&&a._delayInfo.push(o.b.UV3Kind),t.hasUVs4&&a._delayInfo.push(o.b.UV4Kind),t.hasUVs5&&a._delayInfo.push(o.b.UV5Kind),t.hasUVs6&&a._delayInfo.push(o.b.UV6Kind),t.hasColors&&a._delayInfo.push(o.b.ColorKind),t.hasMatricesIndices&&a._delayInfo.push(o.b.MatricesIndicesKind),t.hasMatricesWeights&&a._delayInfo.push(o.b.MatricesWeightsKind),a._delayLoadingFunction=r.a.ImportVertexData):r.a.ImportVertexData(t,a),i.pushGeometry(a,!0),a},e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return d});var n=i(1),r=i(9),o=i(0),s=i(39),a=i(54),c=i(50),l=i(46),u=i(38),h=i(30),d=function(e){function t(i,n,s,a){void 0===n&&(n=o.e.Gray()),void 0===s&&(s=u.a.DefaultUtilityLayer),void 0===a&&(a=null);var l=e.call(this,s)||this;l._pointerObserver=null,l.snapDistance=0,l.onSnapObservable=new r.c,l._isEnabled=!0,l._parent=null,l._parent=a,l._coloredMaterial=new h.a("",s.utilityLayerScene),l._coloredMaterial.diffuseColor=n,l._coloredMaterial.specularColor=n.subtract(new o.e(.1,.1,.1)),l._hoverMaterial=new h.a("",s.utilityLayerScene),l._hoverMaterial.diffuseColor=n.add(new o.e(.3,.3,.3)),l._arrow=t._CreateArrow(s.utilityLayerScene,l._coloredMaterial),l._arrow.lookAt(l._rootMesh.position.add(i)),l._arrow.scaling.scaleInPlace(1/3),l._arrow.parent=l._rootMesh;var d=0,f=new o.x,p={snapDistance:0};l.dragBehavior=new c.a({dragAxis:i}),l.dragBehavior.moveAttached=!1,l._rootMesh.addBehavior(l.dragBehavior);var _=new o.x,m=new o.j;l.dragBehavior.onDragObservable.add(function(e){if(l.attachedMesh)if(l.attachedMesh.parent?(l.attachedMesh.parent.computeWorldMatrix().invertToRef(m),m.setTranslationFromFloats(0,0,0),o.x.TransformCoordinatesToRef(e.delta,m,_)):_.copyFrom(e.delta),0==l.snapDistance)l.attachedMesh.position.addInPlace(_);else if(d+=e.dragDistance,Math.abs(d)>l.snapDistance){var t=Math.floor(Math.abs(d)/l.snapDistance);d%=l.snapDistance,_.normalizeToRef(f),f.scaleInPlace(l.snapDistance*t),l.attachedMesh.position.addInPlace(f),p.snapDistance=l.snapDistance*t,l.onSnapObservable.notifyObservers(p)}}),l._pointerObserver=s.utilityLayerScene.onPointerObservable.add(function(e){if(!l._customMeshSet){var t=e.pickInfo&&-1!=l._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh)?l._hoverMaterial:l._coloredMaterial;l._rootMesh.getChildMeshes().forEach(function(e){e.material=t,e.color&&(e.color=t.diffuseColor)})}});var g=s._getSharedGizmoLight();return g.includedOnlyMeshes=g.includedOnlyMeshes.concat(l._rootMesh.getChildMeshes(!1)),l}return n.d(t,e),t._CreateArrow=function(e,t){var i=new s.a("arrow",e),n=a.a.CreateCylinder("cylinder",{diameterTop:0,height:.075,diameterBottom:.0375,tessellation:96},e),r=a.a.CreateCylinder("cylinder",{diameterTop:.005,height:.275,diameterBottom:.005,tessellation:96},e);return r.material=t,n.parent=i,r.parent=i,n.material=t,n.rotation.x=Math.PI/2,n.position.z+=.3,r.position.z+=.1375,r.rotation.x=Math.PI/2,i},t._CreateArrowInstance=function(e,t){for(var i=new s.a("arrow",e),n=0,r=t.getChildMeshes();n=this.subMaterials.length?this.getScene().defaultMaterial:this.subMaterials[e]},t.prototype.getActiveTextures=function(){var t;return(t=e.prototype.getActiveTextures.call(this)).concat.apply(t,this.subMaterials.map(function(e){return e?e.getActiveTextures():[]}))},t.prototype.getClassName=function(){return"MultiMaterial"},t.prototype.isReadyForSubMesh=function(e,t,i){for(var n=0;n=0&&r.multiMaterials.splice(o,1),e.prototype.dispose.call(this,t,i)}},t.ParseMultiMaterial=function(e,i){var n=new t(e.name,i);n.id=e.id,o.a&&o.a.AddTagsTo(n,e.tags);for(var r=0;r-1&&this._debugMeshMeshes.splice(o,1),this._numMeshes--,this._numMeshes>0?(this._meshes[n]=this._meshes[this._numMeshes],this._impostors[n]=this._impostors[this._numMeshes],this._meshes[this._numMeshes]=null,this._impostors[this._numMeshes]=null):(this._meshes[0]=null,this._impostors[0]=null),t=!0;break}t&&0===this._numMeshes&&this._scene.unregisterBeforeRender(this._renderFunction)}},e.prototype._getDebugMaterial=function(e){return this._debugMaterial||(this._debugMaterial=new r.a("",e),this._debugMaterial.wireframe=!0,this._debugMaterial.emissiveColor=n.e.White(),this._debugMaterial.disableLighting=!0),this._debugMaterial},e.prototype._getDebugBoxMesh=function(e){return this._debugBoxMesh||(this._debugBoxMesh=_.a.CreateBox("physicsBodyBoxViewMesh",{size:1},e),this._debugBoxMesh.rotationQuaternion=n.q.Identity(),this._debugBoxMesh.material=this._getDebugMaterial(e),this._debugBoxMesh.setEnabled(!1)),this._debugBoxMesh.createInstance("physicsBodyBoxViewInstance")},e.prototype._getDebugSphereMesh=function(e){return this._debugSphereMesh||(this._debugSphereMesh=m.a.CreateSphere("physicsBodySphereViewMesh",{diameter:1},e),this._debugSphereMesh.rotationQuaternion=n.q.Identity(),this._debugSphereMesh.material=this._getDebugMaterial(e),this._debugSphereMesh.setEnabled(!1)),this._debugSphereMesh.createInstance("physicsBodyBoxViewInstance")},e.prototype._getDebugCylinderMesh=function(e){return this._debugCylinderMesh||(this._debugCylinderMesh=b.a.CreateCylinder("physicsBodyCylinderViewMesh",{diameterTop:1,diameterBottom:1,height:1},e),this._debugCylinderMesh.rotationQuaternion=n.q.Identity(),this._debugCylinderMesh.material=this._getDebugMaterial(e),this._debugCylinderMesh.setEnabled(!1)),this._debugCylinderMesh.createInstance("physicsBodyBoxViewInstance")},e.prototype._getDebugMeshMesh=function(e,t){var i=new p.a(e.name,t,null,e);return i.position=n.x.Zero(),i.setParent(e),i.material=this._getDebugMaterial(t),this._debugMeshMeshes.push(i),i},e.prototype._getDebugMesh=function(e,t){var i=this;if(!this._utilityLayer)return null;if(t&&t.parent&&t.parent.physicsImpostor)return null;var n=null,r=this._utilityLayer.utilityLayerScene;switch(e.type){case v.a.BoxImpostor:n=this._getDebugBoxMesh(r),e.getBoxSizeToRef(n.scaling);break;case v.a.SphereImpostor:n=this._getDebugSphereMesh(r);var o=e.getRadius();n.scaling.x=2*o,n.scaling.y=2*o,n.scaling.z=2*o;break;case v.a.MeshImpostor:t&&(n=this._getDebugMeshMesh(t,r));break;case v.a.NoImpostor:if(t)t.getChildMeshes().filter(function(e){return e.physicsImpostor?1:0}).forEach(function(e){i._getDebugBoxMesh(r).parent=e});break;case v.a.CylinderImpostor:n=this._getDebugCylinderMesh(r);var s=e.object.getBoundingInfo();n.scaling.x=s.boundingBox.maximum.x-s.boundingBox.minimum.x,n.scaling.y=s.boundingBox.maximum.y-s.boundingBox.minimum.y,n.scaling.z=s.boundingBox.maximum.z-s.boundingBox.minimum.z}return n},e.prototype.dispose=function(){for(var e=this._numMeshes,t=0;t=0;a--){var c=e[a],l=c.getParent();if(l){var u=this._debugLines[r];u||(u=[n.x.Zero(),n.x.Zero()],this._debugLines[r]=u),c.getAbsolutePositionToRef(o,u[0]),l.getAbsolutePositionToRef(o,u[1]),u[0].subtractInPlace(s),u[1].subtractInPlace(s),r++}}},e.prototype.update=function(){if(this._utilityLayer){this.autoUpdateBonesMatrices&&this.skeleton.computeAbsoluteTransforms();var e=this.mesh._effectiveMesh;void 0===this.skeleton.bones[0].length?this._getLinesForBonesNoLength(this.skeleton.bones,e.getWorldMatrix()):this._getLinesForBonesWithLength(this.skeleton.bones,e.getWorldMatrix());var t=this._utilityLayer.utilityLayerScene;this._debugMesh?E.a.CreateLineSystem("",{lines:this._debugLines,updatable:!0,instance:this._debugMesh},t):(this._debugMesh=E.a.CreateLineSystem("",{lines:this._debugLines,updatable:!0,instance:null},t),this._debugMesh.renderingGroupId=this.renderingGroupId),this._debugMesh.position.copyFrom(this.mesh.position),this._debugMesh.color=this.color}},e.prototype.dispose=function(){this.isEnabled=!1,this._debugMesh&&(this.isEnabled=!1,this._debugMesh.dispose(),this._debugMesh=null),this._utilityLayer&&(this._utilityLayer.dispose(),this._utilityLayer=null)},e}();i.d(t,"AxesViewer",function(){return s}),i.d(t,"BoneAxesViewer",function(){return c}),i.d(t,"DebugLayer",function(){return f}),i.d(t,"PhysicsViewer",function(){return T}),i.d(t,"RayHelper",function(){return x}),i.d(t,"SkeletonViewer",function(){return A})},function(e,t,i){"use strict";i.d(t,"a",function(){return d});var n=i(1),r=i(2),o=i(0),s=i(4),a=i(8),c=i(14),l=i(6),u=i(23),h=i(22),d=function(e){function t(t,i,r,s){void 0===s&&(s={});var a=e.call(this,t,i)||this;return a._textures={},a._textureArrays={},a._floats={},a._ints={},a._floatsArrays={},a._colors3={},a._colors3Arrays={},a._colors4={},a._vectors2={},a._vectors3={},a._vectors4={},a._matrices={},a._matrices3x3={},a._matrices2x2={},a._vectors2Arrays={},a._vectors3Arrays={},a._cachedWorldViewMatrix=new o.j,a._cachedWorldViewProjectionMatrix=new o.j,a._shaderPath=r,a._options=n.a({needAlphaBlending:!1,needAlphaTesting:!1,attributes:["position","normal","uv"],uniforms:["worldViewProjection"],uniformBuffers:[],samplers:[],defines:[]},s),a}return n.d(t,e),Object.defineProperty(t.prototype,"options",{get:function(){return this._options},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"ShaderMaterial"},t.prototype.needAlphaBlending=function(){return this.alpha<1||this._options.needAlphaBlending},t.prototype.needAlphaTesting=function(){return this._options.needAlphaTesting},t.prototype._checkUniform=function(e){-1===this._options.uniforms.indexOf(e)&&this._options.uniforms.push(e)},t.prototype.setTexture=function(e,t){return-1===this._options.samplers.indexOf(e)&&this._options.samplers.push(e),this._textures[e]=t,this},t.prototype.setTextureArray=function(e,t){return-1===this._options.samplers.indexOf(e)&&this._options.samplers.push(e),this._checkUniform(e),this._textureArrays[e]=t,this},t.prototype.setFloat=function(e,t){return this._checkUniform(e),this._floats[e]=t,this},t.prototype.setInt=function(e,t){return this._checkUniform(e),this._ints[e]=t,this},t.prototype.setFloats=function(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this},t.prototype.setColor3=function(e,t){return this._checkUniform(e),this._colors3[e]=t,this},t.prototype.setColor3Array=function(e,t){return this._checkUniform(e),this._colors3Arrays[e]=t.reduce(function(e,t){return t.toArray(e,e.length),e},[]),this},t.prototype.setColor4=function(e,t){return this._checkUniform(e),this._colors4[e]=t,this},t.prototype.setVector2=function(e,t){return this._checkUniform(e),this._vectors2[e]=t,this},t.prototype.setVector3=function(e,t){return this._checkUniform(e),this._vectors3[e]=t,this},t.prototype.setVector4=function(e,t){return this._checkUniform(e),this._vectors4[e]=t,this},t.prototype.setMatrix=function(e,t){return this._checkUniform(e),this._matrices[e]=t,this},t.prototype.setMatrix3x3=function(e,t){return this._checkUniform(e),this._matrices3x3[e]=t,this},t.prototype.setMatrix2x2=function(e,t){return this._checkUniform(e),this._matrices2x2[e]=t,this},t.prototype.setArray2=function(e,t){return this._checkUniform(e),this._vectors2Arrays[e]=t,this},t.prototype.setArray3=function(e,t){return this._checkUniform(e),this._vectors3Arrays[e]=t,this},t.prototype._checkCache=function(e,t){return!e||(this._effect&&this._effect.defines.indexOf("#define INSTANCES"),!1)},t.prototype.isReadyForSubMesh=function(e,t,i){return this.isReady(e,i)},t.prototype.isReady=function(e,t){var i=this.getScene(),n=i.getEngine();if(!this.checkReadyOnEveryCall&&this._renderId===i.getRenderId()&&this._checkCache(e,t))return!0;for(var r=[],o=[],a=new l.c,u=0;u4&&(o.push(s.b.MatricesIndicesExtraKind),o.push(s.b.MatricesWeightsExtraKind));var h=e.skeleton;r.push("#define NUM_BONE_INFLUENCERS "+e.numBoneInfluencers),a.addCPUSkinningFallback(0,e),h.isUsingTextureForMatrices?(r.push("#define BONETEXTURE"),-1===this._options.uniforms.indexOf("boneTextureWidth")&&this._options.uniforms.push("boneTextureWidth"),-1===this._options.samplers.indexOf("boneSampler")&&this._options.samplers.push("boneSampler")):(r.push("#define BonesPerMesh "+(h.bones.length+1)),-1===this._options.uniforms.indexOf("mBones")&&this._options.uniforms.push("mBones"))}else r.push("#define NUM_BONE_INFLUENCERS 0");for(var d in this._textures)if(!this._textures[d].isReady())return!1;e&&this._shouldTurnAlphaTestOn(e)&&r.push("#define ALPHATEST");var f=this._effect,p=r.join("\n");return this._effect=n.createEffect(this._shaderPath,{attributes:o,uniformsNames:this._options.uniforms,uniformBuffersNames:this._options.uniformBuffers,samplers:this._options.samplers,defines:p,fallbacks:a,onCompiled:this.onCompiled,onError:this.onError},n),!!this._effect.isReady()&&(f!==this._effect&&i.resetCachedMaterial(),this._renderId=i.getRenderId(),!0)},t.prototype.bindOnlyWorldMatrix=function(e){var t=this.getScene();this._effect&&(-1!==this._options.uniforms.indexOf("world")&&this._effect.setMatrix("world",e),-1!==this._options.uniforms.indexOf("worldView")&&(e.multiplyToRef(t.getViewMatrix(),this._cachedWorldViewMatrix),this._effect.setMatrix("worldView",this._cachedWorldViewMatrix)),-1!==this._options.uniforms.indexOf("worldViewProjection")&&(e.multiplyToRef(t.getTransformMatrix(),this._cachedWorldViewProjectionMatrix),this._effect.setMatrix("worldViewProjection",this._cachedWorldViewProjectionMatrix)))},t.prototype.bind=function(e,t){if(this.bindOnlyWorldMatrix(e),this._effect&&this.getScene().getCachedMaterial()!==this){var i;for(i in-1!==this._options.uniforms.indexOf("view")&&this._effect.setMatrix("view",this.getScene().getViewMatrix()),-1!==this._options.uniforms.indexOf("projection")&&this._effect.setMatrix("projection",this.getScene().getProjectionMatrix()),-1!==this._options.uniforms.indexOf("viewProjection")&&this._effect.setMatrix("viewProjection",this.getScene().getTransformMatrix()),c.a.BindBonesParameters(t,this._effect),this._textures)this._effect.setTexture(i,this._textures[i]);for(i in this._textureArrays)this._effect.setTextureArray(i,this._textureArrays[i]);for(i in this._ints)this._effect.setInt(i,this._ints[i]);for(i in this._floats)this._effect.setFloat(i,this._floats[i]);for(i in this._floatsArrays)this._effect.setArray(i,this._floatsArrays[i]);for(i in this._colors3)this._effect.setColor3(i,this._colors3[i]);for(i in this._colors3Arrays)this._effect.setArray3(i,this._colors3Arrays[i]);for(i in this._colors4){var n=this._colors4[i];this._effect.setFloat4(i,n.r,n.g,n.b,n.a)}for(i in this._vectors2)this._effect.setVector2(i,this._vectors2[i]);for(i in this._vectors3)this._effect.setVector3(i,this._vectors3[i]);for(i in this._vectors4)this._effect.setVector4(i,this._vectors4[i]);for(i in this._matrices)this._effect.setMatrix(i,this._matrices[i]);for(i in this._matrices3x3)this._effect.setMatrix3x3(i,this._matrices3x3[i]);for(i in this._matrices2x2)this._effect.setMatrix2x2(i,this._matrices2x2[i]);for(i in this._vectors2Arrays)this._effect.setArray2(i,this._vectors2Arrays[i]);for(i in this._vectors3Arrays)this._effect.setArray3(i,this._vectors3Arrays[i])}this._afterBind(t)},t.prototype.getActiveTextures=function(){var t=e.prototype.getActiveTextures.call(this);for(var i in this._textures)t.push(this._textures[i]);for(var i in this._textureArrays)for(var n=this._textureArrays[i],r=0;ru-n)&&(!(c-hh-o)&&!(l-dd-s))},e.prototype.intersectsSphere=function(t){return e.IntersectsSphere(this.minimumWorld,this.maximumWorld,t.centerWorld,t.radiusWorld)},e.prototype.intersectsMinMax=function(e,t){var i=this.minimumWorld,n=this.maximumWorld,r=i.x,o=i.y,s=i.z,a=n.x,c=n.y,l=n.z,u=e.x,h=e.y,d=e.z,f=t.x,p=t.y,_=t.z;return!(af)&&(!(cp)&&!(l_))},e.Intersects=function(e,t){return e.intersectsMinMax(t.minimumWorld,t.maximumWorld)},e.IntersectsSphere=function(t,i,n,o){var s=e.TmpVector3[0];return r.x.ClampToRef(n,t,i,s),r.x.DistanceSquared(n,s)<=o*o},e.IsCompletelyInFrustum=function(e,t){for(var i=0;i<6;++i)for(var n=t[i],r=0;r<8;++r)if(n.dotCoordinate(e[r])<0)return!1;return!0},e.IsInFrustum=function(e,t){for(var i=0;i<6;++i){for(var n=!0,r=t[i],o=0;o<8;++o)if(r.dotCoordinate(e[o])>=0){n=!1;break}if(n)return!1}return!0},e.TmpVector3=n.a.BuildArray(3,r.x.Zero),e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return r});var n=i(3),r=function(){function e(){this.hoverCursor="",this.actions=new Array,this.isRecursive=!1}return Object.defineProperty(e,"HasTriggers",{get:function(){for(var t in e.Triggers)if(e.Triggers.hasOwnProperty(t))return!0;return!1},enumerable:!0,configurable:!0}),Object.defineProperty(e,"HasPickTriggers",{get:function(){for(var t in e.Triggers)if(e.Triggers.hasOwnProperty(t)){var i=parseInt(t);if(i>=n.a.ACTION_OnPickTrigger&&i<=n.a.ACTION_OnPickUpTrigger)return!0}return!1},enumerable:!0,configurable:!0}),e.HasSpecificTrigger=function(t){for(var i in e.Triggers){if(e.Triggers.hasOwnProperty(i))if(parseInt(i)===t)return!0}return!1},e.Triggers={},e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return o});var n=i(34),r=i(0),o=function(){function e(e,t,i){this.center=r.x.Zero(),this.centerWorld=r.x.Zero(),this.minimum=r.x.Zero(),this.maximum=r.x.Zero(),this.reConstruct(e,t,i)}return e.prototype.reConstruct=function(e,t,i){this.minimum.copyFrom(e),this.maximum.copyFrom(t);var n=r.x.Distance(e,t);t.addToRef(e,this.center).scaleInPlace(.5),this.radius=.5*n,this._update(i||r.j.IdentityReadOnly)},e.prototype.scale=function(t){var i=this.radius*t,n=e.TmpVector3,r=n[0].setAll(i),o=this.center.subtractToRef(r,n[1]),s=this.center.addToRef(r,n[2]);return this.reConstruct(o,s,this._worldMatrix),this},e.prototype.getWorldMatrix=function(){return this._worldMatrix},e.prototype._update=function(t){if(t.isIdentity())this.centerWorld.copyFrom(this.center),this.radiusWorld=this.radius;else{r.x.TransformCoordinatesToRef(this.center,t,this.centerWorld);var i=e.TmpVector3[0];r.x.TransformNormalFromFloatsToRef(1,1,1,t,i),this.radiusWorld=Math.max(Math.abs(i.x),Math.abs(i.y),Math.abs(i.z))*this.radius}},e.prototype.isInFrustum=function(e){for(var t=this.centerWorld,i=this.radiusWorld,n=0;n<6;n++)if(e[n].dotCoordinate(t)<=-i)return!1;return!0},e.prototype.isCenterInFrustum=function(e){for(var t=this.centerWorld,i=0;i<6;i++)if(e[i].dotCoordinate(t)<0)return!1;return!0},e.prototype.intersectsPoint=function(e){var t=r.x.DistanceSquared(this.centerWorld,e);return!(this.radiusWorld*this.radiusWorldthis.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 t=0;t-1)return!0}return!1},t.prototype.hasSpecificTriggers2=function(e,t){for(var i=0;i=t.OnPickTrigger&&i.trigger<=t.OnPointerOutTrigger)return!0}return!1},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"hasPickTriggers",{get:function(){for(var e=0;e=t.OnPickTrigger&&i.trigger<=t.OnPickUpTrigger)return!0}return!1},enumerable:!0,configurable:!0}),t.prototype.registerAction=function(e){return e.trigger===t.OnEveryFrameTrigger&&this.getScene().actionManager!==this?(p.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 i=this.actions.indexOf(e);return-1!==i&&(this.actions.splice(i,1),t.Triggers[e.trigger]-=1,0===t.Triggers[e.trigger]&&delete t.Triggers[e.trigger],delete e._actionManager,!0)},t.prototype.processTrigger=function(e,i){for(var n=0;n0;if(2===e.type?f.push(r):f.push(i),m){for(var g=new Array,v=0;v0){var p=f.properties[0].value,_=null===f.properties[0].targetType?p:n.getMeshByName(p);_._meshId&&(_.mesh=n.getMeshByID(_._meshId)),d={trigger:t[f.name],parameter:_}}else d=t[f.name];for(var m=0;m=0;o--)this._keys[o].frame>=n&&this._keys[o].frame<=r&&this._keys.splice(o,1);this._ranges[e]=null}},e.prototype.getRange=function(e){return this._ranges[e]},e.prototype.getKeys=function(){return this._keys},e.prototype.getHighestFrame=function(){for(var e=0,t=0,i=this._keys.length;t0)return i.highLimitValue.clone?i.highLimitValue.clone():i.highLimitValue;var n=this._keys;if(1===n.length)return this._getKeyValue(n[0].value);var r=i.key;if(n[r].frame>=t)for(;r-1>=0&&n[r].frame>=t;)r--;for(var o=r;o=t){i.key=o;var a=n[o],c=this._getKeyValue(a.value);if(a.interpolation===I.STEP)return c;var l=this._getKeyValue(s.value),u=void 0!==a.outTangent&&void 0!==s.inTangent,h=s.frame-a.frame,d=(t-a.frame)/h,f=this.getEasingFunction();switch(null!=f&&(d=f.ease(d)),this.dataType){case e.ANIMATIONTYPE_FLOAT:var p=u?this.floatInterpolateFunctionWithTangents(c,a.outTangent*h,l,s.inTangent*h,d):this.floatInterpolateFunction(c,l,d);switch(i.loopMode){case e.ANIMATIONLOOPMODE_CYCLE:case e.ANIMATIONLOOPMODE_CONSTANT:return p;case e.ANIMATIONLOOPMODE_RELATIVE:return i.offsetValue*i.repeatCount+p}break;case e.ANIMATIONTYPE_QUATERNION:var _=u?this.quaternionInterpolateFunctionWithTangents(c,a.outTangent.scale(h),l,s.inTangent.scale(h),d):this.quaternionInterpolateFunction(c,l,d);switch(i.loopMode){case e.ANIMATIONLOOPMODE_CYCLE:case e.ANIMATIONLOOPMODE_CONSTANT:return _;case e.ANIMATIONLOOPMODE_RELATIVE:return _.addInPlace(i.offsetValue.scale(i.repeatCount))}return _;case e.ANIMATIONTYPE_VECTOR3:var m=u?this.vector3InterpolateFunctionWithTangents(c,a.outTangent.scale(h),l,s.inTangent.scale(h),d):this.vector3InterpolateFunction(c,l,d);switch(i.loopMode){case e.ANIMATIONLOOPMODE_CYCLE:case e.ANIMATIONLOOPMODE_CONSTANT:return m;case e.ANIMATIONLOOPMODE_RELATIVE:return m.add(i.offsetValue.scale(i.repeatCount))}case e.ANIMATIONTYPE_VECTOR2:var g=u?this.vector2InterpolateFunctionWithTangents(c,a.outTangent.scale(h),l,s.inTangent.scale(h),d):this.vector2InterpolateFunction(c,l,d);switch(i.loopMode){case e.ANIMATIONLOOPMODE_CYCLE:case e.ANIMATIONLOOPMODE_CONSTANT:return g;case e.ANIMATIONLOOPMODE_RELATIVE:return g.add(i.offsetValue.scale(i.repeatCount))}case e.ANIMATIONTYPE_SIZE:switch(i.loopMode){case e.ANIMATIONLOOPMODE_CYCLE:case e.ANIMATIONLOOPMODE_CONSTANT:return this.sizeInterpolateFunction(c,l,d);case e.ANIMATIONLOOPMODE_RELATIVE:return this.sizeInterpolateFunction(c,l,d).add(i.offsetValue.scale(i.repeatCount))}case e.ANIMATIONTYPE_COLOR3:switch(i.loopMode){case e.ANIMATIONLOOPMODE_CYCLE:case e.ANIMATIONLOOPMODE_CONSTANT:return this.color3InterpolateFunction(c,l,d);case e.ANIMATIONLOOPMODE_RELATIVE:return this.color3InterpolateFunction(c,l,d).add(i.offsetValue.scale(i.repeatCount))}case e.ANIMATIONTYPE_MATRIX:switch(i.loopMode){case e.ANIMATIONLOOPMODE_CYCLE:case e.ANIMATIONLOOPMODE_CONSTANT:if(e.AllowMatricesInterpolation)return this.matrixInterpolateFunction(c,l,d,i.workValue);case e.ANIMATIONLOOPMODE_RELATIVE:return c}}break}}return this._getKeyValue(n[n.length-1].value)},e.prototype.matrixInterpolateFunction=function(t,i,n,r){return e.AllowMatrixDecomposeForInterpolation?r?(o.j.DecomposeLerpToRef(t,i,n,r),r):o.j.DecomposeLerp(t,i,n):r?(o.j.LerpToRef(t,i,n,r),r):o.j.Lerp(t,i,n)},e.prototype.clone=function(){var t=new e(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 i in t._ranges={},this._ranges){var n=this._ranges[i];n&&(t._ranges[i]=n.clone())}return t},e.prototype.setKeys=function(e){this._keys=e.slice(0)},e.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 i=this.dataType;t.keys=[];for(var n=this.getKeys(),r=0;r=1&&(c=u.values[1]),u.values.length>=2&&(l=u.values[2]);break;case e.ANIMATIONTYPE_QUATERNION:if(i=o.q.FromArray(u.values),u.values.length>=8){var h=o.q.FromArray(u.values.slice(4,8));h.equals(o.q.Zero())||(c=h)}if(u.values.length>=12){var d=o.q.FromArray(u.values.slice(8,12));d.equals(o.q.Zero())||(l=d)}break;case e.ANIMATIONTYPE_MATRIX:i=o.j.FromArray(u.values);break;case e.ANIMATIONTYPE_COLOR3:i=o.e.FromArray(u.values);break;case e.ANIMATIONTYPE_VECTOR3:default:i=o.x.FromArray(u.values)}var f={};f.frame=u.frame,f.value=i,null!=c&&(f.inTangent=c),null!=l&&(f.outTangent=l),a.push(f)}if(r.setKeys(a),t.ranges)for(n=0;n0&&h.forEach(function(e){r._events.push(e._clone())}),this._enableBlending=e&&e.animationPropertiesOverride?e.animationPropertiesOverride.enableBlending:this._animation.enableBlending}return Object.defineProperty(e.prototype,"currentFrame",{get:function(){return this._currentFrame},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"weight",{get:function(){return this._weight},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"currentValue",{get:function(){return this._currentValue},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"targetPath",{get:function(){return this._targetPath},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"target",{get:function(){return this._currentActiveTarget},enumerable:!0,configurable:!0}),e.prototype._preparePath=function(e,t){void 0===t&&(t=0);var i=this._animation.targetPropertyPath;if(i.length>1){for(var n=e[i[0]],r=1;r-1&&this._animation.runtimeAnimations.splice(e,1)},e.prototype.setValue=function(e,t){if(this._targetIsArray)for(var i=0;it[t.length-1].frame&&(e=t[t.length-1].frame);var i=this._events;if(i.length)for(var n=0;nthis._maxFrame)&&(t=this._minFrame),(ithis._maxFrame)&&(i=this._maxFrame);var l,u,h=i-t,d=e*(s.framePerSecond*r)/1e3+this._ratioOffset,f=0;if(this._previousDelay=e,this._previousRatio=d,!n&&i>=t&&d>=h)c=!1,f=s._getKeyValue(this._maxValue);else if(!n&&t>=i&&d<=h)c=!1,f=s._getKeyValue(this._minValue);else if(this._animationState.loopMode!==B.ANIMATIONLOOPMODE_CYCLE){var p=i.toString()+t.toString();if(!this._offsetsCache[p]){this._animationState.repeatCount=0,this._animationState.loopMode=B.ANIMATIONLOOPMODE_CYCLE;var _=s._interpolate(t,this._animationState),m=s._interpolate(i,this._animationState);switch(this._animationState.loopMode=this._getCorrectLoopMode(),s.dataType){case B.ANIMATIONTYPE_FLOAT:this._offsetsCache[p]=m-_;break;case B.ANIMATIONTYPE_QUATERNION:this._offsetsCache[p]=m.subtract(_);break;case B.ANIMATIONTYPE_VECTOR3:this._offsetsCache[p]=m.subtract(_);case B.ANIMATIONTYPE_VECTOR2:this._offsetsCache[p]=m.subtract(_);case B.ANIMATIONTYPE_SIZE:this._offsetsCache[p]=m.subtract(_);case B.ANIMATIONTYPE_COLOR3:this._offsetsCache[p]=m.subtract(_)}this._highLimitsCache[p]=m}f=this._highLimitsCache[p],l=this._offsetsCache[p]}if(void 0===l)switch(s.dataType){case B.ANIMATIONTYPE_FLOAT:l=0;break;case B.ANIMATIONTYPE_QUATERNION:l=V;break;case B.ANIMATIONTYPE_VECTOR3:l=k;break;case B.ANIMATIONTYPE_VECTOR2:l=G;break;case B.ANIMATIONTYPE_SIZE:l=z;break;case B.ANIMATIONTYPE_COLOR3:l=j}if(this._host&&this._host.syncRoot){var g=this._host.syncRoot;u=t+(i-t)*((g.masterFrame-g.fromFrame)/(g.toFrame-g.fromFrame))}else u=c&&0!==h?t+d%h:i;var v=this._events;if((h>0&&this.currentFrame>u||h<0&&this.currentFrame>0,this._animationState.highLimitValue=f,this._animationState.offsetValue=l;var b=s._interpolate(u,this._animationState);if(this.setValue(b,o),v.length)for(y=0;y0&&u>=v[y].frame&&v[y].frame>=t||h<0&&u<=v[y].frame&&v[y].frame<=t){var T=v[y];T.isDone||(T.onlyOnce&&(v.splice(y,1),y--),T.isDone=!0,T.action(u))}return c||(this._stopped=!0),c},e}(),H=i(16),X=i(48),Y=i(34),K=function(e){function t(t,i,n,r,s,a,c){void 0===n&&(n=null),void 0===r&&(r=null),void 0===s&&(s=null),void 0===a&&(a=null),void 0===c&&(c=null);var l=e.call(this,t,i.getScene(),!1)||this;return l.name=t,l.children=new Array,l.animations=new Array,l._index=null,l._absoluteTransform=new o.j,l._invertedAbsoluteTransform=new o.j,l._scalingDeterminant=1,l._worldTransform=new o.j,l._needToDecompose=!0,l._needToCompose=!1,l._linkedTransformNode=null,l._waitingTransformNodeId=null,l._skeleton=i,l._localMatrix=r?r.clone():o.j.Identity(),l._restPose=s||l._localMatrix.clone(),l._baseMatrix=a||l._localMatrix.clone(),l._index=c,i.bones.push(l),l.setParent(n,!1),(a||r)&&l._updateDifferenceMatrix(),l}return l.d(t,e),Object.defineProperty(t.prototype,"_matrix",{get:function(){return this._compose(),this._localMatrix},set:function(e){this._localMatrix.copyFrom(e),this._needToDecompose=!0},enumerable:!0,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.setParent=function(e,t){if(void 0===t&&(t=!0),this._parent!==e){if(this._parent){var i=this._parent.children.indexOf(this);-1!==i&&this._parent.children.splice(i,1)}this._parent=e,this._parent&&this._parent.children.push(this),t&&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.getWorldMatrix=function(){return this._worldTransform},t.prototype.returnToRest=function(){this.updateMatrix(this._restPose.clone())},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++},Object.defineProperty(t.prototype,"position",{get:function(){return this._decompose(),this._localPosition},set:function(e){this._decompose(),this._localPosition.copyFrom(e),this._markAsDirtyAndCompose()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rotation",{get:function(){return this.getRotation()},set:function(e){this.setRotation(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"rotationQuaternion",{get:function(){return this._decompose(),this._localRotation},set:function(e){this.setRotationQuaternion(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"scaling",{get:function(){return this.getScale()},set:function(e){this.setScale(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"animationPropertiesOverride",{get:function(){return this._skeleton.animationPropertiesOverride},enumerable:!0,configurable:!0}),t.prototype._decompose=function(){this._needToDecompose&&(this._needToDecompose=!1,this._localScaling||(this._localScaling=o.x.Zero(),this._localRotation=o.q.Zero(),this._localPosition=o.x.Zero()),this._localMatrix.decompose(this._localScaling,this._localRotation,this._localPosition))},t.prototype._compose=function(){this._needToCompose&&(this._localScaling?(this._needToCompose=!1,o.j.ComposeToRef(this._localScaling,this._localRotation,this._localPosition,this._localMatrix)):this._needToCompose=!1)},t.prototype.updateMatrix=function(e,t,i){void 0===t&&(t=!0),void 0===i&&(i=!0),this._baseMatrix.copyFrom(e),t&&this._updateDifferenceMatrix(),i?(this._localMatrix.copyFrom(e),this._markAsDirtyAndDecompose()):this.markAsDirty()},t.prototype._updateDifferenceMatrix=function(e,t){if(void 0===t&&(t=!0),e||(e=this._baseMatrix),this._parent?e.multiplyToRef(this._parent._absoluteTransform,this._absoluteTransform):this._absoluteTransform.copyFrom(e),this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform),t)for(var i=0;i-1&&(this._scene._activeAnimatables.splice(t,1),this._scene._activeAnimatables.push(this))}return this},e.prototype.getAnimations=function(){return this._runtimeAnimations},e.prototype.appendAnimations=function(e,t){for(var i=this,n=0;n-1){for(var n=(o=this._runtimeAnimations).length-1;n>=0;n--){var r=o[n];e&&r.animation.name!=e||(t&&!t(r.target)||(r.dispose(),o.splice(n,1)))}0==o.length&&(this._scene._activeAnimatables.splice(i,1),this._raiseOnAnimationEnd())}}else{if((n=this._scene._activeAnimatables.indexOf(this))>-1){this._scene._activeAnimatables.splice(n,1);var o=this._runtimeAnimations;for(n=0;n0)return;this._animationTimeLast=t}var i=this.useConstantAnimationDeltaTime?16:(t-this._animationTimeLast)*this.animationTimeScale;this._animationTime+=i;var n=this._animationTime;this._animationTimeLast=t;for(var r=0;ri&&r>0&&(r*=-1),a&&this.stopAnimation(e,void 0,c),s||(s=new Q(this,e,t,i,n,r,o,void 0,l));var u=!c||c(e);if(e.animations&&u&&s.appendAnimations(e,e.animations),e.getAnimatables)for(var h=e.getAnimatables(),d=0;d=l&&s.frame<=u&&(n?(c=s.value.clone(),_?(a=c.getTranslation(),c.setTranslation(a.scaleInPlace(m))):g&&r?(a=c.getTranslation(),c.setTranslation(a.multiplyInPlace(r))):c=s.value):c=s.value,v.push({frame:s.frame+i,value:c}));return this.animations[0].createRange(t,l+i,u+i),!0};var q=function(){function e(){}return e.prototype.serialize=function(){var e={};return e.animation=this.animation.serialize(),e.targetId=this.target.id,e},e}(),Z=function(){function e(e,t){void 0===t&&(t=null),this.name=e,this._targetedAnimations=new Array,this._animatables=new Array,this._from=Number.MAX_VALUE,this._to=-Number.MAX_VALUE,this._speedRatio=1,this._loopAnimation=!1,this.onAnimationEndObservable=new r.c,this.onAnimationLoopObservable=new r.c,this.onAnimationGroupEndObservable=new r.c,this.onAnimationGroupPauseObservable=new r.c,this.onAnimationGroupPlayObservable=new r.c,this._scene=t||R.a.LastCreatedScene,this.uniqueId=this._scene.getUniqueId(),this._scene.animationGroups.push(this)}return Object.defineProperty(e.prototype,"from",{get:function(){return this._from},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"to",{get:function(){return this._to},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isStarted",{get:function(){return this._isStarted},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isPlaying",{get:function(){return this._isStarted&&!this._isPaused},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"speedRatio",{get:function(){return this._speedRatio},set:function(e){if(this._speedRatio!==e){this._speedRatio=e;for(var t=0;tn[0].frame&&(this._from=n[0].frame),this._toe){var s={frame:e,value:r.value,inTangent:r.inTangent,outTangent:r.outTangent,interpolation:r.interpolation};n.splice(0,0,s)}if(o.framen&&this._speedRatio>0&&(this._speedRatio=-t);return this._isStarted=!0,this._isPaused=!1,this.onAnimationGroupPlayObservable.notifyObservers(this),this},e.prototype.pause=function(){if(!this._isStarted)return this;this._isPaused=!0;for(var e=0;e-1&&this._scene.animationGroups.splice(e,1),this.onAnimationEndObservable.clear(),this.onAnimationGroupEndObservable.clear(),this.onAnimationGroupPauseObservable.clear(),this.onAnimationGroupPlayObservable.clear(),this.onAnimationLoopObservable.clear()},e.prototype._checkAnimationGroupEnded=function(e){var t=this._animatables.indexOf(e);t>-1&&this._animatables.splice(t,1),0===this._animatables.length&&(this._isStarted=!1,this.onAnimationGroupEndObservable.notifyObservers(this))},e.prototype.clone=function(t,i){for(var n=new e(t||this.name,this._scene),r=0,o=this._targetedAnimations;r=.5?.5*(1-this.easeInCore(2*(1-t)))+.5:.5*this.easeInCore(2*t)},e.EASINGMODE_EASEIN=0,e.EASINGMODE_EASEOUT=1,e.EASINGMODE_EASEINOUT=2,e}(),ee=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return l.d(t,e),t.prototype.easeInCore=function(e){return e=Math.max(0,Math.min(1,e)),1-Math.sqrt(1-e*e)},t}($),te=function(e){function t(t){void 0===t&&(t=1);var i=e.call(this)||this;return i.amplitude=t,i}return l.d(t,e),t.prototype.easeInCore=function(e){var t=Math.max(0,this.amplitude);return Math.pow(e,3)-e*t*Math.sin(3.141592653589793*e)},t}($),ie=function(e){function t(t,i){void 0===t&&(t=3),void 0===i&&(i=2);var n=e.call(this)||this;return n.bounces=t,n.bounciness=i,n}return l.d(t,e),t.prototype.easeInCore=function(e){var t=Math.max(0,this.bounces),i=this.bounciness;i<=1&&(i=1.001);var n=Math.pow(i,t),r=1-i,o=(1-n)/r+.5*n,s=e*o,a=Math.log(-s*(1-i)+1)/Math.log(i),c=Math.floor(a),l=c+1,u=(1-Math.pow(i,c))/(r*o),h=.5*(u+(1-Math.pow(i,l))/(r*o)),d=e-h,f=h-u;return-Math.pow(1/i,t-c)/(f*f)*(d-f)*(d+f)},t}($),ne=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return l.d(t,e),t.prototype.easeInCore=function(e){return e*e*e},t}($),re=function(e){function t(t,i){void 0===t&&(t=3),void 0===i&&(i=3);var n=e.call(this)||this;return n.oscillations=t,n.springiness=i,n}return l.d(t,e),t.prototype.easeInCore=function(e){var t=Math.max(0,this.oscillations),i=Math.max(0,this.springiness);return(0==i?e:(Math.exp(i*e)-1)/(Math.exp(i)-1))*Math.sin((6.283185307179586*t+1.5707963267948966)*e)},t}($),oe=function(e){function t(t){void 0===t&&(t=2);var i=e.call(this)||this;return i.exponent=t,i}return l.d(t,e),t.prototype.easeInCore=function(e){return this.exponent<=0?e:(Math.exp(this.exponent*e)-1)/(Math.exp(this.exponent)-1)},t}($),se=function(e){function t(t){void 0===t&&(t=2);var i=e.call(this)||this;return i.power=t,i}return l.d(t,e),t.prototype.easeInCore=function(e){var t=Math.max(0,this.power);return Math.pow(e,t)},t}($),ae=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return l.d(t,e),t.prototype.easeInCore=function(e){return e*e},t}($),ce=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return l.d(t,e),t.prototype.easeInCore=function(e){return e*e*e*e},t}($),le=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return l.d(t,e),t.prototype.easeInCore=function(e){return e*e*e*e*e},t}($),ue=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return l.d(t,e),t.prototype.easeInCore=function(e){return 1-Math.sin(1.5707963267948966*(1-e))},t}($),he=function(e){function t(t,i,n,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=1),void 0===r&&(r=1);var o=e.call(this)||this;return o.x1=t,o.y1=i,o.x2=n,o.y2=r,o}return l.d(t,e),t.prototype.easeInCore=function(e){return o.d.Interpolate(e,this.x1,this.y1,this.x2,this.y2)},t}($),de=function(){function e(e,t,i){this.frame=e,this.action=t,this.onlyOnce=i,this.isDone=!1}return e.prototype._clone=function(){return new e(this.frame,this.action,this.onlyOnce)},e}(),fe=i(5),pe=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return l.d(t,e),t}(n.a),_e=function(e){function t(t){var i=e.call(this)||this;return i.scene=t,i.sounds=[],i.effectLayers=[],i.layers=[],i.lensFlareSystems=[],i.proceduralTextures=[],i.reflectionProbes=[],i}return l.d(t,e),t.prototype.addAllToScene=function(){var e=this;this.cameras.forEach(function(t){e.scene.addCamera(t)}),this.lights.forEach(function(t){e.scene.addLight(t)}),this.meshes.forEach(function(t){e.scene.addMesh(t)}),this.skeletons.forEach(function(t){e.scene.addSkeleton(t)}),this.animations.forEach(function(t){e.scene.addAnimation(t)}),this.animationGroups.forEach(function(t){e.scene.addAnimationGroup(t)}),this.multiMaterials.forEach(function(t){e.scene.addMultiMaterial(t)}),this.materials.forEach(function(t){e.scene.addMaterial(t)}),this.morphTargetManagers.forEach(function(t){e.scene.addMorphTargetManager(t)}),this.geometries.forEach(function(t){e.scene.addGeometry(t)}),this.transformNodes.forEach(function(t){e.scene.addTransformNode(t)}),this.actionManagers.forEach(function(t){e.scene.addActionManager(t)}),this.textures.forEach(function(t){e.scene.addTexture(t)}),this.reflectionProbes.forEach(function(t){e.scene.addReflectionProbe(t)}),this.environmentTexture&&(this.scene.environmentTexture=this.environmentTexture);for(var t=0,i=this.scene._serializableComponents;t0&&(h=!0,this._soundLoaded(i));break;case"String":u.push(i);case"Array":0===u.length&&(u=i);for(var d=0;d0&&(this._htmlAudioElement.currentTime=0)):this._streamingSource.disconnect(),this.isPlaying=!1;else if(me.b.audioEngine.audioContext&&this._soundSource){var i=e?me.b.audioEngine.audioContext.currentTime+e:me.b.audioEngine.audioContext.currentTime;this._soundSource.stop(i),this._soundSource.onended=function(){t.isPlaying=!1},this.isPaused||(this._startOffset=0)}},e.prototype.pause=function(){this.isPlaying&&(this.isPaused=!0,this._streaming?this._htmlAudioElement?this._htmlAudioElement.pause():this._streamingSource.disconnect():me.b.audioEngine.audioContext&&(this.stop(0),this._startOffset+=me.b.audioEngine.audioContext.currentTime-this._startTime))},e.prototype.setVolume=function(e,t){me.b.audioEngine.canUseWebAudio&&this._soundGain&&(t&&me.b.audioEngine.audioContext?(this._soundGain.gain.cancelScheduledValues(me.b.audioEngine.audioContext.currentTime),this._soundGain.gain.setValueAtTime(this._soundGain.gain.value,me.b.audioEngine.audioContext.currentTime),this._soundGain.gain.linearRampToValueAtTime(e,me.b.audioEngine.audioContext.currentTime+t)):this._soundGain.gain.value=e),this._volume=e},e.prototype.setPlaybackRate=function(e){this._playbackRate=e,this.isPlaying&&(this._streaming&&this._htmlAudioElement?this._htmlAudioElement.playbackRate=this._playbackRate:this._soundSource&&(this._soundSource.playbackRate.value=this._playbackRate))},e.prototype.getVolume=function(){return this._volume},e.prototype.attachToMesh=function(e){var t=this;this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null),this._connectedTransformNode=e,this.spatialSound||(this.spatialSound=!0,this._createSpatialParameters(),this.isPlaying&&this.loop&&(this.stop(),this.play())),this._onRegisterAfterWorldMatrixUpdate(this._connectedTransformNode),this._registerFunc=function(e){return t._onRegisterAfterWorldMatrixUpdate(e)},this._connectedTransformNode.registerAfterWorldMatrixUpdate(this._registerFunc)},e.prototype.detachFromMesh=function(){this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null,this._connectedTransformNode=null)},e.prototype._onRegisterAfterWorldMatrixUpdate=function(e){if(e.getBoundingInfo){var t=e;if(this._positionInEmitterSpace)t.worldMatrixFromCache.invertToRef(o.t.Matrix[0]),this.setPosition(o.t.Matrix[0].getTranslation());else{var i=t.getBoundingInfo();this.setPosition(i.boundingSphere.centerWorld)}me.b.audioEngine.canUseWebAudio&&this._isDirectional&&this.isPlaying&&this._updateDirection()}},e.prototype.clone=function(){var t=this;if(this._streaming)return null;var i=function(){t._isReadyToPlay?(r._audioBuffer=t.getAudioBuffer(),r._isReadyToPlay=!0,r.autoplay&&r.play()):window.setTimeout(i,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},r=new e(this.name+"_cloned",new ArrayBuffer(0),this._scene,null,n);return this.useCustomAttenuation&&r.setAttenuationFunction(this._customAttenuationFunction),r.setPosition(this._position),r.setPlaybackRate(this._playbackRate),i(),r},e.prototype.getAudioBuffer=function(){return this._audioBuffer},e.prototype.serialize=function(){var e={name:this.name,url:this.name,autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this.spatialSound,maxDistance:this.maxDistance,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel,playbackRate:this._playbackRate,panningModel:this._panningModel,soundTrackId:this.soundTrackId};return this.spatialSound&&(this._connectedTransformNode&&(e.connectedMeshId=this._connectedTransformNode.id),e.position=this._position.asArray(),e.refDistance=this.refDistance,e.distanceModel=this.distanceModel,e.isDirectional=this._isDirectional,e.localDirectionToMesh=this._localDirection.asArray(),e.coneInnerAngle=this._coneInnerAngle,e.coneOuterAngle=this._coneOuterAngle,e.coneOuterGain=this._coneOuterGain),e},e.Parse=function(t,i,n,r){var s,a=t.name;s=t.url?n+t.url:n+a;var c,l={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(r){var u=function(){r._isReadyToPlay?(c._audioBuffer=r.getAudioBuffer(),c._isReadyToPlay=!0,c.autoplay&&c.play()):window.setTimeout(u,300)};c=new e(a,new ArrayBuffer(0),i,null,l),u()}else c=new e(a,s,i,function(){i._removePendingData(c)},l),i._addPendingData(c);if(t.position){var h=o.x.FromArray(t.position);c.setPosition(h)}if(t.isDirectional&&(c.setDirectionalCone(t.coneInnerAngle||360,t.coneOuterAngle||360,t.coneOuterGain||0),t.localDirectionToMesh)){var d=o.x.FromArray(t.localDirectionToMesh);c.setLocalDirectionToMesh(d)}if(t.connectedMeshId){var f=i.getMeshByID(t.connectedMeshId);f&&c.attachToMesh(f)}return c},e._SceneComponentInitialization=function(e){throw be.a.WarnImport("AudioSceneComponent")},e}(),Ee=function(){function e(e,t){void 0===t&&(t={}),this.id=-1,this._isMainTrack=!1,this._isInitialized=!1,this._scene=e,this.soundCollection=new Array,this._options=t,!this._isMainTrack&&this._scene.soundTracks&&(this._scene.soundTracks.push(this),this.id=this._scene.soundTracks.length-1)}return e.prototype._initializeSoundTrackAudioGraph=function(){me.b.audioEngine.canUseWebAudio&&me.b.audioEngine.audioContext&&(this._outputAudioNode=me.b.audioEngine.audioContext.createGain(),this._outputAudioNode.connect(me.b.audioEngine.masterGain),this._options&&(this._options.volume&&(this._outputAudioNode.gain.value=this._options.volume),this._options.mainTrack&&(this._isMainTrack=this._options.mainTrack)),this._isInitialized=!0)},e.prototype.dispose=function(){if(me.b.audioEngine&&me.b.audioEngine.canUseWebAudio){for(this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas();this.soundCollection.length;)this.soundCollection[0].dispose();this._outputAudioNode&&this._outputAudioNode.disconnect(),this._outputAudioNode=null}},e.prototype.AddSound=function(e){this._isInitialized||this._initializeSoundTrackAudioGraph(),me.b.audioEngine.canUseWebAudio&&this._outputAudioNode&&e.connectToSoundTrackAudioNode(this._outputAudioNode),e.soundTrackId&&(-1===e.soundTrackId?this._scene.mainSoundTrack.RemoveSound(e):this._scene.soundTracks&&this._scene.soundTracks[e.soundTrackId].RemoveSound(e)),this.soundCollection.push(e),e.soundTrackId=this.id},e.prototype.RemoveSound=function(e){var t=this.soundCollection.indexOf(e);-1!==t&&this.soundCollection.splice(t,1)},e.prototype.setVolume=function(e){me.b.audioEngine.canUseWebAudio&&this._outputAudioNode&&(this._outputAudioNode.gain.value=e)},e.prototype.switchPanningModelToHRTF=function(){if(me.b.audioEngine.canUseWebAudio)for(var e=0;e0?e.activeCameras[0]:e.activeCamera)&&i.audioContext){i.audioContext.listener.setPosition(t.position.x,t.position.y,t.position.z),t.rigCameras&&t.rigCameras.length>0&&(t=t.rigCameras[0]);var n,r=o.j.Invert(t.getViewMatrix()),s=o.x.TransformNormal(new o.x(0,0,-1),r);for(s.normalize(),isNaN(s.x)||isNaN(s.y)||isNaN(s.z)||i.audioContext.listener.setOrientation(s.x,s.y,s.z,0,1,0),n=0;n0?1/r:0,c=0;c0},enumerable:!0,configurable:!0}),e.prototype.init=function(){},e.prototype.attach=function(e){var t=this;this._attachedCamera=e;var i=this._attachedCamera.getScene();this._onPrePointerObservableObserver=i.onPrePointerObservable.add(function(e){e.type!==Re.a.POINTERDOWN?e.type===Re.a.POINTERUP&&(t._isPointerDown=!1):t._isPointerDown=!0}),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add(function(){var e=X.a.Now,i=0;null!=t._lastFrameTime&&(i=e-t._lastFrameTime),t._lastFrameTime=e,t._applyUserInteraction();var n=e-t._lastInteractionTime-t._idleRotationWaitTime,r=Math.max(Math.min(n/t._idleRotationSpinupTime,1),0);t._cameraRotationSpeed=t._idleRotationSpeed*r,t._attachedCamera&&(t._attachedCamera.alpha-=t._cameraRotationSpeed*(i/1e3))})},e.prototype.detach=function(){if(this._attachedCamera){var e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._attachedCamera=null}},e.prototype._userIsZooming=function(){return!!this._attachedCamera&&0!==this._attachedCamera.inertialRadiusOffset},e.prototype._shouldAnimationStopForInteraction=function(){if(!this._attachedCamera)return!1;var e=!1;return this._lastFrameRadius===this._attachedCamera.radius&&0!==this._attachedCamera.inertialRadiusOffset&&(e=!0),this._lastFrameRadius=this._attachedCamera.radius,this._zoomStopsAnimation?e:this._userIsZooming()},e.prototype._applyUserInteraction=function(){this._userIsMoving()&&!this._shouldAnimationStopForInteraction()&&(this._lastInteractionTime=X.a.Now)},e.prototype._userIsMoving=function(){return!!this._attachedCamera&&(0!==this._attachedCamera.inertialAlphaOffset||0!==this._attachedCamera.inertialBetaOffset||0!==this._attachedCamera.inertialRadiusOffset||0!==this._attachedCamera.inertialPanningX||0!==this._attachedCamera.inertialPanningY||this._isPointerDown)},e}(),Ce=function(){function e(){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(e.prototype,"name",{get:function(){return"Bouncing"},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"autoTransitionRange",{get:function(){return this._autoTransitionRange},set:function(e){var t=this;if(this._autoTransitionRange!==e){this._autoTransitionRange=e;var i=this._attachedCamera;i&&(e?this._onMeshTargetChangedObserver=i.onMeshTargetChangedObservable.add(function(e){if(e){e.computeWorldMatrix(!0);var i=e.getBoundingInfo().diagonalLength;t.lowerRadiusTransitionRange=.05*i,t.upperRadiusTransitionRange=.05*i}}):this._onMeshTargetChangedObserver&&i.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver))}},enumerable:!0,configurable:!0}),e.prototype.init=function(){},e.prototype.attach=function(e){var t=this;this._attachedCamera=e,this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add(function(){t._attachedCamera&&(t._isRadiusAtLimit(t._attachedCamera.lowerRadiusLimit)&&t._applyBoundRadiusAnimation(t.lowerRadiusTransitionRange),t._isRadiusAtLimit(t._attachedCamera.upperRadiusLimit)&&t._applyBoundRadiusAnimation(t.upperRadiusTransitionRange))})},e.prototype.detach=function(){this._attachedCamera&&(this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null)},e.prototype._isRadiusAtLimit=function(e){return!!this._attachedCamera&&(this._attachedCamera.radius===e&&!this._radiusIsAnimating)},e.prototype._applyBoundRadiusAnimation=function(t){var i=this;if(this._attachedCamera){this._radiusBounceTransition||(e.EasingFunction.setEasingMode(e.EasingMode),this._radiusBounceTransition=B.CreateAnimation("radius",B.ANIMATIONTYPE_FLOAT,60,e.EasingFunction)),this._cachedWheelPrecision=this._attachedCamera.wheelPrecision,this._attachedCamera.wheelPrecision=1/0,this._attachedCamera.inertialRadiusOffset=0,this.stopAllAnimations(),this._radiusIsAnimating=!0;var n=B.TransitionTo("radius",this._attachedCamera.radius+t,this._attachedCamera,this._attachedCamera.getScene(),60,this._radiusBounceTransition,this.transitionDuration,function(){return i._clearAnimationLocks()});n&&this._animatables.push(n)}},e.prototype._clearAnimationLocks=function(){this._radiusIsAnimating=!1,this._attachedCamera&&(this._attachedCamera.wheelPrecision=this._cachedWheelPrecision)},e.prototype.stopAllAnimations=function(){for(this._attachedCamera&&(this._attachedCamera.animations=[]);this._animatables.length;)this._animatables[0].onAnimationEnd=null,this._animatables[0].stop(),this._animatables.shift()},e.EasingFunction=new te(.3),e.EasingMode=$.EASINGMODE_EASEOUT,e}(),Me=function(){function e(){this._mode=e.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(e.prototype,"name",{get:function(){return"Framing"},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"mode",{get:function(){return this._mode},set:function(e){this._mode=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"radiusScale",{get:function(){return this._radiusScale},set:function(e){this._radiusScale=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"positionScale",{get:function(){return this._positionScale},set:function(e){this._positionScale=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"defaultElevation",{get:function(){return this._defaultElevation},set:function(e){this._defaultElevation=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"elevationReturnTime",{get:function(){return this._elevationReturnTime},set:function(e){this._elevationReturnTime=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"elevationReturnWaitTime",{get:function(){return this._elevationReturnWaitTime},set:function(e){this._elevationReturnWaitTime=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"zoomStopsAnimation",{get:function(){return this._zoomStopsAnimation},set:function(e){this._zoomStopsAnimation=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"framingTime",{get:function(){return this._framingTime},set:function(e){this._framingTime=e},enumerable:!0,configurable:!0}),e.prototype.init=function(){},e.prototype.attach=function(t){var i=this;this._attachedCamera=t;var n=this._attachedCamera.getScene();e.EasingFunction.setEasingMode(e.EasingMode),this._onPrePointerObservableObserver=n.onPrePointerObservable.add(function(e){e.type!==Re.a.POINTERDOWN?e.type===Re.a.POINTERUP&&(i._isPointerDown=!1):i._isPointerDown=!0}),this._onMeshTargetChangedObserver=t.onMeshTargetChangedObservable.add(function(e){e&&i.zoomOnMesh(e)}),this._onAfterCheckInputsObserver=t.onAfterCheckInputsObservable.add(function(){i._applyUserInteraction(),i._maintainCameraAboveGround()})},e.prototype.detach=function(){if(this._attachedCamera){var e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null}},e.prototype.zoomOnMesh=function(e,t,i){void 0===t&&(t=!1),void 0===i&&(i=null),e.computeWorldMatrix(!0);var n=e.getBoundingInfo().boundingBox;this.zoomOnBoundingInfo(n.minimumWorld,n.maximumWorld,t,i)},e.prototype.zoomOnMeshHierarchy=function(e,t,i){void 0===t&&(t=!1),void 0===i&&(i=null),e.computeWorldMatrix(!0);var n=e.getHierarchyBoundingVectors(!0);this.zoomOnBoundingInfo(n.min,n.max,t,i)},e.prototype.zoomOnMeshesHierarchy=function(e,t,i){void 0===t&&(t=!1),void 0===i&&(i=null);for(var n=new o.x(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),r=new o.x(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),s=0;sl.upperRadiusLimit?l.upperRadiusLimit:c),c):0},e.prototype._maintainCameraAboveGround=function(){var t=this;if(!(this._elevationReturnTime<0)){var i=X.a.Now-this._lastInteractionTime,n=.5*Math.PI-this._defaultElevation,r=.5*Math.PI;if(this._attachedCamera&&!this._betaIsAnimating&&this._attachedCamera.beta>r&&i>=this._elevationReturnWaitTime){this._betaIsAnimating=!0,this.stopAllAnimations(),this._betaTransition||(this._betaTransition=B.CreateAnimation("beta",B.ANIMATIONTYPE_FLOAT,60,e.EasingFunction));var o=B.TransitionTo("beta",n,this._attachedCamera,this._attachedCamera.getScene(),60,this._betaTransition,this._elevationReturnTime,function(){t._clearAnimationLocks(),t.stopAllAnimations()});o&&this._animatables.push(o)}}},e.prototype._getFrustumSlope=function(){var e=this._attachedCamera;if(!e)return o.w.Zero();var t=e.getScene().getEngine().getAspectRatio(e),i=Math.tan(e.fov/2),n=i*t;return new o.w(n,i)},e.prototype._clearAnimationLocks=function(){this._betaIsAnimating=!1},e.prototype._applyUserInteraction=function(){this.isUserIsMoving&&(this._lastInteractionTime=X.a.Now,this.stopAllAnimations(),this._clearAnimationLocks())},e.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(e.prototype,"isUserIsMoving",{get:function(){return!!this._attachedCamera&&(0!==this._attachedCamera.inertialAlphaOffset||0!==this._attachedCamera.inertialBetaOffset||0!==this._attachedCamera.inertialRadiusOffset||0!==this._attachedCamera.inertialPanningX||0!==this._attachedCamera.inertialPanningY||this._isPointerDown)},enumerable:!0,configurable:!0}),e.EasingFunction=new oe,e.EasingMode=$.EASINGMODE_EASEINOUT,e.IgnoreBoundsSizeMode=0,e.FitFrustumSidesMode=1,e}(),Oe=function(){return function(e,t,i,n){void 0===t&&(t=new o.x),void 0===i&&(i=0),void 0===n&&(n=!1),this.direction=e,this.rotatedDirection=t,this.diff=i,this.ignore=n}}(),Ie=function(){function e(e){this.ui=e,this.name="AttachToBoxBehavior",this.distanceAwayFromFace=.15,this.distanceAwayFromBottomOfFace=.15,this._faceVectors=[new Oe(o.x.Up()),new Oe(o.x.Down()),new Oe(o.x.Left()),new Oe(o.x.Right()),new Oe(o.x.Forward()),new Oe(o.x.Forward().scaleInPlace(-1))],this._tmpMatrix=new o.j,this._tmpVector=new o.x,this._zeroVector=o.x.Zero(),this._lookAtTmpMatrix=new o.j}return e.prototype.init=function(){},e.prototype._closestFace=function(e){var t=this;return this._faceVectors.forEach(function(i){t._target.rotationQuaternion||(t._target.rotationQuaternion=o.q.RotationYawPitchRoll(t._target.rotation.y,t._target.rotation.x,t._target.rotation.z)),t._target.rotationQuaternion.toRotationMatrix(t._tmpMatrix),o.x.TransformCoordinatesToRef(i.direction,t._tmpMatrix,i.rotatedDirection),i.diff=o.x.GetAngleBetweenVectors(i.rotatedDirection,e,o.x.Cross(i.rotatedDirection,e))}),this._faceVectors.reduce(function(e,t){return e.ignore?t:t.ignore?e:e.diff1)return e._setAllVisibility(e._ownerNode,1),void(e._hoverValue=e.fadeInTime+e.delay);if(e._ownerNode.visibility<0&&(e._setAllVisibility(e._ownerNode,0),e._hoverValue<0))return void(e._hoverValue=0);setTimeout(e._update,e._millisecondsPerFrame)}}}return Object.defineProperty(e.prototype,"name",{get:function(){return"FadeInOut"},enumerable:!0,configurable:!0}),e.prototype.init=function(){},e.prototype.attach=function(e){this._ownerNode=e,this._setAllVisibility(this._ownerNode,0)},e.prototype.detach=function(){this._ownerNode=null},e.prototype.fadeIn=function(e){this._hovered=e,this._update()},e.prototype._setAllVisibility=function(e,t){var i=this;e.visibility=t,e.getChildMeshes().forEach(function(e){i._setAllVisibility(e,t)})},e}(),Le=i(50),we=function(){function e(){this._startDistance=0,this._initialScale=new o.x(0,0,0),this._targetScale=new o.x(0,0,0),this._sceneRenderObserver=null,this._dragBehaviorA=new Le.a({}),this._dragBehaviorA.moveAttached=!1,this._dragBehaviorB=new Le.a({}),this._dragBehaviorB.moveAttached=!1}return Object.defineProperty(e.prototype,"name",{get:function(){return"MultiPointerScale"},enumerable:!0,configurable:!0}),e.prototype.init=function(){},e.prototype._getCurrentDistance=function(){return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length()},e.prototype.attach=function(e){var t=this;this._ownerNode=e,this._dragBehaviorA.onDragStartObservable.add(function(i){t._dragBehaviorA.dragging&&t._dragBehaviorB.dragging&&(t._dragBehaviorA.currentDraggingPointerID==t._dragBehaviorB.currentDraggingPointerID?t._dragBehaviorA.releaseDrag():(t._initialScale.copyFrom(e.scaling),t._startDistance=t._getCurrentDistance()))}),this._dragBehaviorB.onDragStartObservable.add(function(i){t._dragBehaviorA.dragging&&t._dragBehaviorB.dragging&&(t._dragBehaviorA.currentDraggingPointerID==t._dragBehaviorB.currentDraggingPointerID?t._dragBehaviorB.releaseDrag():(t._initialScale.copyFrom(e.scaling),t._startDistance=t._getCurrentDistance()))}),[this._dragBehaviorA,this._dragBehaviorB].forEach(function(e){e.onDragObservable.add(function(){if(t._dragBehaviorA.dragging&&t._dragBehaviorB.dragging){var e=t._getCurrentDistance()/t._startDistance;t._initialScale.scaleToRef(e,t._targetScale)}})}),e.addBehavior(this._dragBehaviorA),e.addBehavior(this._dragBehaviorB),this._sceneRenderObserver=e.getScene().onBeforeRenderObservable.add(function(){if(t._dragBehaviorA.dragging&&t._dragBehaviorB.dragging){var i=t._targetScale.subtract(e.scaling).scaleInPlace(.1);i.length()>.01&&e.scaling.addInPlace(i)}})},e.prototype.detach=function(){var e=this;this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver),[this._dragBehaviorA,this._dragBehaviorB].forEach(function(t){t.onDragStartObservable.clear(),t.onDragObservable.clear(),e._ownerNode.removeBehavior(t)})},e}(),Fe=i(24),Ne=i(20),Be=i(45),Ue=function(){function e(){this._sceneRenderObserver=null,this._targetPosition=new o.x(0,0,0),this._moving=!1,this._startingOrientation=new o.q,this.zDragFactor=3,this.rotateDraggedObject=!0,this.dragging=!1,this.dragDeltaRatio=.2,this.currentDraggingPointerID=-1,this.detachCameraControls=!0,this.onDragStartObservable=new r.c,this.onDragEndObservable=new r.c}return Object.defineProperty(e.prototype,"name",{get:function(){return"SixDofDrag"},enumerable:!0,configurable:!0}),e.prototype.init=function(){},Object.defineProperty(e.prototype,"_pointerCamera",{get:function(){return this._scene.cameraToUseForPointers?this._scene.cameraToUseForPointers:this._scene.activeCamera},enumerable:!0,configurable:!0}),e.prototype.attach=function(t){var i=this;this._ownerNode=t,this._scene=this._ownerNode.getScene(),e._virtualScene||(e._virtualScene=new H.a(this._scene.getEngine()),e._virtualScene.detachControl(),this._scene.getEngine().scenes.pop());var n=null,r=new o.x(0,0,0);this._virtualOriginMesh=new Fe.a("",e._virtualScene),this._virtualOriginMesh.rotationQuaternion=new o.q,this._virtualDragMesh=new Fe.a("",e._virtualScene),this._virtualDragMesh.rotationQuaternion=new o.q;var s=null;this._pointerObserver=this._scene.onPointerObservable.add(function(e,t){if(e.type==Re.a.POINTERDOWN){if(!i.dragging&&e.pickInfo&&e.pickInfo.hit&&e.pickInfo.pickedMesh&&e.pickInfo.ray&&(h=e.pickInfo.pickedMesh,i._ownerNode==h||h.isDescendantOf(i._ownerNode))){i._pointerCamera&&i._pointerCamera.cameraRigMode==Ne.a.RIG_MODE_NONE&&e.pickInfo.ray.origin.copyFrom(i._pointerCamera.globalPosition),n=i._ownerNode,Be.a._RemoveAndStorePivotPoint(n),r.copyFrom(e.pickInfo.ray.origin),i._virtualOriginMesh.position.copyFrom(e.pickInfo.ray.origin),i._virtualOriginMesh.lookAt(e.pickInfo.ray.origin.add(e.pickInfo.ray.direction)),i._virtualOriginMesh.removeChild(i._virtualDragMesh),n.computeWorldMatrix(),i._virtualDragMesh.position.copyFrom(n.absolutePosition),n.rotationQuaternion||(n.rotationQuaternion=o.q.RotationYawPitchRoll(n.rotation.y,n.rotation.x,n.rotation.z));var a=n.parent;n.setParent(null),i._virtualDragMesh.rotationQuaternion.copyFrom(n.rotationQuaternion),n.setParent(a),i._virtualOriginMesh.addChild(i._virtualDragMesh),i._targetPosition.copyFrom(i._virtualDragMesh.absolutePosition),i.dragging=!0,i.currentDraggingPointerID=e.event.pointerId,i.detachCameraControls&&i._pointerCamera&&!i._pointerCamera.leftCamera&&(i._pointerCamera.inputs.attachedElement?(s=i._pointerCamera.inputs.attachedElement,i._pointerCamera.detachControl(i._pointerCamera.inputs.attachedElement)):s=null),Be.a._RestorePivotPoint(n),i.onDragStartObservable.notifyObservers({})}}else if(e.type==Re.a.POINTERUP)i.currentDraggingPointerID==e.event.pointerId&&(i.dragging=!1,i._moving=!1,i.currentDraggingPointerID=-1,n=null,i._virtualOriginMesh.removeChild(i._virtualDragMesh),i.detachCameraControls&&s&&i._pointerCamera&&!i._pointerCamera.leftCamera&&i._pointerCamera.attachControl(s,!0),i.onDragEndObservable.notifyObservers({}));else if(e.type==Re.a.POINTERMOVE&&i.currentDraggingPointerID==e.event.pointerId&&i.dragging&&e.pickInfo&&e.pickInfo.ray&&n){var c=i.zDragFactor;i._pointerCamera&&i._pointerCamera.cameraRigMode==Ne.a.RIG_MODE_NONE&&(e.pickInfo.ray.origin.copyFrom(i._pointerCamera.globalPosition),c=0);var l=e.pickInfo.ray.origin.subtract(r);r.copyFrom(e.pickInfo.ray.origin);var u=-o.x.Dot(l,e.pickInfo.ray.direction);i._virtualOriginMesh.addChild(i._virtualDragMesh),i._virtualDragMesh.position.z-=i._virtualDragMesh.position.z<1?u*i.zDragFactor:u*c*i._virtualDragMesh.position.z,i._virtualDragMesh.position.z<0&&(i._virtualDragMesh.position.z=0),i._virtualOriginMesh.position.copyFrom(e.pickInfo.ray.origin),i._virtualOriginMesh.lookAt(e.pickInfo.ray.origin.add(e.pickInfo.ray.direction)),i._virtualOriginMesh.removeChild(i._virtualDragMesh),i._targetPosition.copyFrom(i._virtualDragMesh.absolutePosition),n.parent&&o.x.TransformCoordinatesToRef(i._targetPosition,o.j.Invert(n.parent.getWorldMatrix()),i._targetPosition),i._moving||i._startingOrientation.copyFrom(i._virtualDragMesh.rotationQuaternion),i._moving=!0}var h});var a=new o.q;this._sceneRenderObserver=t.getScene().onBeforeRenderObservable.add(function(){if(i.dragging&&i._moving&&n){if(Be.a._RemoveAndStorePivotPoint(n),n.position.addInPlace(i._targetPosition.subtract(n.position).scale(i.dragDeltaRatio)),i.rotateDraggedObject){a.copyFrom(i._startingOrientation),a.x=-a.x,a.y=-a.y,a.z=-a.z,i._virtualDragMesh.rotationQuaternion.multiplyToRef(a,a),o.q.RotationYawPitchRollToRef(a.toEulerAngles("xyz").y,0,0,a),a.multiplyToRef(i._startingOrientation,a);var e=n.parent;(!e||e.scaling&&!e.scaling.isNonUniformWithinEpsilon(.001))&&(n.setParent(null),o.q.SlerpToRef(n.rotationQuaternion,a,i.dragDeltaRatio,n.rotationQuaternion),n.setParent(e))}Be.a._RestorePivotPoint(n)}})},e.prototype.detach=function(){this._scene&&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.onDragStartObservable.clear()},e}(),Ve=function(){function e(e,t,i){if(this.targetPosition=o.x.Zero(),this.poleTargetPosition=o.x.Zero(),this.poleTargetLocalOffset=o.x.Zero(),this.poleAngle=0,this.slerpAmount=1,this._bone1Quat=o.q.Identity(),this._bone1Mat=o.j.Identity(),this._bone2Ang=Math.PI,this._maxAngle=Math.PI,this._rightHandedSystem=!1,this._bendAxis=o.x.Right(),this._slerping=!1,this._adjustRoll=0,this._bone2=t,this._bone1=t.getParent(),this._bone1){this.mesh=e;var n=t.getPosition();if(t.getAbsoluteTransform().determinant()>0&&(this._rightHandedSystem=!0,this._bendAxis.x=0,this._bendAxis.y=0,this._bendAxis.z=-1,n.x>n.y&&n.x>n.z&&(this._adjustRoll=.5*Math.PI,this._bendAxis.z=1)),this._bone1.length){var r=this._bone1.getScale(),s=this._bone2.getScale();this._bone1Length=this._bone1.length*r.y*this.mesh.scaling.y,this._bone2Length=this._bone2.length*s.y*this.mesh.scaling.y}else if(this._bone1.children[0]){e.computeWorldMatrix(!0);var a=this._bone2.children[0].getAbsolutePosition(e),c=this._bone2.getAbsolutePosition(e),l=this._bone1.getAbsolutePosition(e);this._bone1Length=o.x.Distance(a,c),this._bone2Length=o.x.Distance(c,l)}this._bone1.getRotationMatrixToRef(o.s.WORLD,e,this._bone1Mat),this.maxAngle=Math.PI,i&&(i.targetMesh&&(this.targetMesh=i.targetMesh,this.targetMesh.computeWorldMatrix(!0)),i.poleTargetMesh?(this.poleTargetMesh=i.poleTargetMesh,this.poleTargetMesh.computeWorldMatrix(!0)):i.poleTargetBone?this.poleTargetBone=i.poleTargetBone:this._bone1.getParent()&&(this.poleTargetBone=this._bone1.getParent()),i.poleTargetLocalOffset&&this.poleTargetLocalOffset.copyFrom(i.poleTargetLocalOffset),i.poleAngle&&(this.poleAngle=i.poleAngle),i.bendAxis&&this._bendAxis.copyFrom(i.bendAxis),i.maxAngle&&(this.maxAngle=i.maxAngle),i.slerpAmount&&(this.slerpAmount=i.slerpAmount))}}return Object.defineProperty(e.prototype,"maxAngle",{get:function(){return this._maxAngle},set:function(e){this._setMaxAngle(e)},enumerable:!0,configurable:!0}),e.prototype._setMaxAngle=function(e){e<0&&(e=0),(e>Math.PI||null==e)&&(e=Math.PI),this._maxAngle=e;var t=this._bone1Length,i=this._bone2Length;this._maxReach=Math.sqrt(t*t+i*i-2*t*i*Math.cos(e))},e.prototype.update=function(){var t=this._bone1;if(t){var i=this.targetPosition,n=this.poleTargetPosition,r=e._tmpMats[0],s=e._tmpMats[1];this.targetMesh&&i.copyFrom(this.targetMesh.getAbsolutePosition()),this.poleTargetBone?this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset,this.mesh,n):this.poleTargetMesh&&o.x.TransformCoordinatesToRef(this.poleTargetLocalOffset,this.poleTargetMesh.getWorldMatrix(),n);var a=e._tmpVecs[0],c=e._tmpVecs[1],l=e._tmpVecs[2],u=e._tmpVecs[3],h=e._tmpVecs[4],d=e._tmpQuat;t.getAbsolutePositionToRef(this.mesh,a),n.subtractToRef(a,h),0==h.x&&0==h.y&&0==h.z?h.y=1:h.normalize(),i.subtractToRef(a,u),u.normalize(),o.x.CrossToRef(u,h,c),c.normalize(),o.x.CrossToRef(u,c,l),l.normalize(),o.j.FromXYZAxesToRef(l,u,c,r);var f=this._bone1Length,p=this._bone2Length,_=o.x.Distance(a,i);this._maxReach>0&&(_=Math.min(this._maxReach,_));var m=(p*p+_*_-f*f)/(2*p*_),g=(_*_+f*f-p*p)/(2*_*f);m>1&&(m=1),g>1&&(g=1),m<-1&&(m=-1),g<-1&&(g=-1);var v=Math.acos(m),y=Math.acos(g),b=-v-y;if(this._rightHandedSystem)o.j.RotationYawPitchRollToRef(0,0,this._adjustRoll,s),s.multiplyToRef(r,r),o.j.RotationAxisToRef(this._bendAxis,y,s),s.multiplyToRef(r,r);else{var T=e._tmpVecs[5];T.copyFrom(this._bendAxis),T.x*=-1,o.j.RotationAxisToRef(T,-y,s),s.multiplyToRef(r,r)}this.poleAngle&&(o.j.RotationAxisToRef(u,this.poleAngle,s),r.multiplyToRef(s,r)),this._bone1&&(this.slerpAmount<1?(this._slerping||o.q.FromRotationMatrixToRef(this._bone1Mat,this._bone1Quat),o.q.FromRotationMatrixToRef(r,d),o.q.SlerpToRef(this._bone1Quat,d,this.slerpAmount,this._bone1Quat),b=this._bone2Ang*(1-this.slerpAmount)+b*this.slerpAmount,this._bone1.setRotationQuaternion(this._bone1Quat,o.s.WORLD,this.mesh),this._slerping=!0):(this._bone1.setRotationMatrix(r,o.s.WORLD,this.mesh),this._bone1Mat.copyFrom(r),this._slerping=!1)),this._bone2.setAxisAngle(this._bendAxis,b,o.s.LOCAL),this._bone2Ang=b}},e._tmpVecs=[o.x.Zero(),o.x.Zero(),o.x.Zero(),o.x.Zero(),o.x.Zero(),o.x.Zero()],e._tmpQuat=o.q.Identity(),e._tmpMats=[o.j.Identity(),o.j.Identity()],e}(),ke=function(){function e(e,t,i,n){if(this.upAxis=o.x.Up(),this.upAxisSpace=o.s.LOCAL,this.adjustYaw=0,this.adjustPitch=0,this.adjustRoll=0,this.slerpAmount=1,this._boneQuat=o.q.Identity(),this._slerping=!1,this._firstFrameSkipped=!1,this._fowardAxis=o.x.Forward(),this.mesh=e,this.bone=t,this.target=i,n&&(n.adjustYaw&&(this.adjustYaw=n.adjustYaw),n.adjustPitch&&(this.adjustPitch=n.adjustPitch),n.adjustRoll&&(this.adjustRoll=n.adjustRoll),null!=n.maxYaw?this.maxYaw=n.maxYaw:this.maxYaw=Math.PI,null!=n.minYaw?this.minYaw=n.minYaw:this.minYaw=-Math.PI,null!=n.maxPitch?this.maxPitch=n.maxPitch:this.maxPitch=Math.PI,null!=n.minPitch?this.minPitch=n.minPitch:this.minPitch=-Math.PI,null!=n.slerpAmount&&(this.slerpAmount=n.slerpAmount),null!=n.upAxis&&(this.upAxis=n.upAxis),null!=n.upAxisSpace&&(this.upAxisSpace=n.upAxisSpace),null!=n.yawAxis||null!=n.pitchAxis)){var r=o.c.Y,s=o.c.X;null!=n.yawAxis&&(r=n.yawAxis.clone()).normalize(),null!=n.pitchAxis&&(s=n.pitchAxis.clone()).normalize();var a=o.x.Cross(s,r);this._transformYawPitch=o.j.Identity(),o.j.FromXYZAxesToRef(s,r,a,this._transformYawPitch),this._transformYawPitchInv=this._transformYawPitch.clone(),this._transformYawPitch.invert()}t.getParent()||this.upAxisSpace!=o.s.BONE||(this.upAxisSpace=o.s.LOCAL)}return Object.defineProperty(e.prototype,"minYaw",{get:function(){return this._minYaw},set:function(e){this._minYaw=e,this._minYawSin=Math.sin(e),this._minYawCos=Math.cos(e),null!=this._maxYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"maxYaw",{get:function(){return this._maxYaw},set:function(e){this._maxYaw=e,this._maxYawSin=Math.sin(e),this._maxYawCos=Math.cos(e),null!=this._minYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"minPitch",{get:function(){return this._minPitch},set:function(e){this._minPitch=e,this._minPitchTan=Math.tan(e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"maxPitch",{get:function(){return this._maxPitch},set:function(e){this._maxPitch=e,this._maxPitchTan=Math.tan(e)},enumerable:!0,configurable:!0}),e.prototype.update=function(){if(this.slerpAmount<1&&!this._firstFrameSkipped)this._firstFrameSkipped=!0;else{var t=this.bone,i=e._tmpVecs[0];t.getAbsolutePositionToRef(this.mesh,i);var n=this.target,r=e._tmpMats[0],s=e._tmpMats[1],a=this.mesh,c=t.getParent(),l=e._tmpVecs[1];l.copyFrom(this.upAxis),this.upAxisSpace==o.s.BONE&&c?(this._transformYawPitch&&o.x.TransformCoordinatesToRef(l,this._transformYawPitchInv,l),c.getDirectionToRef(l,this.mesh,l)):this.upAxisSpace==o.s.LOCAL&&(a.getDirectionToRef(l,l),1==a.scaling.x&&1==a.scaling.y&&1==a.scaling.z||l.normalize());var u=!1,h=!1;if(this._maxYaw==Math.PI&&this._minYaw==-Math.PI||(u=!0),this._maxPitch==Math.PI&&this._minPitch==-Math.PI||(h=!0),u||h){var d=e._tmpMats[2],f=e._tmpMats[3];if(this.upAxisSpace==o.s.BONE&&1==l.y&&c)c.getRotationMatrixToRef(o.s.WORLD,this.mesh,d);else if(this.upAxisSpace!=o.s.LOCAL||1!=l.y||c){(_=e._tmpVecs[2]).copyFrom(this._fowardAxis),this._transformYawPitch&&o.x.TransformCoordinatesToRef(_,this._transformYawPitchInv,_),c?c.getDirectionToRef(_,this.mesh,_):a.getDirectionToRef(_,_);var p=o.x.Cross(l,_);p.normalize();var _=o.x.Cross(p,l);o.j.FromXYZAxesToRef(p,l,_,d)}else d.copyFrom(a.getWorldMatrix());d.invertToRef(f);var m=null;if(h){var g=e._tmpVecs[3];n.subtractToRef(i,g),o.x.TransformCoordinatesToRef(g,f,g),m=Math.sqrt(g.x*g.x+g.z*g.z);var v=Math.atan2(g.y,m),y=v;v>this._maxPitch?(g.y=this._maxPitchTan*m,y=this._maxPitch):vthis._maxYaw||bMath.PI?this._isAngleBetween(b,this._maxYaw,this._midYawConstraint)?(g.z=this._maxYawCos*m,g.x=this._maxYawSin*m,T=this._maxYaw):this._isAngleBetween(b,this._midYawConstraint,this._minYaw)&&(g.z=this._minYawCos*m,g.x=this._minYawSin*m,T=this._minYaw):b>this._maxYaw?(g.z=this._maxYawCos*m,g.x=this._maxYawSin*m,T=this._maxYaw):bMath.PI){var E=e._tmpVecs[8];E.copyFrom(o.c.Z),this._transformYawPitch&&o.x.TransformCoordinatesToRef(E,this._transformYawPitchInv,E);var x=e._tmpMats[4];this._boneQuat.toRotationMatrix(x),this.mesh.getWorldMatrix().multiplyToRef(x,x),o.x.TransformCoordinatesToRef(E,x,E),o.x.TransformCoordinatesToRef(E,f,E);var A=Math.atan2(E.x,E.z);if(this._getAngleBetween(A,b)>this._getAngleBetween(A,this._midYawConstraint)){null==m&&(m=Math.sqrt(g.x*g.x+g.z*g.z));var P=this._getAngleBetween(A,this._maxYaw);this._getAngleBetween(A,this._minYaw)Math.PI?i-=2*Math.PI:i<-Math.PI&&(i+=2*Math.PI),i},e.prototype._getAngleBetween=function(e,t){var i=0;return(i=(e=(e%=2*Math.PI)<0?e+2*Math.PI:e)<(t=(t%=2*Math.PI)<0?t+2*Math.PI:t)?t-e:e-t)>Math.PI&&(i=2*Math.PI-i),i},e.prototype._isAngleBetween=function(e,t,i){if(e=(e%=2*Math.PI)<0?e+2*Math.PI:e,(t=(t%=2*Math.PI)<0?t+2*Math.PI:t)<(i=(i%=2*Math.PI)<0?i+2*Math.PI:i)){if(e>t&&ei&&e>v,b=0;b<6;b++){var T=g[v][b];m&&(T=d._convertRGBtoRGBATextureData(T,y,y,r)),f.texImage2D(b,v,_,y,y,0,u,l,T)}d._bindTextureDirectly(f.TEXTURE_CUBE_MAP,null)}else d.updateRawCubeTexture(p,o,n,r,h);p.isReady=!0,t._removePendingData(p),c&&c()}}(e)},void 0,t.offlineProvider,!0,function(e,i){t._removePendingData(p),l&&e&&l(e.status+" "+e.statusText,i)}),p},me.b.prototype.createRawTexture3D=function(e,t,i,n,r,o,s,a,c,l){void 0===c&&(c=null),void 0===l&&(l=me.b.TEXTURETYPE_UNSIGNED_INT);var u=new ze.a(this,ze.a.DATASOURCE_RAW3D);u.baseWidth=t,u.baseHeight=i,u.baseDepth=n,u.width=t,u.height=i,u.depth=n,u.format=r,u.type=l,u.generateMipMaps=o,u.samplingMode=a,u.is3D=!0,this._doNotHandleContextLost||(u._bufferView=e),this.updateRawTexture3D(u,e,r,s,c,l),this._bindTextureDirectly(this._gl.TEXTURE_3D,u,!0);var h=this._getSamplingParameters(a,o);return this._gl.texParameteri(this._gl.TEXTURE_3D,this._gl.TEXTURE_MAG_FILTER,h.mag),this._gl.texParameteri(this._gl.TEXTURE_3D,this._gl.TEXTURE_MIN_FILTER,h.min),o&&this._gl.generateMipmap(this._gl.TEXTURE_3D),this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._internalTexturesCache.push(u),u},me.b.prototype.updateRawTexture3D=function(e,t,i,n,r,o){void 0===r&&(r=null),void 0===o&&(o=me.b.TEXTURETYPE_UNSIGNED_INT);var s=this._getWebGLTextureType(o),a=this._getInternalFormat(i),c=this._getRGBABufferInternalSizedFormat(o,i);this._bindTextureDirectly(this._gl.TEXTURE_3D,e,!0),this._unpackFlipY(void 0===n||!!n),this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.invertY=n,e._compression=r),e.width%4!=0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),r&&t?this._gl.compressedTexImage3D(this._gl.TEXTURE_3D,0,this.getCaps().s3tc[r],e.width,e.height,e.depth,0,t):this._gl.texImage3D(this._gl.TEXTURE_3D,0,c,e.width,e.height,e.depth,0,a,s,t),e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_3D),this._bindTextureDirectly(this._gl.TEXTURE_3D,null),e.isReady=!0};var je=function(e){function t(t,i,n,r,o,s,a,c,l){void 0===s&&(s=!0),void 0===a&&(a=!1),void 0===c&&(c=_.a.TEXTURE_TRILINEAR_SAMPLINGMODE),void 0===l&&(l=_.a.TEXTURETYPE_UNSIGNED_INT);var u=e.call(this,null,o,!s,a)||this;return u.format=r,u._engine=o.getEngine(),u._texture=o.getEngine().createRawTexture(t,i,n,r,s,a,c,null,l),u.wrapU=Ge.a.CLAMP_ADDRESSMODE,u.wrapV=Ge.a.CLAMP_ADDRESSMODE,u}return l.d(t,e),t.prototype.update=function(e){this._engine.updateRawTexture(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type)},t.CreateLuminanceTexture=function(e,i,n,r,o,s,a){return void 0===o&&(o=!0),void 0===s&&(s=!1),void 0===a&&(a=_.a.TEXTURE_TRILINEAR_SAMPLINGMODE),new t(e,i,n,_.a.TEXTUREFORMAT_LUMINANCE,r,o,s,a)},t.CreateLuminanceAlphaTexture=function(e,i,n,r,o,s,a){return void 0===o&&(o=!0),void 0===s&&(s=!1),void 0===a&&(a=_.a.TEXTURE_TRILINEAR_SAMPLINGMODE),new t(e,i,n,_.a.TEXTUREFORMAT_LUMINANCE_ALPHA,r,o,s,a)},t.CreateAlphaTexture=function(e,i,n,r,o,s,a){return void 0===o&&(o=!0),void 0===s&&(s=!1),void 0===a&&(a=_.a.TEXTURE_TRILINEAR_SAMPLINGMODE),new t(e,i,n,_.a.TEXTUREFORMAT_ALPHA,r,o,s,a)},t.CreateRGBTexture=function(e,i,n,r,o,s,a,c){return void 0===o&&(o=!0),void 0===s&&(s=!1),void 0===a&&(a=_.a.TEXTURE_TRILINEAR_SAMPLINGMODE),void 0===c&&(c=_.a.TEXTURETYPE_UNSIGNED_INT),new t(e,i,n,_.a.TEXTUREFORMAT_RGB,r,o,s,a,c)},t.CreateRGBATexture=function(e,i,n,r,o,s,a,c){return void 0===o&&(o=!0),void 0===s&&(s=!1),void 0===a&&(a=_.a.TEXTURE_TRILINEAR_SAMPLINGMODE),void 0===c&&(c=_.a.TEXTURETYPE_UNSIGNED_INT),new t(e,i,n,_.a.TEXTUREFORMAT_RGBA,r,o,s,a,c)},t.CreateRTexture=function(e,i,n,r,o,s,a,c){return void 0===o&&(o=!0),void 0===s&&(s=!1),void 0===a&&(a=Ge.a.TRILINEAR_SAMPLINGMODE),void 0===c&&(c=_.a.TEXTURETYPE_FLOAT),new t(e,i,n,_.a.TEXTUREFORMAT_R,r,o,s,a,c)},t}(Ge.a),We=function(){function e(e,t,i){this.name=e,this.id=t,this.bones=new Array,this.needInitialSkinMatrix=!1,this.overrideMesh=null,this._isDirty=!0,this._meshesWithPoseMatrix=new Array,this._identity=o.j.Identity(),this._ranges={},this._lastAbsoluteTransformsUpdateId=-1,this._canUseTextureForBones=!1,this._uniqueId=0,this._numBonesWithLinkedTransformNode=0,this._hasWaitingData=null,this.doNotSerialize=!1,this._useTextureToStoreBoneMatrices=!0,this._animationPropertiesOverride=null,this.onBeforeComputeObservable=new r.c,this.bones=[],this._scene=i||R.a.LastCreatedScene,this._uniqueId=this._scene.getUniqueId(),this._scene.addSkeleton(this),this._isDirty=!0;var n=this._scene.getEngine().getCaps();this._canUseTextureForBones=n.textureFloat&&n.maxVertexTextureImageUnits>0}return Object.defineProperty(e.prototype,"useTextureToStoreBoneMatrices",{get:function(){return this._useTextureToStoreBoneMatrices},set:function(e){this._useTextureToStoreBoneMatrices=e,this._markAsDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"animationPropertiesOverride",{get:function(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride},set:function(e){this._animationPropertiesOverride=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isUsingTextureForMatrices",{get:function(){return this.useTextureToStoreBoneMatrices&&this._canUseTextureForBones&&!this.needInitialSkinMatrix},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"uniqueId",{get:function(){return this._uniqueId},enumerable:!0,configurable:!0}),e.prototype.getClassName=function(){return"Skeleton"},e.prototype.getChildren=function(){return this.bones.filter(function(e){return!e.getParent()})},e.prototype.getTransformMatrices=function(e){return this.needInitialSkinMatrix&&e._bonesTransformMatrices?e._bonesTransformMatrices:(this._transformMatrices||this.prepare(),this._transformMatrices)},e.prototype.getTransformMatrixTexture=function(){return this._transformMatrixTexture},e.prototype.getScene=function(){return this._scene},e.prototype.toString=function(e){var t="Name: "+this.name+", nBones: "+this.bones.length;if(t+=", nAnimationRanges: "+(this._ranges?Object.keys(this._ranges).length:"none"),e){t+=", Ranges: {";var i=!0;for(var n in this._ranges)i&&(t+=", ",i=!1),t+=n;t+="}"}return t},e.prototype.getBoneIndexByName=function(e){for(var t=0,i=this.bones.length;t-1&&this._meshesWithPoseMatrix.splice(t,1)},e.prototype._computeTransformMatrices=function(e,t){this.onBeforeComputeObservable.notifyObservers(this);for(var i=0;i0)for(var e=0,t=this.bones;e0&&(r.animation=i.animations[0].serialize()),e.ranges=[],this._ranges){var s=this._ranges[o];if(s){var a={};a.name=o,a.from=s.from,a.to=s.to,e.ranges.push(a)}}}return e},e.Parse=function(t,i){var n,r=new e(t.name,t.id,i);for(t.dimensionsAtRest&&(r.dimensionsAtRest=o.x.FromArray(t.dimensionsAtRest)),r.needInitialSkinMatrix=t.needInitialSkinMatrix,n=0;n-1&&(a=r.bones[s.parentBoneIndex]);var c=s.rest?o.j.FromArray(s.rest):null,l=new K(s.name,r,a,o.j.FromArray(s.matrix),c);void 0!==s.id&&null!==s.id&&(l.id=s.id),s.length&&(l.length=s.length),s.metadata&&(l.metadata=s.metadata),s.animation&&l.animations.push(B.Parse(s.animation)),void 0!==s.linkedTransformNodeId&&null!==s.linkedTransformNodeId&&(r._hasWaitingData=!0,l._waitingTransformNodeId=s.linkedTransformNodeId)}if(t.ranges)for(n=0;n0&&(e=this._meshesWithPoseMatrix[0].getPoseMatrix()),e},e.prototype.sortBones=function(){for(var e=new Array,t=new Array(this.bones.length),i=0;i=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(e.prototype,"isConnected",{get:function(){return this._isConnected},enumerable:!0,configurable:!0}),e.prototype.onleftstickchanged=function(e){this._onleftstickchanged=e},e.prototype.onrightstickchanged=function(e){this._onrightstickchanged=e},Object.defineProperty(e.prototype,"leftStick",{get:function(){return this._leftStick},set:function(e){!this._onleftstickchanged||this._leftStick.x===e.x&&this._leftStick.y===e.y||this._onleftstickchanged(e),this._leftStick=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"rightStick",{get:function(){return this._rightStick},set:function(e){!this._onrightstickchanged||this._rightStick.x===e.x&&this._rightStick.y===e.y||this._onrightstickchanged(e),this._rightStick=e},enumerable:!0,configurable:!0}),e.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]})},e.prototype.dispose=function(){},e.GAMEPAD=0,e.GENERIC=1,e.XBOX=2,e.POSE_ENABLED=3,e}(),Qe=function(e){function t(t,i,n){var o=e.call(this,t,i,n)||this;return o.onButtonDownObservable=new r.c,o.onButtonUpObservable=new r.c,o.type=Ke.GENERIC,o._buttons=new Array(n.buttons.length),o}return l.d(t,e),t.prototype.onbuttondown=function(e){this._onbuttondown=e},t.prototype.onbuttonup=function(e){this._onbuttonup=e},t.prototype._setButtonValue=function(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e},t.prototype.update=function(){e.prototype.update.call(this);for(var t=0;t.005&&(e.inertialAlphaOffset+=i)}if(0!=t.y){var n=t.y/this.gamepadRotationSensibility;0!=n&&Math.abs(n)>.005&&(e.inertialBetaOffset+=n)}}var r=this.gamepad.leftStick;if(r&&0!=r.y){var o=r.y/this.gamepadMoveSensibility;0!=o&&Math.abs(o)>.005&&(this.camera.inertialRadiusOffset-=o)}}},e.prototype.getClassName=function(){return"ArcRotateCameraGamepadInput"},e.prototype.getSimpleName=function(){return"gamepad"},l.c([Object(L.c)()],e.prototype,"gamepadRotationSensibility",void 0),l.c([Object(L.c)()],e.prototype,"gamepadMoveSensibility",void 0),e}();He.ArcRotateCameraGamepadInput=qe;var Ze=i(52),Je=function(){function e(){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 e.prototype.attachControl=function(e,t){var i=this;this._onCanvasBlurObserver||(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add(function(){i._keys=[]}),this._onKeyboardObserver=this._scene.onKeyboardObservable.add(function(e){var n,r=e.event;r.metaKey||(e.type===Ze.a.KEYDOWN?(i._ctrlPressed=r.ctrlKey,i._altPressed=r.altKey,(-1!==i.keysUp.indexOf(r.keyCode)||-1!==i.keysDown.indexOf(r.keyCode)||-1!==i.keysLeft.indexOf(r.keyCode)||-1!==i.keysRight.indexOf(r.keyCode)||-1!==i.keysReset.indexOf(r.keyCode))&&(-1===(n=i._keys.indexOf(r.keyCode))&&i._keys.push(r.keyCode),r.preventDefault&&(t||r.preventDefault()))):-1===i.keysUp.indexOf(r.keyCode)&&-1===i.keysDown.indexOf(r.keyCode)&&-1===i.keysLeft.indexOf(r.keyCode)&&-1===i.keysRight.indexOf(r.keyCode)&&-1===i.keysReset.indexOf(r.keyCode)||((n=i._keys.indexOf(r.keyCode))>=0&&i._keys.splice(n,1),r.preventDefault&&(t||r.preventDefault())))}))},e.prototype.detachControl=function(e){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=[]},e.prototype.checkInputs=function(){if(this._onKeyboardObserver)for(var e=this.camera,t=0;t0?i/(1+this.wheelDeltaPercentage):i*(1+this.wheelDeltaPercentage)},e.prototype.attachControl=function(e,t){var i=this;this._wheel=function(e,n){if(e.type===Re.a.POINTERWHEEL){var r=e.event,o=0,s=r;if(s.wheelDelta)if(i.wheelDeltaPercentage){if((o=i.computeDeltaFromMouseWheelLegacyEvent(s,i.camera.radius))>0){for(var a=i.camera.radius,c=i.camera.inertialRadiusOffset+o,l=0;l<20&&Math.abs(c)>.001;l++)a-=c,c*=i.camera.inertia;a=D.a.Clamp(a,0,Number.MAX_VALUE),o=i.computeDeltaFromMouseWheelLegacyEvent(s,a)}}else o=s.wheelDelta/(40*i.wheelPrecision);else o=-(r.deltaY||r.detail)/i.wheelPrecision;o&&(i.camera.inertialRadiusOffset+=o),r.preventDefault&&(t||r.preventDefault())}},this._observer=this.camera.getScene().onPointerObservable.add(this._wheel,Re.a.POINTERWHEEL)},e.prototype.detachControl=function(e){this._observer&&e&&(this.camera.getScene().onPointerObservable.remove(this._observer),this._observer=null,this._wheel=null)},e.prototype.getClassName=function(){return"ArcRotateCameraMouseWheelInput"},e.prototype.getSimpleName=function(){return"mousewheel"},l.c([Object(L.c)()],e.prototype,"wheelPrecision",void 0),l.c([Object(L.c)()],e.prototype,"wheelDeltaPercentage",void 0),e}();He.ArcRotateCameraMouseWheelInput=$e;var et=function(){function e(){this.buttons=[0,1,2]}return e.prototype.attachControl=function(e,t){var i=this,n=this.camera.getEngine(),r=0,o=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(s,a){var c=s.event,l="touch"===c.pointerType;if(!n.isInVRExclusivePointerMode&&(s.type===Re.a.POINTERMOVE||-1!==i.buttons.indexOf(c.button))){var u=c.srcElement||c.target;if(i._altKey=c.altKey,i._ctrlKey=c.ctrlKey,i._metaKey=c.metaKey,i._shiftKey=c.shiftKey,i._buttonsPressed=c.buttons,n.isPointerLock){var h=c.movementX||c.mozMovementX||c.webkitMovementX||c.msMovementX||0,d=c.movementY||c.mozMovementY||c.webkitMovementY||c.msMovementY||0;i.onTouch(null,h,d),i.pointA=null,i.pointB=null}else if(s.type===Re.a.POINTERDOWN&&u){try{u.setPointerCapture(c.pointerId)}catch(e){}null===i.pointA?i.pointA={x:c.clientX,y:c.clientY,pointerId:c.pointerId,type:c.pointerType}:null===i.pointB&&(i.pointB={x:c.clientX,y:c.clientY,pointerId:c.pointerId,type:c.pointerType}),i.onButtonDown(c),t||(c.preventDefault(),e.focus())}else if(s.type===Re.a.POINTERDOUBLETAP)i.onDoubleTap(c.pointerType);else if(s.type===Re.a.POINTERUP&&u){try{u.releasePointerCapture(c.pointerId)}catch(e){}l||(i.pointB=null),n._badOS?i.pointA=i.pointB=null:i.pointB&&i.pointA&&i.pointA.pointerId==c.pointerId?(i.pointA=i.pointB,i.pointB=null):i.pointA&&i.pointB&&i.pointB.pointerId==c.pointerId?i.pointB=null:i.pointA=i.pointB=null,(0!==r||o)&&(i.onMultiTouch(i.pointA,i.pointB,r,0,o,null),r=0,o=null),i.onButtonUp(c),t||c.preventDefault()}else if(s.type===Re.a.POINTERMOVE)if(t||c.preventDefault(),i.pointA&&null===i.pointB){h=c.clientX-i.pointA.x,d=c.clientY-i.pointA.y;i.onTouch(i.pointA,h,d),i.pointA.x=c.clientX,i.pointA.y=c.clientY}else if(i.pointA&&i.pointB){var f=i.pointA.pointerId===c.pointerId?i.pointA:i.pointB;f.x=c.clientX,f.y=c.clientY;var p=i.pointA.x-i.pointB.x,_=i.pointA.y-i.pointB.y,m=p*p+_*_,g={x:(i.pointA.x+i.pointB.x)/2,y:(i.pointA.y+i.pointB.y)/2,pointerId:c.pointerId,type:s.type};i.onMultiTouch(i.pointA,i.pointB,r,m,o,g),o=g,r=m}}},this._observer=this.camera.getScene().onPointerObservable.add(this._pointerInput,Re.a.POINTERDOWN|Re.a.POINTERUP|Re.a.POINTERMOVE),this._onLostFocus=function(){i.pointA=i.pointB=null,r=0,o=null,i.onLostFocus()},e.addEventListener("contextmenu",this.onContextMenu.bind(this),!1),ye.h.RegisterTopRootEvents([{name:"blur",handler:this._onLostFocus}])},e.prototype.detachControl=function(e){this._onLostFocus&&ye.h.UnregisterTopRootEvents([{name:"blur",handler:this._onLostFocus}]),e&&this._observer&&(this.camera.getScene().onPointerObservable.remove(this._observer),this._observer=null,this.onContextMenu&&e.removeEventListener("contextmenu",this.onContextMenu),this._onLostFocus=null),this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0},e.prototype.getClassName=function(){return"BaseCameraPointersInput"},e.prototype.getSimpleName=function(){return"pointers"},e.prototype.onDoubleTap=function(e){},e.prototype.onTouch=function(e,t,i){},e.prototype.onMultiTouch=function(e,t,i,n,r,o){},e.prototype.onContextMenu=function(e){e.preventDefault()},e.prototype.onButtonDown=function(e){},e.prototype.onButtonUp=function(e){},e.prototype.onLostFocus=function(){},l.c([Object(L.c)()],e.prototype,"buttons",void 0),e}(),tt=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.buttons=[0,1,2],t.angularSensibilityX=1e3,t.angularSensibilityY=1e3,t.pinchPrecision=12,t.pinchDeltaPercentage=0,t.panningSensibility=1e3,t.multiTouchPanning=!0,t.multiTouchPanAndZoom=!0,t.pinchInwards=!0,t._isPanClick=!1,t._twoFingerActivityCount=0,t._isPinching=!1,t}return l.d(t,e),t.prototype.getClassName=function(){return"ArcRotateCameraPointersInput"},t.prototype.onTouch=function(e,t,i){0!==this.panningSensibility&&(this._ctrlKey&&this.camera._useCtrlForPanning||this._isPanClick)?(this.camera.inertialPanningX+=-t/this.panningSensibility,this.camera.inertialPanningY+=i/this.panningSensibility):(this.camera.inertialAlphaOffset-=t/this.angularSensibilityX,this.camera.inertialBetaOffset-=i/this.angularSensibilityY)},t.prototype.onDoubleTap=function(e){this.camera.useInputToRestoreState&&this.camera.restoreState()},t.prototype.onMultiTouch=function(e,t,i,n,r,o){if(!(0===i&&null===r||0===n&&null===o)){var s=this.pinchInwards?1:-1;if(this.multiTouchPanAndZoom){if(this.pinchDeltaPercentage?this.camera.inertialRadiusOffset+=.001*(n-i)*this.camera.radius*this.pinchDeltaPercentage:this.camera.inertialRadiusOffset+=(n-i)/(this.pinchPrecision*s*(this.angularSensibilityX+this.angularSensibilityY)/2),0!==this.panningSensibility&&r&&o){var a=o.x-r.x,c=o.y-r.y;this.camera.inertialPanningX+=-a/this.panningSensibility,this.camera.inertialPanningY+=c/this.panningSensibility}}else{this._twoFingerActivityCount++;var l=Math.sqrt(i),u=Math.sqrt(n);if(this._isPinching||this._twoFingerActivityCount<20&&Math.abs(u-l)>this.camera.pinchToPanMaxDistance)this.pinchDeltaPercentage?this.camera.inertialRadiusOffset+=.001*(n-i)*this.camera.radius*this.pinchDeltaPercentage:this.camera.inertialRadiusOffset+=(n-i)/(this.pinchPrecision*s*(this.angularSensibilityX+this.angularSensibilityY)/2),this._isPinching=!0;else if(0!==this.panningSensibility&&this.multiTouchPanning&&o&&r){a=o.x-r.x,c=o.y-r.y;this.camera.inertialPanningX+=-a/this.panningSensibility,this.camera.inertialPanningY+=c/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},l.c([Object(L.c)()],t.prototype,"buttons",void 0),l.c([Object(L.c)()],t.prototype,"angularSensibilityX",void 0),l.c([Object(L.c)()],t.prototype,"angularSensibilityY",void 0),l.c([Object(L.c)()],t.prototype,"pinchPrecision",void 0),l.c([Object(L.c)()],t.prototype,"pinchDeltaPercentage",void 0),l.c([Object(L.c)()],t.prototype,"panningSensibility",void 0),l.c([Object(L.c)()],t.prototype,"multiTouchPanning",void 0),l.c([Object(L.c)()],t.prototype,"multiTouchPanAndZoom",void 0),t}(et);He.ArcRotateCameraPointersInput=tt;var it=function(e){function t(t){return e.call(this,t)||this}return l.d(t,e),t.prototype.addMouseWheel=function(){return this.add(new $e),this},t.prototype.addPointers=function(){return this.add(new tt),this},t.prototype.addKeyboard=function(){return this.add(new Je),this},t}(Xe);it.prototype.addVRDeviceOrientation=function(){return this.add(new nt),this};var nt=function(){function e(){this.alphaCorrection=1,this.gammaCorrection=1,this._alpha=0,this._gamma=0,this._dirty=!1,this._deviceOrientationHandler=this._onOrientationEvent.bind(this)}return e.prototype.attachControl=function(e,t){this.camera.attachControl(e,t),window.addEventListener("deviceorientation",this._deviceOrientationHandler)},e.prototype._onOrientationEvent=function(e){null!==e.alpha&&(this._alpha=(0|+e.alpha)*this.alphaCorrection),null!==e.gamma&&(this._gamma=(0|+e.gamma)*this.gammaCorrection),this._dirty=!0},e.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)},e.prototype.detachControl=function(e){window.removeEventListener("deviceorientation",this._deviceOrientationHandler)},e.prototype.getClassName=function(){return"ArcRotateCameraVRDeviceOrientationInput"},e.prototype.getSimpleName=function(){return"VRDeviceOrientation"},e}();He.ArcRotateCameraVRDeviceOrientationInput=nt;var rt=function(){function e(){this.keysForward=[87],this.keysBackward=[83],this.keysUp=[69],this.keysDown=[81],this.keysRight=[68],this.keysLeft=[65],this._keys=new Array}return e.prototype.attachControl=function(e,t){var i=this;this._onCanvasBlurObserver||(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add(function(){i._keys=[]}),this._onKeyboardObserver=this._scene.onKeyboardObservable.add(function(e){var n,r=e.event;e.type===Ze.a.KEYDOWN?-1===i.keysForward.indexOf(r.keyCode)&&-1===i.keysBackward.indexOf(r.keyCode)&&-1===i.keysUp.indexOf(r.keyCode)&&-1===i.keysDown.indexOf(r.keyCode)&&-1===i.keysLeft.indexOf(r.keyCode)&&-1===i.keysRight.indexOf(r.keyCode)||(-1===(n=i._keys.indexOf(r.keyCode))&&i._keys.push(r.keyCode),t||r.preventDefault()):-1===i.keysForward.indexOf(r.keyCode)&&-1===i.keysBackward.indexOf(r.keyCode)&&-1===i.keysUp.indexOf(r.keyCode)&&-1===i.keysDown.indexOf(r.keyCode)&&-1===i.keysLeft.indexOf(r.keyCode)&&-1===i.keysRight.indexOf(r.keyCode)||((n=i._keys.indexOf(r.keyCode))>=0&&i._keys.splice(n,1),t||r.preventDefault())}))},e.prototype.detachControl=function(e){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=[]},e.prototype.getClassName=function(){return"FlyCameraKeyboardInput"},e.prototype._onLostFocus=function(e){this._keys=[]},e.prototype.getSimpleName=function(){return"keyboard"},e.prototype.checkInputs=function(){if(this._onKeyboardObserver)for(var e=this.camera,t=0;t=0&&i._keys.splice(n,1),r.preventDefault&&(t||r.preventDefault())))}))},e.prototype.detachControl=function(e){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=[]},e.prototype.checkInputs=function(){var e=this;this._onKeyboardObserver&&this._keys.forEach(function(t){-1!==e.keysHeightOffsetIncr.indexOf(t)&&e._modifierHeightOffset()?e.camera.heightOffset+=e.heightSensibility:-1!==e.keysHeightOffsetDecr.indexOf(t)&&e._modifierHeightOffset()?e.camera.heightOffset-=e.heightSensibility:-1!==e.keysRotationOffsetIncr.indexOf(t)&&e._modifierRotationOffset()?(e.camera.rotationOffset+=e.rotationSensibility,e.camera.rotationOffset%=360):-1!==e.keysRotationOffsetDecr.indexOf(t)&&e._modifierRotationOffset()?(e.camera.rotationOffset-=e.rotationSensibility,e.camera.rotationOffset%=360):-1!==e.keysRadiusIncr.indexOf(t)&&e._modifierRadius()?e.camera.radius+=e.radiusSensibility:-1!==e.keysRadiusDecr.indexOf(t)&&e._modifierRadius()&&(e.camera.radius-=e.radiusSensibility)})},e.prototype.getClassName=function(){return"FollowCameraKeyboardMoveInput"},e.prototype.getSimpleName=function(){return"keyboard"},e.prototype._modifierHeightOffset=function(){return this.keysHeightOffsetModifierAlt===this._altPressed&&this.keysHeightOffsetModifierCtrl===this._ctrlPressed&&this.keysHeightOffsetModifierShift===this._shiftPressed},e.prototype._modifierRotationOffset=function(){return this.keysRotationOffsetModifierAlt===this._altPressed&&this.keysRotationOffsetModifierCtrl===this._ctrlPressed&&this.keysRotationOffsetModifierShift===this._shiftPressed},e.prototype._modifierRadius=function(){return this.keysRadiusModifierAlt===this._altPressed&&this.keysRadiusModifierCtrl===this._ctrlPressed&&this.keysRadiusModifierShift===this._shiftPressed},l.c([Object(L.c)()],e.prototype,"keysHeightOffsetIncr",void 0),l.c([Object(L.c)()],e.prototype,"keysHeightOffsetDecr",void 0),l.c([Object(L.c)()],e.prototype,"keysHeightOffsetModifierAlt",void 0),l.c([Object(L.c)()],e.prototype,"keysHeightOffsetModifierCtrl",void 0),l.c([Object(L.c)()],e.prototype,"keysHeightOffsetModifierShift",void 0),l.c([Object(L.c)()],e.prototype,"keysRotationOffsetIncr",void 0),l.c([Object(L.c)()],e.prototype,"keysRotationOffsetDecr",void 0),l.c([Object(L.c)()],e.prototype,"keysRotationOffsetModifierAlt",void 0),l.c([Object(L.c)()],e.prototype,"keysRotationOffsetModifierCtrl",void 0),l.c([Object(L.c)()],e.prototype,"keysRotationOffsetModifierShift",void 0),l.c([Object(L.c)()],e.prototype,"keysRadiusIncr",void 0),l.c([Object(L.c)()],e.prototype,"keysRadiusDecr",void 0),l.c([Object(L.c)()],e.prototype,"keysRadiusModifierAlt",void 0),l.c([Object(L.c)()],e.prototype,"keysRadiusModifierCtrl",void 0),l.c([Object(L.c)()],e.prototype,"keysRadiusModifierShift",void 0),l.c([Object(L.c)()],e.prototype,"heightSensibility",void 0),l.c([Object(L.c)()],e.prototype,"rotationSensibility",void 0),l.c([Object(L.c)()],e.prototype,"radiusSensibility",void 0),e}();He.FollowCameraKeyboardMoveInput=st;var at=function(){function e(){this.axisControlRadius=!0,this.axisControlHeight=!1,this.axisControlRotation=!1,this.wheelPrecision=3,this.wheelDeltaPercentage=0}return e.prototype.attachControl=function(e,t){var i=this;this._wheel=function(e,n){if(e.type===Re.a.POINTERWHEEL){var r=e.event,o=0,s=Math.max(-1,Math.min(1,r.deltaY||r.wheelDelta||-r.detail));i.wheelDeltaPercentage?(console.assert(i.axisControlRadius+i.axisControlHeight+i.axisControlRotation<=1,"wheelDeltaPercentage only usable when mouse wheel controlls ONE axis. Currently enabled: axisControlRadius: "+i.axisControlRadius+", axisControlHeightOffset: "+i.axisControlHeight+", axisControlRotationOffset: "+i.axisControlRotation),i.axisControlRadius?o=.01*s*i.wheelDeltaPercentage*i.camera.radius:i.axisControlHeight?o=.01*s*i.wheelDeltaPercentage*i.camera.heightOffset:i.axisControlRotation&&(o=.01*s*i.wheelDeltaPercentage*i.camera.rotationOffset)):o=s*i.wheelPrecision,o&&(i.axisControlRadius?i.camera.radius+=o:i.axisControlHeight?i.camera.heightOffset-=o:i.axisControlRotation&&(i.camera.rotationOffset-=o)),r.preventDefault&&(t||r.preventDefault())}},this._observer=this.camera.getScene().onPointerObservable.add(this._wheel,Re.a.POINTERWHEEL)},e.prototype.detachControl=function(e){this._observer&&e&&(this.camera.getScene().onPointerObservable.remove(this._observer),this._observer=null,this._wheel=null)},e.prototype.getClassName=function(){return"ArcRotateCameraMouseWheelInput"},e.prototype.getSimpleName=function(){return"mousewheel"},l.c([Object(L.c)()],e.prototype,"axisControlRadius",void 0),l.c([Object(L.c)()],e.prototype,"axisControlHeight",void 0),l.c([Object(L.c)()],e.prototype,"axisControlRotation",void 0),l.c([Object(L.c)()],e.prototype,"wheelPrecision",void 0),l.c([Object(L.c)()],e.prototype,"wheelDeltaPercentage",void 0),e}();He.FollowCameraMouseWheelInput=at;var ct=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.angularSensibilityX=1,t.angularSensibilityY=1,t.pinchPrecision=1e4,t.pinchDeltaPercentage=0,t.axisXControlRadius=!1,t.axisXControlHeight=!1,t.axisXControlRotation=!0,t.axisYControlRadius=!1,t.axisYControlHeight=!0,t.axisYControlRotation=!1,t.axisPinchControlRadius=!0,t.axisPinchControlHeight=!1,t.axisPinchControlRotation=!1,t.warningEnable=!0,t._warningCounter=0,t}return l.d(t,e),t.prototype.getClassName=function(){return"FollowCameraPointersInput"},t.prototype.onTouch=function(e,t,i){this._warning(),this.axisXControlRotation?this.camera.rotationOffset+=t/this.angularSensibilityX:this.axisYControlRotation&&(this.camera.rotationOffset+=i/this.angularSensibilityX),this.axisXControlHeight?this.camera.heightOffset+=t/this.angularSensibilityY:this.axisYControlHeight&&(this.camera.heightOffset+=i/this.angularSensibilityY),this.axisXControlRadius?this.camera.radius-=t/this.angularSensibilityY:this.axisYControlRadius&&(this.camera.radius-=i/this.angularSensibilityY)},t.prototype.onMultiTouch=function(e,t,i,n,r,o){if(!(0===i&&null===r||0===n&&null===o)){var s=(n-i)/(this.pinchPrecision*(this.angularSensibilityX+this.angularSensibilityY)/2);this.pinchDeltaPercentage?(s*=.01*this.pinchDeltaPercentage,this.axisPinchControlRotation&&(this.camera.rotationOffset+=s*this.camera.rotationOffset),this.axisPinchControlHeight&&(this.camera.heightOffset+=s*this.camera.heightOffset),this.axisPinchControlRadius&&(this.camera.radius-=s*this.camera.radius)):(this.axisPinchControlRotation&&(this.camera.rotationOffset+=s),this.axisPinchControlHeight&&(this.camera.heightOffset+=s),this.axisPinchControlRadius&&(this.camera.radius-=s))}},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)}},l.c([Object(L.c)()],t.prototype,"angularSensibilityX",void 0),l.c([Object(L.c)()],t.prototype,"angularSensibilityY",void 0),l.c([Object(L.c)()],t.prototype,"pinchPrecision",void 0),l.c([Object(L.c)()],t.prototype,"pinchDeltaPercentage",void 0),l.c([Object(L.c)()],t.prototype,"axisXControlRadius",void 0),l.c([Object(L.c)()],t.prototype,"axisXControlHeight",void 0),l.c([Object(L.c)()],t.prototype,"axisXControlRotation",void 0),l.c([Object(L.c)()],t.prototype,"axisYControlRadius",void 0),l.c([Object(L.c)()],t.prototype,"axisYControlHeight",void 0),l.c([Object(L.c)()],t.prototype,"axisYControlRotation",void 0),l.c([Object(L.c)()],t.prototype,"axisPinchControlRadius",void 0),l.c([Object(L.c)()],t.prototype,"axisPinchControlHeight",void 0),l.c([Object(L.c)()],t.prototype,"axisPinchControlRotation",void 0),t}(et);He.FollowCameraPointersInput=ct;var lt=function(){function e(){this.keysUp=[38],this.keysDown=[40],this.keysLeft=[37],this.keysRight=[39],this._keys=new Array}return e.prototype.attachControl=function(e,t){var i=this;this._onCanvasBlurObserver||(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add(function(){i._keys=[]}),this._onKeyboardObserver=this._scene.onKeyboardObservable.add(function(e){var n,r=e.event;r.metaKey||(e.type===Ze.a.KEYDOWN?-1===i.keysUp.indexOf(r.keyCode)&&-1===i.keysDown.indexOf(r.keyCode)&&-1===i.keysLeft.indexOf(r.keyCode)&&-1===i.keysRight.indexOf(r.keyCode)||(-1===(n=i._keys.indexOf(r.keyCode))&&i._keys.push(r.keyCode),t||r.preventDefault()):-1===i.keysUp.indexOf(r.keyCode)&&-1===i.keysDown.indexOf(r.keyCode)&&-1===i.keysLeft.indexOf(r.keyCode)&&-1===i.keysRight.indexOf(r.keyCode)||((n=i._keys.indexOf(r.keyCode))>=0&&i._keys.splice(n,1),t||r.preventDefault()))}))},e.prototype.detachControl=function(e){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=[]},e.prototype.checkInputs=function(){if(this._onKeyboardObserver)for(var e=this.camera,t=0;t1)e.cameraRotation.x+=-this._offsetY/this.touchAngularSensibility;else{var t=e._computeLocalCameraSpeed(),i=new o.x(0,0,t*this._offsetY/this.touchMoveSensibility);o.j.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,e._cameraRotationMatrix),e.cameraDirection.addInPlace(o.x.TransformCoordinates(i,e._cameraRotationMatrix))}}},e.prototype.getClassName=function(){return"FreeCameraTouchInput"},e.prototype.getSimpleName=function(){return"touch"},l.c([Object(L.c)()],e.prototype,"touchAngularSensibility",void 0),l.c([Object(L.c)()],e.prototype,"touchMoveSensibility",void 0),e}();He.FreeCameraTouchInput=ht;var dt=function(e){function t(t){var i=e.call(this,t)||this;return i._mouseInput=null,i}return l.d(t,e),t.prototype.addKeyboard=function(){return this.add(new lt),this},t.prototype.addMouse=function(e){return void 0===e&&(e=!0),this._mouseInput||(this._mouseInput=new ut(e),this.add(this._mouseInput)),this},t.prototype.removeMouse=function(){return this._mouseInput&&this.remove(this._mouseInput),this},t.prototype.addTouch=function(){return this.add(new ht),this},t.prototype.clear=function(){e.prototype.clear.call(this),this._mouseInput=null},t}(Xe);dt.prototype.addDeviceOrientation=function(){return this._deviceOrientationInput||(this._deviceOrientationInput=new ft,this.add(this._deviceOrientationInput)),this};var ft=function(){function e(){var e=this;this._screenOrientationAngle=0,this._screenQuaternion=new o.q,this._alpha=0,this._beta=0,this._gamma=0,this._onDeviceOrientationChangedObservable=new r.c,this._orientationChanged=function(){e._screenOrientationAngle=void 0!==window.orientation?+window.orientation:window.screen.orientation&&window.screen.orientation.angle?window.screen.orientation.angle:0,e._screenOrientationAngle=-ye.h.ToRadians(e._screenOrientationAngle/2),e._screenQuaternion.copyFromFloats(0,Math.sin(e._screenOrientationAngle),0,Math.cos(e._screenOrientationAngle))},this._deviceOrientation=function(t){e._alpha=null!==t.alpha?t.alpha:0,e._beta=null!==t.beta?t.beta:0,e._gamma=null!==t.gamma?t.gamma:0,null!==t.alpha&&e._onDeviceOrientationChangedObservable.notifyObservers()},this._constantTranform=new o.q(-Math.sqrt(.5),0,0,Math.sqrt(.5)),this._orientationChanged()}return Object.defineProperty(e.prototype,"camera",{get:function(){return this._camera},set:function(e){var t=this;this._camera=e,null==this._camera||this._camera.rotationQuaternion||(this._camera.rotationQuaternion=new o.q),this._camera&&this._camera.onDisposeObservable.add(function(){t._onDeviceOrientationChangedObservable.clear()})},enumerable:!0,configurable:!0}),e.prototype.attachControl=function(e,t){window.addEventListener("orientationchange",this._orientationChanged),window.addEventListener("deviceorientation",this._deviceOrientation),this._orientationChanged()},e.prototype.detachControl=function(e){window.removeEventListener("orientationchange",this._orientationChanged),window.removeEventListener("deviceorientation",this._deviceOrientation),this._alpha=0},e.prototype.checkInputs=function(){this._alpha&&(o.q.RotationYawPitchRollToRef(ye.h.ToRadians(this._alpha),ye.h.ToRadians(this._beta),-ye.h.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)},e.prototype.getClassName=function(){return"FreeCameraDeviceOrientationInput"},e.prototype.getSimpleName=function(){return"deviceOrientation"},e}();He.FreeCameraDeviceOrientationInput=ft;var pt=function(){function e(){this.gamepadAngularSensibility=200,this.gamepadMoveSensibility=40,this._cameraTransform=o.j.Identity(),this._deltaTransform=o.x.Zero(),this._vector3=o.x.Zero(),this._vector2=o.w.Zero()}return e.prototype.attachControl=function(e,t){var i=this,n=this.camera.getScene().gamepadManager;this._onGamepadConnectedObserver=n.onGamepadConnectedObservable.add(function(e){e.type!==Ke.POSE_ENABLED&&(i.gamepad&&e.type!==Ke.XBOX||(i.gamepad=e))}),this._onGamepadDisconnectedObserver=n.onGamepadDisconnectedObservable.add(function(e){i.gamepad===e&&(i.gamepad=null)}),this.gamepad=n.getGamepadByType(Ke.XBOX)},e.prototype.detachControl=function(e){this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),this.gamepad=null},e.prototype.checkInputs=function(){if(this.gamepad&&this.gamepad.leftStick){var e=this.camera,t=this.gamepad.leftStick,i=t.x/this.gamepadMoveSensibility,n=t.y/this.gamepadMoveSensibility;t.x=Math.abs(i)>.005?0+i:0,t.y=Math.abs(n)>.005?0+n:0;var r=this.gamepad.rightStick;if(r){var s=r.x/this.gamepadAngularSensibility,a=r.y/this.gamepadAngularSensibility;r.x=Math.abs(s)>.001?0+s:0,r.y=Math.abs(a)>.001?0+a:0}else r={x:0,y:0};e.rotationQuaternion?e.rotationQuaternion.toRotationMatrix(this._cameraTransform):o.j.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,this._cameraTransform);var c=50*e._computeLocalCameraSpeed();this._vector3.copyFromFloats(t.x*c,0,-t.y*c),o.x.TransformCoordinatesToRef(this._vector3,this._cameraTransform,this._deltaTransform),e.cameraDirection.addInPlace(this._deltaTransform),this._vector2.copyFromFloats(r.y,r.x),e.cameraRotation.addInPlace(this._vector2)}},e.prototype.getClassName=function(){return"FreeCameraGamepadInput"},e.prototype.getSimpleName=function(){return"gamepad"},l.c([Object(L.c)()],e.prototype,"gamepadAngularSensibility",void 0),l.c([Object(L.c)()],e.prototype,"gamepadMoveSensibility",void 0),e}();He.FreeCameraGamepadInput=pt;var _t,mt=i(62);!function(e){e[e.X=0]="X",e[e.Y=1]="Y",e[e.Z=2]="Z"}(_t||(_t={}));var gt=function(){function e(t){var i=this;if(this._leftJoystick=!!t,e._globalJoystickIndex++,this._axisTargetedByLeftAndRight=_t.X,this._axisTargetedByUpAndDown=_t.Y,this.reverseLeftRight=!1,this.reverseUpDown=!1,this._touches=new mt.a,this.deltaPosition=o.x.Zero(),this._joystickSensibility=25,this._inversedSensibility=1/(this._joystickSensibility/1e3),this._onResize=function(t){e.vjCanvasWidth=window.innerWidth,e.vjCanvasHeight=window.innerHeight,e.Canvas&&(e.Canvas.width=e.vjCanvasWidth,e.Canvas.height=e.vjCanvasHeight),e.halfWidth=e.vjCanvasWidth/2},!e.Canvas){window.addEventListener("resize",this._onResize,!1),e.Canvas=document.createElement("canvas"),e.vjCanvasWidth=window.innerWidth,e.vjCanvasHeight=window.innerHeight,e.Canvas.width=window.innerWidth,e.Canvas.height=window.innerHeight,e.Canvas.style.width="100%",e.Canvas.style.height="100%",e.Canvas.style.position="absolute",e.Canvas.style.backgroundColor="transparent",e.Canvas.style.top="0px",e.Canvas.style.left="0px",e.Canvas.style.zIndex="5",e.Canvas.style.msTouchAction="none",e.Canvas.setAttribute("touch-action","none");var n=e.Canvas.getContext("2d");if(!n)throw new Error("Unable to create canvas for virtual joystick");e.vjCanvasContext=n,e.vjCanvasContext.strokeStyle="#ffffff",e.vjCanvasContext.lineWidth=2,document.body.appendChild(e.Canvas)}e.halfWidth=e.Canvas.width/2,this.pressed=!1,this._joystickColor="cyan",this._joystickPointerID=-1,this._joystickPointerPos=new o.w(0,0),this._joystickPreviousPointerPos=new o.w(0,0),this._joystickPointerStartPos=new o.w(0,0),this._deltaJoystickVector=new o.w(0,0),this._onPointerDownHandlerRef=function(e){i._onPointerDown(e)},this._onPointerMoveHandlerRef=function(e){i._onPointerMove(e)},this._onPointerUpHandlerRef=function(e){i._onPointerUp(e)},e.Canvas.addEventListener("pointerdown",this._onPointerDownHandlerRef,!1),e.Canvas.addEventListener("pointermove",this._onPointerMoveHandlerRef,!1),e.Canvas.addEventListener("pointerup",this._onPointerUpHandlerRef,!1),e.Canvas.addEventListener("pointerout",this._onPointerUpHandlerRef,!1),e.Canvas.addEventListener("contextmenu",function(e){e.preventDefault()},!1),requestAnimationFrame(function(){i._drawVirtualJoystick()})}return e.prototype.setJoystickSensibility=function(e){this._joystickSensibility=e,this._inversedSensibility=1/(this._joystickSensibility/1e3)},e.prototype._onPointerDown=function(t){t.preventDefault(),(!0===this._leftJoystick?t.clientXe.halfWidth)&&this._joystickPointerID<0?(this._joystickPointerID=t.pointerId,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)):e._globalJoystickIndex<2&&this._action&&(this._action(),this._touches.add(t.pointerId.toString(),{x:t.clientX,y:t.clientY,prevX:t.clientX,prevY:t.clientY}))},e.prototype._onPointerMove=function(e){if(this._joystickPointerID==e.pointerId){this._joystickPointerPos.x=e.clientX,this._joystickPointerPos.y=e.clientY,this._deltaJoystickVector=this._joystickPointerPos.clone(),this._deltaJoystickVector=this._deltaJoystickVector.subtract(this._joystickPointerStartPos);var t=(this.reverseLeftRight?-1:1)*this._deltaJoystickVector.x/this._inversedSensibility;switch(this._axisTargetedByLeftAndRight){case _t.X:this.deltaPosition.x=Math.min(1,Math.max(-1,t));break;case _t.Y:this.deltaPosition.y=Math.min(1,Math.max(-1,t));break;case _t.Z:this.deltaPosition.z=Math.min(1,Math.max(-1,t))}var i=(this.reverseUpDown?1:-1)*this._deltaJoystickVector.y/this._inversedSensibility;switch(this._axisTargetedByUpAndDown){case _t.X:this.deltaPosition.x=Math.min(1,Math.max(-1,i));break;case _t.Y:this.deltaPosition.y=Math.min(1,Math.max(-1,i));break;case _t.Z:this.deltaPosition.z=Math.min(1,Math.max(-1,i))}}else{var n=this._touches.get(e.pointerId.toString());n&&(n.x=e.clientX,n.y=e.clientY)}},e.prototype._onPointerUp=function(t){if(this._joystickPointerID==t.pointerId)e.vjCanvasContext.clearRect(this._joystickPointerStartPos.x-64,this._joystickPointerStartPos.y-64,128,128),e.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x-42,this._joystickPreviousPointerPos.y-42,84,84),this._joystickPointerID=-1,this.pressed=!1;else{var i=this._touches.get(t.pointerId.toString());i&&e.vjCanvasContext.clearRect(i.prevX-44,i.prevY-44,88,88)}this._deltaJoystickVector.x=0,this._deltaJoystickVector.y=0,this._touches.remove(t.pointerId.toString())},e.prototype.setJoystickColor=function(e){this._joystickColor=e},e.prototype.setActionOnTouch=function(e){this._action=e},e.prototype.setAxisForLeftRight=function(e){switch(e){case _t.X:case _t.Y:case _t.Z:this._axisTargetedByLeftAndRight=e;break;default:this._axisTargetedByLeftAndRight=_t.X}},e.prototype.setAxisForUpDown=function(e){switch(e){case _t.X:case _t.Y:case _t.Z:this._axisTargetedByUpAndDown=e;break;default:this._axisTargetedByUpAndDown=_t.Y}},e.prototype._drawVirtualJoystick=function(){var t=this;this.pressed&&this._touches.forEach(function(i,n){n.pointerId===t._joystickPointerID?(e.vjCanvasContext.clearRect(t._joystickPointerStartPos.x-64,t._joystickPointerStartPos.y-64,128,128),e.vjCanvasContext.clearRect(t._joystickPreviousPointerPos.x-42,t._joystickPreviousPointerPos.y-42,84,84),e.vjCanvasContext.beginPath(),e.vjCanvasContext.lineWidth=6,e.vjCanvasContext.strokeStyle=t._joystickColor,e.vjCanvasContext.arc(t._joystickPointerStartPos.x,t._joystickPointerStartPos.y,40,0,2*Math.PI,!0),e.vjCanvasContext.stroke(),e.vjCanvasContext.closePath(),e.vjCanvasContext.beginPath(),e.vjCanvasContext.strokeStyle=t._joystickColor,e.vjCanvasContext.lineWidth=2,e.vjCanvasContext.arc(t._joystickPointerStartPos.x,t._joystickPointerStartPos.y,60,0,2*Math.PI,!0),e.vjCanvasContext.stroke(),e.vjCanvasContext.closePath(),e.vjCanvasContext.beginPath(),e.vjCanvasContext.strokeStyle=t._joystickColor,e.vjCanvasContext.arc(t._joystickPointerPos.x,t._joystickPointerPos.y,40,0,2*Math.PI,!0),e.vjCanvasContext.stroke(),e.vjCanvasContext.closePath(),t._joystickPreviousPointerPos=t._joystickPointerPos.clone()):(e.vjCanvasContext.clearRect(n.prevX-44,n.prevY-44,88,88),e.vjCanvasContext.beginPath(),e.vjCanvasContext.fillStyle="white",e.vjCanvasContext.beginPath(),e.vjCanvasContext.strokeStyle="red",e.vjCanvasContext.lineWidth=6,e.vjCanvasContext.arc(n.x,n.y,40,0,2*Math.PI,!0),e.vjCanvasContext.stroke(),e.vjCanvasContext.closePath(),n.prevX=n.x,n.prevY=n.y)}),requestAnimationFrame(function(){t._drawVirtualJoystick()})},e.prototype.releaseCanvas=function(){e.Canvas&&(e.Canvas.removeEventListener("pointerdown",this._onPointerDownHandlerRef),e.Canvas.removeEventListener("pointermove",this._onPointerMoveHandlerRef),e.Canvas.removeEventListener("pointerup",this._onPointerUpHandlerRef),e.Canvas.removeEventListener("pointerout",this._onPointerUpHandlerRef),window.removeEventListener("resize",this._onResize),document.body.removeChild(e.Canvas),e.Canvas=null)},e._globalJoystickIndex=0,e}();dt.prototype.addVirtualJoystick=function(){return this.add(new vt),this};var vt=function(){function e(){}return e.prototype.getLeftJoystick=function(){return this._leftjoystick},e.prototype.getRightJoystick=function(){return this._rightjoystick},e.prototype.checkInputs=function(){if(this._leftjoystick){var e=this.camera,t=50*e._computeLocalCameraSpeed(),i=o.j.RotationYawPitchRoll(e.rotation.y,e.rotation.x,0),n=o.x.TransformCoordinates(new o.x(this._leftjoystick.deltaPosition.x*t,this._leftjoystick.deltaPosition.y*t,this._leftjoystick.deltaPosition.z*t),i);e.cameraDirection=e.cameraDirection.add(n),e.cameraRotation=e.cameraRotation.addVector3(this._rightjoystick.deltaPosition),this._leftjoystick.pressed||(this._leftjoystick.deltaPosition=this._leftjoystick.deltaPosition.scale(.9)),this._rightjoystick.pressed||(this._rightjoystick.deltaPosition=this._rightjoystick.deltaPosition.scale(.9))}},e.prototype.attachControl=function(e,t){this._leftjoystick=new gt(!0),this._leftjoystick.setAxisForUpDown(_t.Z),this._leftjoystick.setAxisForLeftRight(_t.X),this._leftjoystick.setJoystickSensibility(.15),this._rightjoystick=new gt(!1),this._rightjoystick.setAxisForUpDown(_t.X),this._rightjoystick.setAxisForLeftRight(_t.Y),this._rightjoystick.reverseUpDown=!0,this._rightjoystick.setJoystickSensibility(.05),this._rightjoystick.setJoystickColor("yellow")},e.prototype.detachControl=function(e){this._leftjoystick.releaseCanvas(),this._rightjoystick.releaseCanvas()},e.prototype.getClassName=function(){return"FreeCameraVirtualJoystickInput"},e.prototype.getSimpleName=function(){return"virtualJoystick"},e}();He.FreeCameraVirtualJoystickInput=vt;var yt=function(e){function t(t,i,n,r){void 0===r&&(r=!0);var s=e.call(this,t,i,n,r)||this;return s.cameraDirection=new o.x(0,0,0),s.cameraRotation=new o.w(0,0),s.updateUpVectorFromRotation=!1,s._tmpQuaternion=new o.q,s.rotation=new o.x(0,0,0),s.speed=2,s.noRotationConstraint=!1,s.lockedTarget=null,s._currentTarget=o.x.Zero(),s._initialFocalDistance=1,s._viewMatrix=o.j.Zero(),s._camMatrix=o.j.Zero(),s._cameraTransformMatrix=o.j.Zero(),s._cameraRotationMatrix=o.j.Zero(),s._referencePoint=new o.x(0,0,1),s._transformedReferencePoint=o.x.Zero(),s._globalCurrentTarget=o.x.Zero(),s._globalCurrentUpVector=o.x.Zero(),s._defaultUp=o.x.Up(),s._cachedRotationZ=0,s._cachedQuaternionRotationZ=0,s}return l.d(t,e),t.prototype.getFrontPosition=function(e){this.getWorldMatrix();var t=this.getTarget().subtract(this.position);return t.normalize(),t.scaleInPlace(e),this.globalPosition.add(t)},t.prototype._getLockedTargetPosition=function(){return this.lockedTarget?(this.lockedTarget.absolutePosition&&this.lockedTarget.computeWorldMatrix(),this.lockedTarget.absolutePosition||this.lockedTarget):null},t.prototype.storeState=function(){return this._storedPosition=this.position.clone(),this._storedRotation=this.rotation.clone(),this.rotationQuaternion&&(this._storedRotationQuaternion=this.rotationQuaternion.clone()),e.prototype.storeState.call(this)},t.prototype._restoreStateValues=function(){return!!e.prototype._restoreStateValues.call(this)&&(this.position=this._storedPosition.clone(),this.rotation=this._storedRotation.clone(),this.rotationQuaternion&&(this.rotationQuaternion=this._storedRotationQuaternion.clone()),this.cameraDirection.copyFromFloats(0,0,0),this.cameraRotation.copyFromFloats(0,0),!0)},t.prototype._initCache=function(){e.prototype._initCache.call(this),this._cache.lockedTarget=new o.x(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new o.x(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new o.q(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)},t.prototype._updateCache=function(t){t||e.prototype._updateCache.call(this);var i=this._getLockedTargetPosition();i?this._cache.lockedTarget?this._cache.lockedTarget.copyFrom(i):this._cache.lockedTarget=i.clone():this._cache.lockedTarget=null,this._cache.rotation.copyFrom(this.rotation),this.rotationQuaternion&&this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion)},t.prototype._isSynchronizedViewMatrix=function(){if(!e.prototype._isSynchronizedViewMatrix.call(this))return!1;var t=this._getLockedTargetPosition();return(this._cache.lockedTarget?this._cache.lockedTarget.equals(t):!t)&&(this.rotationQuaternion?this.rotationQuaternion.equals(this._cache.rotationQuaternion):this._cache.rotation.equals(this.rotation))},t.prototype._computeLocalCameraSpeed=function(){var e=this.getEngine();return this.speed*Math.sqrt(e.getDeltaTime()/(100*e.getFps()))},t.prototype.setTarget=function(e){this.upVector.normalize(),this._initialFocalDistance=e.subtract(this.position).length(),this.position.z===e.z&&(this.position.z+=o.h),o.j.LookAtLHToRef(this.position,e,this._defaultUp,this._camMatrix),this._camMatrix.invert(),this.rotation.x=Math.atan(this._camMatrix.m[6]/this._camMatrix.m[10]);var t=e.subtract(this.position);t.x>=0?this.rotation.y=-Math.atan(t.z/t.x)+Math.PI/2:this.rotation.y=-Math.atan(t.z/t.x)-Math.PI/2,this.rotation.z=0,isNaN(this.rotation.x)&&(this.rotation.x=0),isNaN(this.rotation.y)&&(this.rotation.y=0),isNaN(this.rotation.z)&&(this.rotation.z=0),this.rotationQuaternion&&o.q.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this.rotationQuaternion)},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(o.t.Matrix[0]),o.x.TransformNormalToRef(this.cameraDirection,o.t.Matrix[0],o.t.Vector3[0]),void this.position.addInPlace(o.t.Vector3[0]);this.position.addInPlace(this.cameraDirection)},t.prototype._checkInputs=function(){var t=this._decideIfNeedsToMove(),i=Math.abs(this.cameraRotation.x)>0||Math.abs(this.cameraRotation.y)>0;if(t&&this._updatePosition(),i){if(this.rotation.x+=this.cameraRotation.x,this.rotation.y+=this.cameraRotation.y,this.rotationQuaternion)this.rotation.lengthSquared()&&o.q.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this.rotationQuaternion);if(!this.noRotationConstraint){this.rotation.x>1.570796&&(this.rotation.x=1.570796),this.rotation.x<-1.570796&&(this.rotation.x=-1.570796)}}t&&(Math.abs(this.cameraDirection.x)me.b.CollisionsEpsilon&&(s.position.addInPlace(s._diffPosition),s.onCollide&&i&&s.onCollide(i))},s.inputs=new dt(s),s.inputs.addKeyboard().addMouse(),s}return l.d(t,e),Object.defineProperty(t.prototype,"angularSensibility",{get:function(){var e=this.inputs.attached.mouse;return e?e.angularSensibility:0},set:function(e){var t=this.inputs.attached.mouse;t&&(t.angularSensibility=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"keysUp",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysUp:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysUp=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"keysDown",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysDown:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysDown=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"keysLeft",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysLeft:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"keysRight",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysRight:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysRight=e)},enumerable:!0,configurable:!0}),t.prototype.attachControl=function(e,t){this.inputs.attachElement(e,t)},t.prototype.detachControl=function(e){this.inputs.detachElement(e),this.cameraDirection=new o.x(0,0,0),this.cameraRotation=new o.w(0,0)},Object.defineProperty(t.prototype,"collisionMask",{get:function(){return this._collisionMask},set:function(e){this._collisionMask=isNaN(e)?-1:e},enumerable:!0,configurable:!0}),t.prototype._collideWithWorld=function(e){(this.parent?o.x.TransformCoordinates(this.position,this.parent.getWorldMatrix()):this.position).subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);var t=this.getScene().collisionCoordinator;this._collider||(this._collider=t.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;var i=e;this.applyGravity&&(i=e.add(this.getScene().gravity)),t.getNewPosition(this._oldPosition,i,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)},t.prototype._checkInputs=function(){this._localDirection||(this._localDirection=o.x.Zero(),this._transformedDirection=o.x.Zero()),this.inputs.checkInputs(),e.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):e.prototype._updatePosition.call(this)},t.prototype.dispose=function(){this.inputs.clear(),e.prototype.dispose.call(this)},t.prototype.getClassName=function(){return"FreeCamera"},l.c([Object(L.o)()],t.prototype,"ellipsoid",void 0),l.c([Object(L.o)()],t.prototype,"ellipsoidOffset",void 0),l.c([Object(L.c)()],t.prototype,"checkCollisions",void 0),l.c([Object(L.c)()],t.prototype,"applyGravity",void 0),t}(yt);F.a.AddNodeConstructor("TouchCamera",function(e,t){return function(){return new Tt(e,o.x.Zero(),t)}});var Tt=function(e){function t(t,i,n){var r=e.call(this,t,i,n)||this;return r.inputs.addTouch(),r._setupInputs(),r}return l.d(t,e),Object.defineProperty(t.prototype,"touchAngularSensibility",{get:function(){var e=this.inputs.attached.touch;return e?e.touchAngularSensibility:0},set:function(e){var t=this.inputs.attached.touch;t&&(t.touchAngularSensibility=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"touchMoveSensibility",{get:function(){var e=this.inputs.attached.touch;return e?e.touchMoveSensibility:0},set:function(e){var t=this.inputs.attached.touch;t&&(t.touchMoveSensibility=e)},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"TouchCamera"},t.prototype._setupInputs=function(){var e=this.inputs.attached.mouse;e&&(e.touchEnabled=!1)},t}(bt);F.a.AddNodeConstructor("ArcRotateCamera",function(e,t){return function(){return new Et(e,0,0,1,o.x.Zero(),t)}});var Et=function(e){function t(t,i,n,s,a,c,l){void 0===l&&(l=!0);var u=e.call(this,t,o.x.Zero(),c,l)||this;return u._upVector=o.x.Up(),u.inertialAlphaOffset=0,u.inertialBetaOffset=0,u.inertialRadiusOffset=0,u.lowerAlphaLimit=null,u.upperAlphaLimit=null,u.lowerBetaLimit=.01,u.upperBetaLimit=Math.PI-.01,u.lowerRadiusLimit=null,u.upperRadiusLimit=null,u.inertialPanningX=0,u.inertialPanningY=0,u.pinchToPanMaxDistance=20,u.panningDistanceLimit=null,u.panningOriginTarget=o.x.Zero(),u.panningInertia=.9,u.zoomOnFactor=1,u.targetScreenOffset=o.w.Zero(),u.allowUpsideDown=!0,u.useInputToRestoreState=!0,u._viewMatrix=new o.j,u.panningAxis=new o.x(1,1,0),u.onMeshTargetChangedObservable=new r.c,u.checkCollisions=!1,u.collisionRadius=new o.x(.5,.5,.5),u._previousPosition=o.x.Zero(),u._collisionVelocity=o.x.Zero(),u._newPosition=o.x.Zero(),u._computationVector=o.x.Zero(),u._onCollisionPositionChange=function(e,t,i){void 0===i&&(i=null),i?(u.setPosition(t),u.onCollide&&u.onCollide(i)):u._previousPosition.copyFrom(u._position);var n=Math.cos(u.alpha),r=Math.sin(u.alpha),o=Math.cos(u.beta),s=Math.sin(u.beta);0===s&&(s=1e-4);var a=u._getTargetPosition();u._computationVector.copyFromFloats(u.radius*n*s,u.radius*o,u.radius*r*s),a.addToRef(u._computationVector,u._newPosition),u._position.copyFrom(u._newPosition);var c=u.upVector;u.allowUpsideDown&&u.beta<0&&(c=(c=c.clone()).negate()),u._computeViewMatrix(u._position,a,c),u._viewMatrix.addAtIndex(12,u.targetScreenOffset.x),u._viewMatrix.addAtIndex(13,u.targetScreenOffset.y),u._collisionTriggered=!1},u._target=o.x.Zero(),a&&u.setTarget(a),u.alpha=i,u.beta=n,u.radius=s,u.getViewMatrix(),u.inputs=new it(u),u.inputs.addKeyboard().addMouseWheel().addPointers(),u}return l.d(t,e),Object.defineProperty(t.prototype,"target",{get:function(){return this._target},set:function(e){this.setTarget(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"position",{get:function(){return this._position},set:function(e){this.setPosition(e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"upVector",{get:function(){return this._upVector},set:function(e){this._upToYMatrix||(this._YToUpMatrix=new o.j,this._upToYMatrix=new o.j,this._upVector=o.x.Zero()),e.normalize(),this._upVector.copyFrom(e),this.setMatUp()},enumerable:!0,configurable:!0}),t.prototype.setMatUp=function(){o.j.RotationAlignToRef(o.x.UpReadOnly,this._upVector,this._YToUpMatrix),o.j.RotationAlignToRef(this._upVector,o.x.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 t=this.inputs.attached.pointers;t&&(t.angularSensibilityX=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"angularSensibilityY",{get:function(){var e=this.inputs.attached.pointers;return e?e.angularSensibilityY:0},set:function(e){var t=this.inputs.attached.pointers;t&&(t.angularSensibilityY=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"pinchPrecision",{get:function(){var e=this.inputs.attached.pointers;return e?e.pinchPrecision:0},set:function(e){var t=this.inputs.attached.pointers;t&&(t.pinchPrecision=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"pinchDeltaPercentage",{get:function(){var e=this.inputs.attached.pointers;return e?e.pinchDeltaPercentage:0},set:function(e){var t=this.inputs.attached.pointers;t&&(t.pinchDeltaPercentage=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"panningSensibility",{get:function(){var e=this.inputs.attached.pointers;return e?e.panningSensibility:0},set:function(e){var t=this.inputs.attached.pointers;t&&(t.panningSensibility=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"keysUp",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysUp:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysUp=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"keysDown",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysDown:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysDown=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"keysLeft",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysLeft:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"keysRight",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysRight:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysRight=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"wheelPrecision",{get:function(){var e=this.inputs.attached.mousewheel;return e?e.wheelPrecision:0},set:function(e){var t=this.inputs.attached.mousewheel;t&&(t.wheelPrecision=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"wheelDeltaPercentage",{get:function(){var e=this.inputs.attached.mousewheel;return e?e.wheelDeltaPercentage:0},set:function(e){var t=this.inputs.attached.mousewheel;t&&(t.wheelDeltaPercentage=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"bouncingBehavior",{get:function(){return this._bouncingBehavior},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"useBouncingBehavior",{get:function(){return null!=this._bouncingBehavior},set:function(e){e!==this.useBouncingBehavior&&(e?(this._bouncingBehavior=new Ce,this.addBehavior(this._bouncingBehavior)):this._bouncingBehavior&&(this.removeBehavior(this._bouncingBehavior),this._bouncingBehavior=null))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"framingBehavior",{get:function(){return this._framingBehavior},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"useFramingBehavior",{get:function(){return null!=this._framingBehavior},set:function(e){e!==this.useFramingBehavior&&(e?(this._framingBehavior=new Me,this.addBehavior(this._framingBehavior)):this._framingBehavior&&(this.removeBehavior(this._framingBehavior),this._framingBehavior=null))},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"autoRotationBehavior",{get:function(){return this._autoRotationBehavior},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"useAutoRotationBehavior",{get:function(){return null!=this._autoRotationBehavior},set:function(e){e!==this.useAutoRotationBehavior&&(e?(this._autoRotationBehavior=new Se,this.addBehavior(this._autoRotationBehavior)):this._autoRotationBehavior&&(this.removeBehavior(this._autoRotationBehavior),this._autoRotationBehavior=null))},enumerable:!0,configurable:!0}),t.prototype._initCache=function(){e.prototype._initCache.call(this),this._cache._target=new o.x(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.alpha=void 0,this._cache.beta=void 0,this._cache.radius=void 0,this._cache.targetScreenOffset=o.w.Zero()},t.prototype._updateCache=function(t){t||e.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 t=this._getLockedTargetPosition();return t||this._target},t.prototype.storeState=function(){return this._storedAlpha=this.alpha,this._storedBeta=this.beta,this._storedRadius=this.radius,this._storedTarget=this._getTargetPosition().clone(),e.prototype.storeState.call(this)},t.prototype._restoreStateValues=function(){return!!e.prototype._restoreStateValues.call(this)&&(this.alpha=this._storedAlpha,this.beta=this._storedBeta,this.radius=this._storedRadius,this.setTarget(this._storedTarget.clone()),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0,!0)},t.prototype._isSynchronizedViewMatrix=function(){return!!e.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,t,i,n){var r=this;void 0===i&&(i=!0),void 0===n&&(n=2),this._useCtrlForPanning=i,this._panningMouseButton=n,this.inputs.attachElement(e,t),this._reset=function(){r.inertialAlphaOffset=0,r.inertialBetaOffset=0,r.inertialRadiusOffset=0,r.inertialPanningX=0,r.inertialPanningY=0}},t.prototype.detachControl=function(e){this.inputs.detachElement(e),this._reset&&this._reset()},t.prototype._checkInputs=function(){if(!this._collisionTriggered){if(this.inputs.checkInputs(),0!==this.inertialAlphaOffset||0!==this.inertialBetaOffset||0!==this.inertialRadiusOffset){var t=this.inertialAlphaOffset;this.beta<=0&&(t*=-1),this.getScene().useRightHandedSystem&&(t*=-1),this.parent&&this.parent._getWorldMatrixDeterminant()<0&&(t*=-1),this.alpha+=t,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),null!==this.lowerAlphaLimit&&this.alphathis.upperAlphaLimit&&(this.alpha=this.upperAlphaLimit),null!==this.lowerRadiusLimit&&this.radiusthis.upperRadiusLimit&&(this.radius=this.upperRadiusLimit,this.inertialRadiusOffset=0)},t.prototype.rebuildAnglesAndRadius=function(){this._position.subtractToRef(this._getTargetPosition(),this._computationVector),0===this._upVector.x&&1===this._upVector.y&&0===this._upVector.z||o.x.TransformCoordinatesToRef(this._computationVector,this._upToYMatrix,this._computationVector),this.radius=this._computationVector.length(),0===this.radius&&(this.radius=1e-4),0===this._computationVector.x&&0===this._computationVector.z?this.alpha=Math.PI/2:this.alpha=Math.acos(this._computationVector.x/Math.sqrt(Math.pow(this._computationVector.x,2)+Math.pow(this._computationVector.z,2))),this._computationVector.z<0&&(this.alpha=2*Math.PI-this.alpha),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,t,i){if(void 0===t&&(t=!1),void 0===i&&(i=!1),e.getBoundingInfo)this._targetBoundingCenter=t?e.getBoundingInfo().boundingBox.centerWorld.clone():null,e.computeWorldMatrix(),this._targetHost=e,this._target=this._getTargetPosition(),this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);else{var n=e,r=this._getTargetPosition();if(r&&!i&&r.equals(n))return;this._targetHost=null,this._target=n,this._targetBoundingCenter=null,this.onMeshTargetChangedObservable.notifyObservers(null)}this.rebuildAnglesAndRadius()},t.prototype._getViewMatrix=function(){var e=Math.cos(this.alpha),t=Math.sin(this.alpha),i=Math.cos(this.beta),n=Math.sin(this.beta);0===n&&(n=1e-4);var r=this._getTargetPosition();if(this._computationVector.copyFromFloats(this.radius*e*n,this.radius*i,this.radius*t*n),0===this._upVector.x&&1===this._upVector.y&&0===this._upVector.z||o.x.TransformCoordinatesToRef(this._computationVector,this._YToUpMatrix,this._computationVector),r.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 a=this.upVector;this.allowUpsideDown&&n<0&&(a=(a=a.clone()).negate()),this._computeViewMatrix(this._position,r,a),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y)}return this._currentTarget=r,this._viewMatrix},t.prototype.zoomOn=function(e,t){void 0===t&&(t=!1),e=e||this.getScene().meshes;var i=fe.a.MinMax(e),n=o.x.Distance(i.min,i.max);this.radius=n*this.zoomOnFactor,this.focusOn({min:i.min,max:i.max,distance:n},t)},t.prototype.focusOn=function(e,t){var i,n;if(void 0===t&&(t=!1),void 0===e.min){var r=e||this.getScene().meshes;i=fe.a.MinMax(r),n=o.x.Distance(i.min,i.max)}else{i=e,n=e.distance}this._target=fe.a.Center(i),t||(this.maxZ=2*n)},t.prototype.createRigCamera=function(e,i){var n=0;switch(this.cameraRigMode){case Ne.a.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case Ne.a.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case Ne.a.RIG_MODE_STEREOSCOPIC_OVERUNDER:case Ne.a.RIG_MODE_VR:n=this._cameraRigParams.stereoHalfAngle*(0===i?1:-1);break;case Ne.a.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:n=this._cameraRigParams.stereoHalfAngle*(0===i?-1:1)}var r=new t(e,this.alpha+n,this.beta,this.radius,this._target,this.getScene());return r._cameraRigParams={},r},t.prototype._updateRigCameras=function(){var t=this._rigCameras[0],i=this._rigCameras[1];switch(t.beta=i.beta=this.beta,this.cameraRigMode){case Ne.a.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case Ne.a.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case Ne.a.RIG_MODE_STEREOSCOPIC_OVERUNDER:case Ne.a.RIG_MODE_VR:t.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,i.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case Ne.a.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:t.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle,i.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle}e.prototype._updateRigCameras.call(this)},t.prototype.dispose=function(){this.inputs.clear(),e.prototype.dispose.call(this)},t.prototype.getClassName=function(){return"ArcRotateCamera"},l.c([Object(L.c)()],t.prototype,"alpha",void 0),l.c([Object(L.c)()],t.prototype,"beta",void 0),l.c([Object(L.c)()],t.prototype,"radius",void 0),l.c([Object(L.o)("target")],t.prototype,"_target",void 0),l.c([Object(L.o)("upVector")],t.prototype,"_upVector",void 0),l.c([Object(L.c)()],t.prototype,"inertialAlphaOffset",void 0),l.c([Object(L.c)()],t.prototype,"inertialBetaOffset",void 0),l.c([Object(L.c)()],t.prototype,"inertialRadiusOffset",void 0),l.c([Object(L.c)()],t.prototype,"lowerAlphaLimit",void 0),l.c([Object(L.c)()],t.prototype,"upperAlphaLimit",void 0),l.c([Object(L.c)()],t.prototype,"lowerBetaLimit",void 0),l.c([Object(L.c)()],t.prototype,"upperBetaLimit",void 0),l.c([Object(L.c)()],t.prototype,"lowerRadiusLimit",void 0),l.c([Object(L.c)()],t.prototype,"upperRadiusLimit",void 0),l.c([Object(L.c)()],t.prototype,"inertialPanningX",void 0),l.c([Object(L.c)()],t.prototype,"inertialPanningY",void 0),l.c([Object(L.c)()],t.prototype,"pinchToPanMaxDistance",void 0),l.c([Object(L.c)()],t.prototype,"panningDistanceLimit",void 0),l.c([Object(L.o)()],t.prototype,"panningOriginTarget",void 0),l.c([Object(L.c)()],t.prototype,"panningInertia",void 0),l.c([Object(L.c)()],t.prototype,"zoomOnFactor",void 0),l.c([Object(L.c)()],t.prototype,"targetScreenOffset",void 0),l.c([Object(L.c)()],t.prototype,"allowUpsideDown",void 0),l.c([Object(L.c)()],t.prototype,"useInputToRestoreState",void 0),t}(yt);F.a.AddNodeConstructor("DeviceOrientationCamera",function(e,t){return function(){return new xt(e,o.x.Zero(),t)}});var xt=function(e){function t(t,i,n){var r=e.call(this,t,i,n)||this;return r._tmpDragQuaternion=new o.q,r._disablePointerInputWhenUsingDeviceOrientation=!0,r._dragFactor=0,r._quaternionCache=new o.q,r.inputs.addDeviceOrientation(),r.inputs._deviceOrientationInput&&r.inputs._deviceOrientationInput._onDeviceOrientationChangedObservable.addOnce(function(){r._disablePointerInputWhenUsingDeviceOrientation&&r.inputs._mouseInput&&(r.inputs._mouseInput._allowCameraRotation=!1,r.inputs._mouseInput.onPointerMovedObservable.add(function(e){0!=r._dragFactor&&(r._initialQuaternion||(r._initialQuaternion=new o.q),o.q.FromEulerAnglesToRef(0,e.offsetX*r._dragFactor,0,r._tmpDragQuaternion),r._initialQuaternion.multiplyToRef(r._tmpDragQuaternion,r._initialQuaternion))}))}),r}return l.d(t,e),t.prototype.enableHorizontalDragging=function(e){void 0===e&&(e=1/300),this._dragFactor=e},t.prototype.getClassName=function(){return"DeviceOrientationCamera"},t.prototype._checkInputs=function(){e.prototype._checkInputs.call(this),this._quaternionCache.copyFrom(this.rotationQuaternion),this._initialQuaternion&&this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)},t.prototype.resetToCurrentRotation=function(e){var t=this;void 0===e&&(e=o.c.Y),this.rotationQuaternion&&(this._initialQuaternion||(this._initialQuaternion=new o.q),this._initialQuaternion.copyFrom(this._quaternionCache||this.rotationQuaternion),["x","y","z"].forEach(function(i){e[i]?t._initialQuaternion[i]*=-1:t._initialQuaternion[i]=0}),this._initialQuaternion.normalize(),this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion))},t}(bt),At=function(e){function t(t){return e.call(this,t)||this}return l.d(t,e),t.prototype.addKeyboard=function(){return this.add(new rt),this},t.prototype.addMouse=function(e){return void 0===e&&(e=!0),this.add(new ot(e)),this},t}(Xe),Pt=function(e){function t(t,i,n,r){void 0===r&&(r=!0);var s=e.call(this,t,i,n,r)||this;return s.ellipsoid=new o.x(1,1,1),s.ellipsoidOffset=new o.x(0,0,0),s.checkCollisions=!1,s.applyGravity=!1,s.cameraDirection=o.x.Zero(),s._trackRoll=0,s.rollCorrect=100,s.bankedTurn=!1,s.bankedTurnLimit=Math.PI/2,s.bankedTurnMultiplier=1,s._needMoveForGravity=!1,s._oldPosition=o.x.Zero(),s._diffPosition=o.x.Zero(),s._newPosition=o.x.Zero(),s._collisionMask=-1,s._onCollisionPositionChange=function(e,t,i){void 0===i&&(i=null);var n;n=t,s._newPosition.copyFrom(n),s._newPosition.subtractToRef(s._oldPosition,s._diffPosition),s._diffPosition.length()>me.b.CollisionsEpsilon&&(s.position.addInPlace(s._diffPosition),s.onCollide&&i&&s.onCollide(i))},s.inputs=new At(s),s.inputs.addKeyboard().addMouse(),s}return l.d(t,e),Object.defineProperty(t.prototype,"angularSensibility",{get:function(){var e=this.inputs.attached.mouse;return e?e.angularSensibility:0},set:function(e){var t=this.inputs.attached.mouse;t&&(t.angularSensibility=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"keysForward",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysForward:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysForward=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"keysBackward",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysBackward:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysBackward=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"keysUp",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysUp:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysUp=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"keysDown",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysDown:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysDown=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"keysLeft",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysLeft:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"keysRight",{get:function(){var e=this.inputs.attached.keyboard;return e?e.keysRight:[]},set:function(e){var t=this.inputs.attached.keyboard;t&&(t.keysRight=e)},enumerable:!0,configurable:!0}),t.prototype.attachControl=function(e,t){this.inputs.attachElement(e,t)},t.prototype.detachControl=function(e){this.inputs.detachElement(e),this.cameraDirection=new o.x(0,0,0)},Object.defineProperty(t.prototype,"collisionMask",{get:function(){return this._collisionMask},set:function(e){this._collisionMask=isNaN(e)?-1:e},enumerable:!0,configurable:!0}),t.prototype._collideWithWorld=function(e){(this.parent?o.x.TransformCoordinates(this.position,this.parent.getWorldMatrix()):this.position).subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);var t=this.getScene().collisionCoordinator;this._collider||(this._collider=t.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;var i=e;this.applyGravity&&(i=e.add(this.getScene().gravity)),t.getNewPosition(this._oldPosition,i,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)},t.prototype._checkInputs=function(){this._localDirection||(this._localDirection=o.x.Zero(),this._transformedDirection=o.x.Zero()),this.inputs.checkInputs(),e.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):e.prototype._updatePosition.call(this)},t.prototype.restoreRoll=function(e){var t=this._trackRoll,i=t-this.rotation.z;Math.abs(i)>=.001&&(this.rotation.z+=i/e,Math.abs(t-this.rotation.z)<=.001&&(this.rotation.z=t))},t.prototype.dispose=function(){this.inputs.clear(),e.prototype.dispose.call(this)},t.prototype.getClassName=function(){return"FlyCamera"},l.c([Object(L.o)()],t.prototype,"ellipsoid",void 0),l.c([Object(L.o)()],t.prototype,"ellipsoidOffset",void 0),l.c([Object(L.c)()],t.prototype,"checkCollisions",void 0),l.c([Object(L.c)()],t.prototype,"applyGravity",void 0),t}(yt),Rt=function(e){function t(t){return e.call(this,t)||this}return l.d(t,e),t.prototype.addKeyboard=function(){return this.add(new st),this},t.prototype.addMouseWheel=function(){return this.add(new at),this},t.prototype.addPointers=function(){return this.add(new ct),this},t.prototype.addVRDeviceOrientation=function(){return console.warn("DeviceOrientation support not yet implemented for FollowCamera."),this},t}(Xe);F.a.AddNodeConstructor("FollowCamera",function(e,t){return function(){return new Ct(e,o.x.Zero(),t)}}),F.a.AddNodeConstructor("ArcFollowCamera",function(e,t){return function(){return new Mt(e,0,0,1,null,t)}});var St,Ct=function(e){function t(t,i,n,r){void 0===r&&(r=null);var o=e.call(this,t,i,n)||this;return o.radius=12,o.lowerRadiusLimit=null,o.upperRadiusLimit=null,o.rotationOffset=0,o.lowerRotationOffsetLimit=null,o.upperRotationOffsetLimit=null,o.heightOffset=4,o.lowerHeightOffsetLimit=null,o.upperHeightOffsetLimit=null,o.cameraAcceleration=.05,o.maxCameraSpeed=20,o.lockedTarget=r,o.inputs=new Rt(o),o.inputs.addKeyboard().addMouseWheel().addPointers(),o}return l.d(t,e),t.prototype._follow=function(e){if(e){var t;if(e.rotationQuaternion){var i=new o.j;e.rotationQuaternion.toRotationMatrix(i),t=Math.atan2(i.m[8],i.m[10])}else t=e.rotation.y;var n=ye.h.ToRadians(this.rotationOffset)+t,r=e.getAbsolutePosition(),s=r.x+Math.sin(n)*this.radius,a=r.z+Math.cos(n)*this.radius,c=s-this.position.x,l=r.y+this.heightOffset-this.position.y,u=a-this.position.z,h=c*this.cameraAcceleration*2,d=l*this.cameraAcceleration,f=u*this.cameraAcceleration*2;(h>this.maxCameraSpeed||h<-this.maxCameraSpeed)&&(h=h<1?-this.maxCameraSpeed:this.maxCameraSpeed),(d>this.maxCameraSpeed||d<-this.maxCameraSpeed)&&(d=d<1?-this.maxCameraSpeed:this.maxCameraSpeed),(f>this.maxCameraSpeed||f<-this.maxCameraSpeed)&&(f=f<1?-this.maxCameraSpeed:this.maxCameraSpeed),this.position=new o.x(this.position.x+h,this.position.y+d,this.position.z+f),this.setTarget(r)}},t.prototype.attachControl=function(e,t){this.inputs.attachElement(e,t),this._reset=function(){}},t.prototype.detachControl=function(e){this.inputs.detachElement(e),this._reset&&this._reset()},t.prototype._checkInputs=function(){this.inputs.checkInputs(),this._checkLimits(),e.prototype._checkInputs.call(this),this.lockedTarget&&this._follow(this.lockedTarget)},t.prototype._checkLimits=function(){null!==this.lowerRadiusLimit&&this.radiusthis.upperRadiusLimit&&(this.radius=this.upperRadiusLimit),null!==this.lowerHeightOffsetLimit&&this.heightOffsetthis.upperHeightOffsetLimit&&(this.heightOffset=this.upperHeightOffsetLimit),null!==this.lowerRotationOffsetLimit&&this.rotationOffsetthis.upperRotationOffsetLimit&&(this.rotationOffset=this.upperRotationOffsetLimit)},t.prototype.getClassName=function(){return"FollowCamera"},l.c([Object(L.c)()],t.prototype,"radius",void 0),l.c([Object(L.c)()],t.prototype,"lowerRadiusLimit",void 0),l.c([Object(L.c)()],t.prototype,"upperRadiusLimit",void 0),l.c([Object(L.c)()],t.prototype,"rotationOffset",void 0),l.c([Object(L.c)()],t.prototype,"lowerRotationOffsetLimit",void 0),l.c([Object(L.c)()],t.prototype,"upperRotationOffsetLimit",void 0),l.c([Object(L.c)()],t.prototype,"heightOffset",void 0),l.c([Object(L.c)()],t.prototype,"lowerHeightOffsetLimit",void 0),l.c([Object(L.c)()],t.prototype,"upperHeightOffsetLimit",void 0),l.c([Object(L.c)()],t.prototype,"cameraAcceleration",void 0),l.c([Object(L.c)()],t.prototype,"maxCameraSpeed",void 0),l.c([Object(L.k)("lockedTargetId")],t.prototype,"lockedTarget",void 0),t}(yt),Mt=function(e){function t(t,i,n,r,s,a){var c=e.call(this,t,o.x.Zero(),a)||this;return c.alpha=i,c.beta=n,c.radius=r,c.target=s,c._cartesianCoordinates=o.x.Zero(),c._follow(),c}return l.d(t,e),t.prototype._follow=function(){if(this.target){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.target.getAbsolutePosition();this.position=e.add(this._cartesianCoordinates),this.setTarget(e)}},t.prototype._checkInputs=function(){e.prototype._checkInputs.call(this),this._follow()},t.prototype.getClassName=function(){return"ArcFollowCamera"},t}(yt),Ot=i(35),It=i(41);!function(e){e[e.VIVE=0]="VIVE",e[e.OCULUS=1]="OCULUS",e[e.WINDOWS=2]="WINDOWS",e[e.GEAR_VR=3]="GEAR_VR",e[e.DAYDREAM=4]="DAYDREAM",e[e.GENERIC=5]="GENERIC"}(St||(St={}));var Dt,Lt,wt=function(){function e(){}return e.InitiateController=function(e){for(var t=0,i=this._ControllerFactories;tthis._maxRotationDistFromHeadset){var n=i-(i<0?-this._maxRotationDistFromHeadset:this._maxRotationDistFromHeadset);this._draggedRoomRotation+=n;var r=Math.sin(-n),s=Math.cos(-n);this._calculatedPosition.x=this._calculatedPosition.x*s-this._calculatedPosition.z*r,this._calculatedPosition.z=this._calculatedPosition.x*r+this._calculatedPosition.z*s}}o.x.TransformCoordinatesToRef(this._calculatedPosition,this._deviceToWorld,this.devicePosition),this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix),o.q.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(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 t=this.rawPose;e.orientation&&t.orientation&&(this._deviceRoomRotationQuaternion.copyFromFloats(t.orientation[0],t.orientation[1],-t.orientation[2],-t.orientation[3]),this._mesh&&(this._mesh.getScene().useRightHandedSystem?(this._deviceRoomRotationQuaternion.z*=-1,this._deviceRoomRotationQuaternion.w*=-1):this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion,this._deviceRoomRotationQuaternion)),this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion,this._calculatedRotation))}},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 o.q),this._updatePoseAndMesh(),this._pointingPoseNode){for(var t=[],i=this._pointingPoseNode;i.parent;)t.push(i.parent),i=i.parent;t.reverse().forEach(function(e){e.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,e.prototype.dispose.call(this)},Object.defineProperty(t.prototype,"mesh",{get:function(){return this._mesh},enumerable:!0,configurable:!0}),t.prototype.getForwardRay=function(e){if(void 0===e&&(e=100),!this.mesh)return new It.a(o.x.Zero(),new o.x(0,0,1),e);var t=this._pointingPoseNode?this._pointingPoseNode.getWorldMatrix():this.mesh.getWorldMatrix(),i=t.getTranslation(),n=new o.x(0,0,-1),r=o.x.TransformNormal(n,t),s=o.x.Normalize(r);return new It.a(i,s,e)},t.POINTING_POSE="POINTING_POSE",t}(Ke);!function(e){e[e.A=0]="A",e[e.B=1]="B",e[e.X=2]="X",e[e.Y=3]="Y",e[e.Start=4]="Start",e[e.Back=5]="Back",e[e.LB=6]="LB",e[e.RB=7]="RB",e[e.LeftStick=8]="LeftStick",e[e.RightStick=9]="RightStick"}(Dt||(Dt={})),function(e){e[e.Up=0]="Up",e[e.Down=1]="Down",e[e.Left=2]="Left",e[e.Right=3]="Right"}(Lt||(Lt={}));var Nt=function(e){function t(t,i,n,o){void 0===o&&(o=!1);var s=e.call(this,t,i,n,0,1,2,3)||this;return s._leftTrigger=0,s._rightTrigger=0,s.onButtonDownObservable=new r.c,s.onButtonUpObservable=new r.c,s.onPadDownObservable=new r.c,s.onPadUpObservable=new r.c,s._buttonA=0,s._buttonB=0,s._buttonX=0,s._buttonY=0,s._buttonBack=0,s._buttonStart=0,s._buttonLB=0,s._buttonRB=0,s._buttonLeftStick=0,s._buttonRightStick=0,s._dPadUp=0,s._dPadDown=0,s._dPadLeft=0,s._dPadRight=0,s._isXboxOnePad=!1,s.type=Ke.XBOX,s._isXboxOnePad=o,s}return l.d(t,e),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:!0,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:!0,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,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e},t.prototype._setDPadValue=function(e,t,i){return e!==t&&(1===e&&(this._ondpaddown&&this._ondpaddown(i),this.onPadDownObservable.notifyObservers(i)),0===e&&(this._ondpadup&&this._ondpadup(i),this.onPadUpObservable.notifyObservers(i))),e},Object.defineProperty(t.prototype,"buttonA",{get:function(){return this._buttonA},set:function(e){this._buttonA=this._setButtonValue(e,this._buttonA,Dt.A)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"buttonB",{get:function(){return this._buttonB},set:function(e){this._buttonB=this._setButtonValue(e,this._buttonB,Dt.B)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"buttonX",{get:function(){return this._buttonX},set:function(e){this._buttonX=this._setButtonValue(e,this._buttonX,Dt.X)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"buttonY",{get:function(){return this._buttonY},set:function(e){this._buttonY=this._setButtonValue(e,this._buttonY,Dt.Y)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"buttonStart",{get:function(){return this._buttonStart},set:function(e){this._buttonStart=this._setButtonValue(e,this._buttonStart,Dt.Start)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"buttonBack",{get:function(){return this._buttonBack},set:function(e){this._buttonBack=this._setButtonValue(e,this._buttonBack,Dt.Back)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"buttonLB",{get:function(){return this._buttonLB},set:function(e){this._buttonLB=this._setButtonValue(e,this._buttonLB,Dt.LB)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"buttonRB",{get:function(){return this._buttonRB},set:function(e){this._buttonRB=this._setButtonValue(e,this._buttonRB,Dt.RB)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"buttonLeftStick",{get:function(){return this._buttonLeftStick},set:function(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,Dt.LeftStick)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"buttonRightStick",{get:function(){return this._buttonRightStick},set:function(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,Dt.RightStick)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"dPadUp",{get:function(){return this._dPadUp},set:function(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,Lt.Up)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"dPadDown",{get:function(){return this._dPadDown},set:function(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,Lt.Down)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"dPadLeft",{get:function(){return this._dPadLeft},set:function(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,Lt.Left)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"dPadRight",{get:function(){return this._dPadRight},set:function(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,Lt.Right)},enumerable:!0,configurable:!0}),t.prototype.update=function(){e.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.axes[2],this.rightTrigger=this.browserGamepad.axes[5],this.buttonBack=this.browserGamepad.buttons[9].value,this.buttonStart=this.browserGamepad.buttons[8].value,this.buttonLeftStick=this.browserGamepad.buttons[6].value,this.buttonRightStick=this.browserGamepad.buttons[7].value,this.dPadUp=this.browserGamepad.buttons[11].value,this.dPadDown=this.browserGamepad.buttons[12].value,this.dPadLeft=this.browserGamepad.buttons[13].value,this.dPadRight=this.browserGamepad.buttons[14].value):(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(){e.prototype.dispose.call(this),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear(),this.onPadDownObservable.clear(),this.onPadUpObservable.clear()},t}(Ke),Bt=function(){function e(e){var t=this;this._scene=e,this._babylonGamepads=[],this._oneGamepadConnected=!1,this._isMonitoring=!1,this.onGamepadDisconnectedObservable=new r.c,Ot.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(e){for(var i in t._babylonGamepads){var n=t._babylonGamepads[i];n&&n._isConnected&&t.onGamepadConnectedObservable.notifyObserver(e,n)}}),this._onGamepadConnectedEvent=function(e){var i,n=e.gamepad;n.index in t._babylonGamepads&&t._babylonGamepads[n.index].isConnected||(t._babylonGamepads[n.index]?((i=t._babylonGamepads[n.index]).browserGamepad=n,i._isConnected=!0):i=t._addNewGamepad(n),t.onGamepadConnectedObservable.notifyObservers(i),t._startMonitoringGamepads())},this._onGamepadDisconnectedEvent=function(e){var i=e.gamepad;for(var n in t._babylonGamepads)if(t._babylonGamepads[n].index===i.index){var r=t._babylonGamepads[n];r._isConnected=!1,t.onGamepadDisconnectedObservable.notifyObservers(r);break}},this._gamepadSupport&&(this._updateGamepadObjects(),this._babylonGamepads.length&&this._startMonitoringGamepads(),this._gamepadEventSupported?(window.addEventListener("gamepadconnected",this._onGamepadConnectedEvent,!1),window.addEventListener("gamepaddisconnected",this._onGamepadDisconnectedEvent,!1)):this._startMonitoringGamepads())}return Object.defineProperty(e.prototype,"gamepads",{get:function(){return this._babylonGamepads},enumerable:!0,configurable:!0}),e.prototype.getGamepadByType=function(e){void 0===e&&(e=Ke.XBOX);for(var t=0,i=this._babylonGamepads;t0){for(var p=0;p0)for(var e=0;e0){var n=this._camera._getFirstPostProcess();n&&n.markTextureDirty()}this.onActivateObservable.clear(),this.onAfterRenderObservable.clear(),this.onApplyObservable.clear(),this.onBeforeRenderObservable.clear(),this.onSizeChangedObservable.clear()}},e}(),Ht="\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}";zt.a.ShadersStore.passPixelShader=Ht;var Xt="\nvarying vec2 vUV;\nuniform samplerCube textureSampler;\nvoid main(void)\n{\nvec2 uv=vUV*2.0-1.0;\n#ifdef POSITIVEX\ngl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x));\n#endif\n#ifdef NEGATIVEX\ngl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x));\n#endif\n#ifdef POSITIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x));\n#endif\n#ifdef NEGATIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x));\n#endif\n#ifdef POSITIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,1.001));\n#endif\n#ifdef NEGATIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,-1.001));\n#endif\n}";zt.a.ShadersStore.passCubePixelShader=Xt;var Yt=function(e){function t(t,i,n,r,o,s,a,c){return void 0===n&&(n=null),void 0===a&&(a=_.a.TEXTURETYPE_UNSIGNED_INT),void 0===c&&(c=!1),e.call(this,t,"pass",null,null,i,n,r,o,s,void 0,a,void 0,null,c)||this}return l.d(t,e),t}(Wt),Kt=function(e){function t(t,i,n,r,o,s,a,c){void 0===n&&(n=null),void 0===a&&(a=_.a.TEXTURETYPE_UNSIGNED_INT),void 0===c&&(c=!1);var l=e.call(this,t,"passCube",null,null,i,n,r,o,s,"#define POSITIVEX",a,void 0,null,c)||this;return l._face=0,l}return l.d(t,e),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:!0,configurable:!0}),t}(Wt);me.b._RescalePostProcessFactory=function(e){return new Yt("rescale",1,null,me.b.TEXTURE_BILINEAR_SAMPLINGMODE,e,!1,me.b.TEXTURETYPE_UNSIGNED_INT)};var Qt="\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}";zt.a.ShadersStore.anaglyphPixelShader=Qt;var qt=function(e){function t(t,i,n,r,o,s){var a=e.call(this,t,"anaglyph",null,["leftSampler"],i,n[1],r,o,s)||this;return a._passedProcess=n[0]._rigPostProcess,a.onApplyObservable.add(function(e){e.setTextureFromPostProcess("leftSampler",a._passedProcess)}),a}return l.d(t,e),t}(Wt);Ne.a._setStereoscopicAnaglyphRigMode=function(e){e._rigCameras[0]._rigPostProcess=new Yt(e.name+"_passthru",1,e._rigCameras[0]),e._rigCameras[1]._rigPostProcess=new qt(e.name+"_anaglyph",1,e._rigCameras)},F.a.AddNodeConstructor("AnaglyphArcRotateCamera",function(e,t,i){return function(){return new Zt(e,0,0,1,o.x.Zero(),i.interaxial_distance,t)}});var Zt=function(e){function t(t,i,n,r,o,s,a){var c=e.call(this,t,i,n,r,o,a)||this;return c.interaxialDistance=s,c.setCameraRigMode(Ne.a.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:s}),c}return l.d(t,e),t.prototype.getClassName=function(){return"AnaglyphArcRotateCamera"},t}(Et);F.a.AddNodeConstructor("AnaglyphFreeCamera",function(e,t,i){return function(){return new Jt(e,o.x.Zero(),i.interaxial_distance,t)}});var Jt=function(e){function t(t,i,n,r){var o=e.call(this,t,i,r)||this;return o.interaxialDistance=n,o.setCameraRigMode(Ne.a.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:n}),o}return l.d(t,e),t.prototype.getClassName=function(){return"AnaglyphFreeCamera"},t}(bt);F.a.AddNodeConstructor("AnaglyphGamepadCamera",function(e,t,i){return function(){return new $t(e,o.x.Zero(),i.interaxial_distance,t)}});var $t=function(e){function t(t,i,n,r){var o=e.call(this,t,i,r)||this;return o.interaxialDistance=n,o.setCameraRigMode(Ne.a.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:n}),o}return l.d(t,e),t.prototype.getClassName=function(){return"AnaglyphGamepadCamera"},t}(kt);F.a.AddNodeConstructor("AnaglyphUniversalCamera",function(e,t,i){return function(){return new ei(e,o.x.Zero(),i.interaxial_distance,t)}});var ei=function(e){function t(t,i,n,r){var o=e.call(this,t,i,r)||this;return o.interaxialDistance=n,o.setCameraRigMode(Ne.a.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:n}),o}return l.d(t,e),t.prototype.getClassName=function(){return"AnaglyphUniversalCamera"},t}(Vt),ti="const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}";zt.a.ShadersStore.stereoscopicInterlacePixelShader=ti;var ii=function(e){function t(t,i,n,r,s,a){var c=e.call(this,t,"stereoscopicInterlace",["stepSize"],["camASampler"],1,i[1],r,s,a,n?"#define IS_STEREOSCOPIC_HORIZ 1":void 0)||this;return c._passedProcess=i[0]._rigPostProcess,c._stepSize=new o.w(1/c.width,1/c.height),c.onSizeChangedObservable.add(function(){c._stepSize=new o.w(1/c.width,1/c.height)}),c.onApplyObservable.add(function(e){e.setTextureFromPostProcess("camASampler",c._passedProcess),e.setFloat2("stepSize",c._stepSize.x,c._stepSize.y)}),c}return l.d(t,e),t}(Wt);Ne.a._setStereoscopicRigMode=function(e){var t=e.cameraRigMode===Ne.a.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL||e.cameraRigMode===Ne.a.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;e._rigCameras[0]._rigPostProcess=new Yt(e.name+"_passthru",1,e._rigCameras[0]),e._rigCameras[1]._rigPostProcess=new ii(e.name+"_stereoInterlace",e._rigCameras,t)},F.a.AddNodeConstructor("StereoscopicArcRotateCamera",function(e,t,i){return function(){return new ni(e,0,0,1,o.x.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)}});var ni=function(e){function t(t,i,n,r,o,s,a,c){var l=e.call(this,t,i,n,r,o,c)||this;return l.interaxialDistance=s,l.isStereoscopicSideBySide=a,l.setCameraRigMode(a?Ne.a.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:Ne.a.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:s}),l}return l.d(t,e),t.prototype.getClassName=function(){return"StereoscopicArcRotateCamera"},t}(Et);F.a.AddNodeConstructor("StereoscopicFreeCamera",function(e,t,i){return function(){return new ri(e,o.x.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)}});var ri=function(e){function t(t,i,n,r,o){var s=e.call(this,t,i,o)||this;return s.interaxialDistance=n,s.isStereoscopicSideBySide=r,s.setCameraRigMode(r?Ne.a.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:Ne.a.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:n}),s}return l.d(t,e),t.prototype.getClassName=function(){return"StereoscopicFreeCamera"},t}(bt);F.a.AddNodeConstructor("StereoscopicGamepadCamera",function(e,t,i){return function(){return new oi(e,o.x.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)}});var oi=function(e){function t(t,i,n,r,o){var s=e.call(this,t,i,o)||this;return s.interaxialDistance=n,s.isStereoscopicSideBySide=r,s.setCameraRigMode(r?Ne.a.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:Ne.a.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:n}),s}return l.d(t,e),t.prototype.getClassName=function(){return"StereoscopicGamepadCamera"},t}(kt);F.a.AddNodeConstructor("StereoscopicFreeCamera",function(e,t,i){return function(){return new si(e,o.x.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)}});var si=function(e){function t(t,i,n,r,o){var s=e.call(this,t,i,o)||this;return s.interaxialDistance=n,s.isStereoscopicSideBySide=r,s.setCameraRigMode(r?Ne.a.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:Ne.a.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:n}),s}return l.d(t,e),t.prototype.getClassName=function(){return"StereoscopicUniversalCamera"},t}(Vt);F.a.AddNodeConstructor("VirtualJoysticksCamera",function(e,t){return function(){return new ai(e,o.x.Zero(),t)}});var ai=function(e){function t(t,i,n){var r=e.call(this,t,i,n)||this;return r.inputs.addVirtualJoystick(),r}return l.d(t,e),t.prototype.getClassName=function(){return"VirtualJoysticksCamera"},t}(bt),ci=function(){function e(){this.compensateDistortion=!0,this.multiviewEnabled=!1}return Object.defineProperty(e.prototype,"aspectRatio",{get:function(){return this.hResolution/(2*this.vResolution)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"aspectRatioFov",{get:function(){return 2*Math.atan(this.postProcessScaleFactor*this.vScreenSize/(2*this.eyeToScreenDistance))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"leftHMatrix",{get:function(){var e=4*(this.hScreenSize/4-this.lensSeparationDistance/2)/this.hScreenSize;return o.j.Translation(e,0,0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"rightHMatrix",{get:function(){var e=4*(this.hScreenSize/4-this.lensSeparationDistance/2)/this.hScreenSize;return o.j.Translation(-e,0,0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"leftPreViewMatrix",{get:function(){return o.j.Translation(.5*this.interpupillaryDistance,0,0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"rightPreViewMatrix",{get:function(){return o.j.Translation(-.5*this.interpupillaryDistance,0,0)},enumerable:!0,configurable:!0}),e.GetDefault=function(){var t=new e;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},e}(),li="\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn;\nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}";zt.a.ShadersStore.vrDistortionCorrectionPixelShader=li;var ui=function(e){function t(t,i,n,r){var s=e.call(this,t,"vrDistortionCorrection",["LensCenter","Scale","ScaleIn","HmdWarpParam"],null,r.postProcessScaleFactor,i,Ge.a.BILINEAR_SAMPLINGMODE)||this;return s._isRightEye=n,s._distortionFactors=r.distortionK,s._postProcessScaleFactor=r.postProcessScaleFactor,s._lensCenterOffset=r.lensCenterOffset,s.adaptScaleToCurrentViewport=!0,s.onSizeChangedObservable.add(function(){s._scaleIn=new o.w(2,2/s.aspectRatio),s._scaleFactor=new o.w(1/s._postProcessScaleFactor*.5,1/s._postProcessScaleFactor*.5*s.aspectRatio),s._lensCenter=new o.w(s._isRightEye?.5-.5*s._lensCenterOffset:.5+.5*s._lensCenterOffset,.5)}),s.onApplyObservable.add(function(e){e.setFloat2("LensCenter",s._lensCenter.x,s._lensCenter.y),e.setFloat2("Scale",s._scaleFactor.x,s._scaleFactor.y),e.setFloat2("ScaleIn",s._scaleIn.x,s._scaleIn.y),e.setFloat4("HmdWarpParam",s._distortionFactors[0],s._distortionFactors[1],s._distortionFactors[2],s._distortionFactors[3])}),s}return l.d(t,e),t}(Wt),hi="precision mediump sampler2DArray;\nvarying vec2 vUV;\nuniform sampler2DArray multiviewSampler;\nuniform int imageIndex;\nvoid main(void)\n{\ngl_FragColor=texture(multiviewSampler,vec3(vUV,imageIndex));\n}";zt.a.ShadersStore.vrMultiviewToSingleviewPixelShader=hi;var di=i(64),fi=i(83),pi=i(93);me.b.prototype.createRenderTargetCubeTexture=function(e,t){var i=l.a({generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:me.b.TEXTURETYPE_UNSIGNED_INT,samplingMode:me.b.TEXTURE_TRILINEAR_SAMPLINGMODE,format:me.b.TEXTUREFORMAT_RGBA},t);i.generateStencilBuffer=i.generateDepthBuffer&&i.generateStencilBuffer,(i.type!==me.b.TEXTURETYPE_FLOAT||this._caps.textureFloatLinearFiltering)&&(i.type!==me.b.TEXTURETYPE_HALF_FLOAT||this._caps.textureHalfFloatLinearFiltering)||(i.samplingMode=me.b.TEXTURE_NEAREST_SAMPLINGMODE);var n=this._gl,r=new ze.a(this,ze.a.DATASOURCE_RENDERTARGET);this._bindTextureDirectly(n.TEXTURE_CUBE_MAP,r,!0);var o=this._getSamplingParameters(i.samplingMode,i.generateMipMaps);i.type!==me.b.TEXTURETYPE_FLOAT||this._caps.textureFloat||(i.type=me.b.TEXTURETYPE_UNSIGNED_INT,p.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 s=0;s<6;s++)n.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+s,0,this._getRGBABufferInternalSizedFormat(i.type,i.format),e,e,0,this._getInternalFormat(i.format),this._getWebGLTextureType(i.type),null);var a=n.createFramebuffer();return this._bindUnboundFramebuffer(a),r._depthStencilBuffer=this._setupFramebufferDepthAttachments(i.generateStencilBuffer,i.generateDepthBuffer,e,e),i.generateMipMaps&&n.generateMipmap(n.TEXTURE_CUBE_MAP),this._bindTextureDirectly(n.TEXTURE_CUBE_MAP,null),n.bindRenderbuffer(n.RENDERBUFFER,null),this._bindUnboundFramebuffer(null),r._framebuffer=a,r.width=e,r.height=e,r.isReady=!0,r.isCube=!0,r.samples=1,r.generateMipMaps=i.generateMipMaps,r.samplingMode=i.samplingMode,r.type=i.type,r.format=i.format,r._generateDepthBuffer=i.generateDepthBuffer,r._generateStencilBuffer=i.generateStencilBuffer,this._internalTexturesCache.push(r),r};var _i=function(e){function t(t,i,n,s,a,c,l,u,h,d,f,p,m){void 0===a&&(a=!0),void 0===c&&(c=_.a.TEXTURETYPE_UNSIGNED_INT),void 0===l&&(l=!1),void 0===u&&(u=Ge.a.TRILINEAR_SAMPLINGMODE),void 0===h&&(h=!0),void 0===d&&(d=!1),void 0===f&&(f=!1),void 0===p&&(p=_.a.TEXTUREFORMAT_RGBA),void 0===m&&(m=!1);var g=e.call(this,null,n,!s)||this;return g.isCube=l,g.renderParticles=!0,g.renderSprites=!1,g.coordinatesMode=Ge.a.PROJECTION_MODE,g.ignoreCameraViewport=!1,g.onBeforeBindObservable=new r.c,g.onAfterUnbindObservable=new r.c,g.onBeforeRenderObservable=new r.c,g.onAfterRenderObservable=new r.c,g.onClearObservable=new r.c,g._currentRefreshId=-1,g._refreshRate=1,g._samples=1,g.boundingBoxPosition=o.x.Zero(),(n=g.getScene())?(g.renderList=new Array,g._engine=n.getEngine(),g.name=t,g.isRenderTarget=!0,g._initialSizeParameter=i,g._processSizeParameter(i),g._resizeObserver=g.getScene().getEngine().onResizeObservable.add(function(){}),g._generateMipMaps=!!s,g._doNotChangeAspectRatio=a,g._renderingManager=new pi.b(n),g._renderingManager._useSceneAutoClearSetup=!0,f?g:(g._renderTargetOptions={generateMipMaps:s,type:c,format:p,samplingMode:u,generateDepthBuffer:h,generateStencilBuffer:d},u===Ge.a.NEAREST_SAMPLINGMODE&&(g.wrapU=Ge.a.CLAMP_ADDRESSMODE,g.wrapV=Ge.a.CLAMP_ADDRESSMODE),m||(l?(g._texture=n.getEngine().createRenderTargetCubeTexture(g.getRenderSize(),g._renderTargetOptions),g.coordinatesMode=Ge.a.INVCUBIC_MODE,g._textureMatrix=o.j.Identity()):g._texture=n.getEngine().createRenderTargetTexture(g._size,g._renderTargetOptions)),g)):g}return l.d(t,e),Object.defineProperty(t.prototype,"renderList",{get:function(){return this._renderList},set:function(e){this._renderList=e,this._renderList&&this._hookArray(this._renderList)},enumerable:!0,configurable:!0}),t.prototype._hookArray=function(e){var t=this,i=e.push;e.push=function(){for(var n=[],r=0;r0&&(this._postProcesses[0].autoClear=!1))}},t.prototype._shouldRender=function(){return-1===this._currentRefreshId?(this._currentRefreshId=1,!0):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},Object.defineProperty(t.prototype,"canRescale",{get:function(){return!0},enumerable:!0,configurable:!0}),t.prototype.scale=function(e){var t=this.getRenderSize()*e;this.resize(t)},t.prototype.getReflectionTextureMatrix=function(){return this.isCube?this._textureMatrix:e.prototype.getReflectionTextureMatrix.call(this)},t.prototype.resize=function(e){var t=this.isCube;this.releaseInternalTexture();var i=this.getScene();i&&(this._processSizeParameter(e),this._texture=t?i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions):i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions))},t.prototype.render=function(e,t){if(void 0===e&&(e=!1),void 0===t&&(t=!1),a=this.getScene()){var i,n=a.getEngine();if(void 0!==this.useCameraPostProcesses&&(e=this.useCameraPostProcesses),this._waitingRenderList){this.renderList=[];for(var r=0;r=0&&this._renderingManager.dispatchParticles(v))}if(this.isCube)for(var b=0;b<6;b++)this.renderToTarget(b,u,e,t),a.incrementRenderId(),a.resetCachedMaterial();else this.renderToTarget(0,u,e,t);this.onAfterUnbindObservable.notifyObservers(this),a.activeCamera&&((a.getEngine().scenes.length>1||this.activeCamera&&this.activeCamera!==a.activeCamera)&&a.setTransformMatrix(a.activeCamera.getViewMatrix(),a.activeCamera.getProjectionMatrix(!0)),n.setViewport(a.activeCamera.viewport)),a.resetCachedMaterial()}},t.prototype._bestReflectionRenderTargetDimension=function(e,t){var i=e*t,n=ye.h.NearestPOT(i+16384/(128+i));return Math.min(ye.h.FloorPOT(e),n)},t.prototype._bindFrameBuffer=function(e){void 0===e&&(e=0);var t=this.getScene();if(t){var i=t.getEngine();this._texture&&i.bindFramebuffer(this._texture,this.isCube?e:void 0,void 0,void 0,this.ignoreCameraViewport,this.depthStencilTexture?this.depthStencilTexture:void 0)}},t.prototype.unbindFrameBuffer=function(e,t){var i=this;this._texture&&e.unBindFramebuffer(this._texture,this.isCube,function(){i.onAfterRenderObservable.notifyObservers(t)})},t.prototype.renderToTarget=function(e,t,i,n){var r=this.getScene();if(r){var o=r.getEngine();if(this._texture){this._postProcessManager?this._postProcessManager._prepareFrame(this._texture,this._postProcesses):i&&r.postProcessManager._prepareFrame(this._texture)||this._bindFrameBuffer(e),this.onBeforeRenderObservable.notifyObservers(e),this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(o):o.clear(this.clearColor||r.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||r.updateTransformMatrix(!0);for(var s=0,a=r._beforeRenderTargetDrawStage;s=0&&t.customRenderTargets.splice(i,1);for(var n=0,r=t.cameras;n=0&&o.customRenderTargets.splice(i,1)}this.depthStencilTexture&&this.getScene().getEngine()._releaseTexture(this.depthStencilTexture),e.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}(Ge.a);Ge.a._CreateRenderTargetTexture=function(e,t,i,n){return new _i(e,t,i,n)};var mi=function(e){function t(t,i){void 0===i&&(i=512);var n=e.call(this,"multiview rtt",i,t,!1,!0,ze.a.DATASOURCE_UNKNOWN,!1,void 0,!1,!1,!0,void 0,!0)||this,r=t.getEngine().createMultiviewRenderTargetTexture(n.getRenderWidth(),n.getRenderHeight());return r.isMultiview=!0,n._texture=r,n}return l.d(t,e),t.prototype._bindFrameBuffer=function(e){void 0===e&&(e=0),this._texture&&this.getScene().getEngine().bindMultiviewFramebuffer(this._texture)},t.prototype.getViewCount=function(){return 2},t}(_i);me.b.prototype.createMultiviewRenderTargetTexture=function(e,t){var i=this._gl;if(!this.getCaps().multiview)throw"Multiview is not supported";var n=new ze.a(this,ze.a.DATASOURCE_UNKNOWN,!0);return n.width=e,n.height=t,n._framebuffer=i.createFramebuffer(),n._colorTextureArray=i.createTexture(),i.bindTexture(i.TEXTURE_2D_ARRAY,n._colorTextureArray),i.texStorage3D(i.TEXTURE_2D_ARRAY,1,i.RGBA8,e,t,2),n._depthStencilTextureArray=i.createTexture(),i.bindTexture(i.TEXTURE_2D_ARRAY,n._depthStencilTextureArray),i.texStorage3D(i.TEXTURE_2D_ARRAY,1,i.DEPTH32F_STENCIL8,e,t,2),n.isReady=!0,n},me.b.prototype.bindMultiviewFramebuffer=function(e){var t=this._gl,i=this.getCaps().multiview;if(this.bindFramebuffer(e,void 0,void 0,void 0,!0),t.bindFramebuffer(t.DRAW_FRAMEBUFFER,e._framebuffer),!e._colorTextureArray||!e._depthStencilTextureArray)throw"Invalid multiview frame buffer";i.framebufferTextureMultiviewOVR(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,e._colorTextureArray,0,0,2),i.framebufferTextureMultiviewOVR(t.DRAW_FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,e._depthStencilTextureArray,0,0,2)},Ne.a.prototype._useMultiviewToSingleView=!1,Ne.a.prototype._multiviewTexture=null,Ne.a.prototype._resizeOrCreateMultiviewTexture=function(e,t){this._multiviewTexture?this._multiviewTexture.getRenderWidth()==e&&this._multiviewTexture.getRenderHeight()==t||(this._multiviewTexture.dispose(),this._multiviewTexture=new mi(this.getScene(),{width:e,height:t})):this._multiviewTexture=new mi(this.getScene(),{width:e,height:t})},H.a.prototype._transformMatrixR=o.j.Zero(),H.a.prototype._multiviewSceneUbo=null,H.a.prototype._createMultiviewUbo=function(){this._multiviewSceneUbo=new di.a(this.getEngine(),void 0,!0),this._multiviewSceneUbo.addUniform("viewProjection",16),this._multiviewSceneUbo.addUniform("viewProjectionR",16),this._multiviewSceneUbo.addUniform("view",16)},H.a.prototype._updateMultiviewUbo=function(e,t){e&&t&&e.multiplyToRef(t,this._transformMatrixR),e&&t&&(e.multiplyToRef(t,o.t.Matrix[0]),o.i.GetRightPlaneToRef(o.t.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())},H.a.prototype._renderMultiviewToSingleView=function(e){e._resizeOrCreateMultiviewTexture(e._rigPostProcess&&e._rigPostProcess&&e._rigPostProcess.width>0?e._rigPostProcess.width/2:this.getEngine().getRenderWidth(!0)/2,e._rigPostProcess&&e._rigPostProcess&&e._rigPostProcess.height>0?e._rigPostProcess.height:this.getEngine().getRenderHeight(!0)),this._multiviewSceneUbo||this._createMultiviewUbo(),e.outputRenderTarget=e._multiviewTexture,this._renderForCamera(e),e.outputRenderTarget=null;for(var t=0;t=2&&e.onControllersAttachedObservable.notifyObservers(e.controllers)}}})},t}(bt),xi=function(e){function t(t){var i=e.call(this,t)||this;return i.onTriggerStateChangedObservable=new r.c,i.onMainButtonStateChangedObservable=new r.c,i.onSecondaryButtonStateChangedObservable=new r.c,i.onPadStateChangedObservable=new r.c,i.onPadValuesChangedObservable=new r.c,i.pad={x:0,y:0},i._changes={pressChanged:!1,touchChanged:!1,valueChanged:!1,changed:!1},i._buttons=new Array(t.buttons.length),i.hand=t.hand,i}return l.d(t,e),t.prototype.onButtonStateChange=function(e){this._onButtonStateChange=e},Object.defineProperty(t.prototype,"defaultModel",{get:function(){return this._defaultModel},enumerable:!0,configurable:!0}),t.prototype.update=function(){e.prototype.update.call(this);for(var t=0;t\n#include\n#include\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}");zt.a.ShadersStore.imageProcessingPixelShader=Si;var Ci=function(e){function t(t,i,n,r,o,s,a,c){void 0===n&&(n=null),void 0===a&&(a=_.a.TEXTURETYPE_UNSIGNED_INT);var l=e.call(this,t,"imageProcessing",[],[],i,n,r,o,s,null,a,"postprocess",null,!0)||this;return l._fromLinearSpace=!0,l._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},c?(c.applyByPostProcess=!0,l._attachImageProcessingConfiguration(c,!0),l.fromLinearSpace=!1):(l._attachImageProcessingConfiguration(null,!0),l.imageProcessingConfiguration.applyByPostProcess=!0),l.onApply=function(e){l.imageProcessingConfiguration.bind(e,l.aspectRatio)},l}return l.d(t,e),Object.defineProperty(t.prototype,"imageProcessingConfiguration",{get:function(){return this._imageProcessingConfiguration},set:function(e){e.applyByPostProcess=!0,this._attachImageProcessingConfiguration(e)},enumerable:!0,configurable:!0}),t.prototype._attachImageProcessingConfiguration=function(e,t){var i=this;if(void 0===t&&(t=!1),e!==this._imageProcessingConfiguration){if(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e)this._imageProcessingConfiguration=e;else{var n=null,r=this.getEngine(),o=this.getCamera();if(o)n=o.getScene();else if(r&&r.scenes){var s=r.scenes;n=s[s.length-1]}else n=R.a.LastCreatedScene;this._imageProcessingConfiguration=n.imageProcessingConfiguration}this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(function(){i._updateParameters()})),t||this._updateParameters()}},Object.defineProperty(t.prototype,"colorCurves",{get:function(){return this.imageProcessingConfiguration.colorCurves},set:function(e){this.imageProcessingConfiguration.colorCurves=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"colorCurvesEnabled",{get:function(){return this.imageProcessingConfiguration.colorCurvesEnabled},set:function(e){this.imageProcessingConfiguration.colorCurvesEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"colorGradingTexture",{get:function(){return this.imageProcessingConfiguration.colorGradingTexture},set:function(e){this.imageProcessingConfiguration.colorGradingTexture=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"colorGradingEnabled",{get:function(){return this.imageProcessingConfiguration.colorGradingEnabled},set:function(e){this.imageProcessingConfiguration.colorGradingEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"exposure",{get:function(){return this.imageProcessingConfiguration.exposure},set:function(e){this.imageProcessingConfiguration.exposure=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"toneMappingEnabled",{get:function(){return this._imageProcessingConfiguration.toneMappingEnabled},set:function(e){this._imageProcessingConfiguration.toneMappingEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"toneMappingType",{get:function(){return this._imageProcessingConfiguration.toneMappingType},set:function(e){this._imageProcessingConfiguration.toneMappingType=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"contrast",{get:function(){return this.imageProcessingConfiguration.contrast},set:function(e){this.imageProcessingConfiguration.contrast=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"vignetteStretch",{get:function(){return this.imageProcessingConfiguration.vignetteStretch},set:function(e){this.imageProcessingConfiguration.vignetteStretch=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"vignetteCentreX",{get:function(){return this.imageProcessingConfiguration.vignetteCentreX},set:function(e){this.imageProcessingConfiguration.vignetteCentreX=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"vignetteCentreY",{get:function(){return this.imageProcessingConfiguration.vignetteCentreY},set:function(e){this.imageProcessingConfiguration.vignetteCentreY=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"vignetteWeight",{get:function(){return this.imageProcessingConfiguration.vignetteWeight},set:function(e){this.imageProcessingConfiguration.vignetteWeight=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"vignetteColor",{get:function(){return this.imageProcessingConfiguration.vignetteColor},set:function(e){this.imageProcessingConfiguration.vignetteColor=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"vignetteCameraFov",{get:function(){return this.imageProcessingConfiguration.vignetteCameraFov},set:function(e){this.imageProcessingConfiguration.vignetteCameraFov=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"vignetteBlendMode",{get:function(){return this.imageProcessingConfiguration.vignetteBlendMode},set:function(e){this.imageProcessingConfiguration.vignetteBlendMode=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"vignetteEnabled",{get:function(){return this.imageProcessingConfiguration.vignetteEnabled},set:function(e){this.imageProcessingConfiguration.vignetteEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fromLinearSpace",{get:function(){return this._fromLinearSpace},set:function(e){this._fromLinearSpace!==e&&(this._fromLinearSpace=e,this._updateParameters())},enumerable:!0,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 t in this._defines)this._defines[t]&&(e+="#define "+t+";\r\n");var i=["textureSampler"],n=["scale"];Ai.a&&(Ai.a.PrepareSamplers(i,this._defines),Ai.a.PrepareUniforms(n,this._defines)),this.updateEffect(e,n,i)},t.prototype.dispose=function(t){e.prototype.dispose.call(this,t),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration&&(this.imageProcessingConfiguration.applyByPostProcess=!1)},l.c([Object(L.c)()],t.prototype,"_fromLinearSpace",void 0),t}(Wt),Mi=i(12),Oi=i(4);fe.a._GroundMeshParser=function(e,t){return Ii.Parse(e,t)};var Ii=function(e){function t(t,i){var n=e.call(this,t,i)||this;return n.generateOctree=!1,n}return l.d(t,e),t.prototype.getClassName=function(){return"GroundMesh"},Object.defineProperty(t.prototype,"subdivisions",{get:function(){return Math.min(this._subdivisionsX,this._subdivisionsY)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"subdivisionsX",{get:function(){return this._subdivisionsX},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"subdivisionsY",{get:function(){return this._subdivisionsY},enumerable:!0,configurable:!0}),t.prototype.optimize=function(e,t){void 0===t&&(t=32),this._subdivisionsX=e,this._subdivisionsY=e,this.subdivide(e);this.createOrUpdateSubmeshesOctree&&this.createOrUpdateSubmeshesOctree(t)},t.prototype.getHeightAtCoordinates=function(e,t){var i=this.getWorldMatrix(),n=o.t.Matrix[5];i.invertToRef(n);var r=o.t.Vector3[8];if(o.x.TransformCoordinatesFromFloatsToRef(e,0,t,n,r),e=r.x,t=r.z,ethis._maxX||tthis._maxZ)return this.position.y;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());var s=this._getFacetAt(e,t),a=-(s.x*e+s.z*t+s.w)/s.y;return o.x.TransformCoordinatesFromFloatsToRef(0,a,0,i,r),r.y},t.prototype.getNormalAtCoordinates=function(e,t){var i=new o.x(0,1,0);return this.getNormalAtCoordinatesToRef(e,t,i),i},t.prototype.getNormalAtCoordinatesToRef=function(e,t,i){var n=this.getWorldMatrix(),r=o.t.Matrix[5];n.invertToRef(r);var s=o.t.Vector3[8];if(o.x.TransformCoordinatesFromFloatsToRef(e,0,t,r,s),e=s.x,t=s.z,ethis._maxX||tthis._maxZ)return this;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());var a=this._getFacetAt(e,t);return o.x.TransformNormalFromFloatsToRef(a.x,a.y,a.z,n,i),this},t.prototype.updateCoordinateHeights=function(){return this._heightQuads&&0!=this._heightQuads.length||this._initHeightQuads(),this._computeHeightQuads(),this},t.prototype._getFacetAt=function(e,t){var i=Math.floor((e+this._maxX)*this._subdivisionsX/this._width),n=Math.floor(-(t+this._maxZ)*this._subdivisionsY/this._height+this._subdivisionsY),r=this._heightQuads[n*this._subdivisionsX+i];return te.maxHeight){u=!0;var h=e.maxHeight;e.maxHeight=e.minHeight,e.minHeight=h}for(t=0;t<=e.subdivisions;t++)for(i=0;i<=e.subdivisions;i++){var d=new o.x(i*e.width/e.subdivisions-e.width/2,0,(e.subdivisions-t)*e.height/e.subdivisions-e.height/2),f=4*(((d.x+e.width/2)/e.width*(e.bufferWidth-1)|0)+((1-(d.z+e.height/2)/e.height)*(e.bufferHeight-1)|0)*e.bufferWidth),p=e.buffer[f]/255,_=e.buffer[f+1]/255,m=e.buffer[f+2]/255,g=e.buffer[f+3]/255;u&&(p=1-p,_=1-_,m=1-m);var v=p*c.r+_*c.g+m*c.b;d.y=g>=l?e.minHeight+(e.maxHeight-e.minHeight)*v:e.minHeight-o.h,r.push(d.x,d.y,d.z),s.push(0,0,0),a.push(i/e.subdivisions,1-t/e.subdivisions)}for(t=0;t=e.minHeight,A=r[3*b+1]>=e.minHeight,P=r[3*T+1]>=e.minHeight;x&&A&&P&&(n.push(y),n.push(b),n.push(T)),r[3*E+1]>=e.minHeight&&x&&P&&(n.push(E),n.push(y),n.push(T))}Mi.a.ComputeNormals(r,n,s);var R=new Mi.a;return R.indices=n,R.positions=r,R.normals=s,R.uvs=a,R},fe.a.CreateGround=function(e,t,i,n,r,o){var s={width:t,height:i,subdivisions:n,updatable:o};return Di.CreateGround(e,s,r)},fe.a.CreateTiledGround=function(e,t,i,n,r,o,s,a,c){var l={xmin:t,zmin:i,xmax:n,zmax:r,subdivisions:o,precision:s,updatable:c};return Di.CreateTiledGround(e,l,a)},fe.a.CreateGroundFromHeightMap=function(e,t,i,n,r,o,s,a,c,l,u){var h={width:i,height:n,subdivisions:r,minHeight:o,maxHeight:s,updatable:c,onReady:l,alphaFilter:u};return Di.CreateGroundFromHeightMap(e,t,h,a)};var Di=function(){function e(){}return e.CreateGround=function(e,t,i){var n=new Ii(e,i);return n._setReady(!1),n._subdivisionsX=t.subdivisionsX||t.subdivisions||1,n._subdivisionsY=t.subdivisionsY||t.subdivisions||1,n._width=t.width||1,n._height=t.height||1,n._maxX=n._width/2,n._maxZ=n._height/2,n._minX=-n._maxX,n._minZ=-n._maxZ,Mi.a.CreateGround(t).applyToMesh(n,t.updatable),n._setReady(!0),n},e.CreateTiledGround=function(e,t,i){void 0===i&&(i=null);var n=new fe.a(e,i);return Mi.a.CreateTiledGround(t).applyToMesh(n,t.updatable),n},e.CreateGroundFromHeightMap=function(e,t,i,n){void 0===n&&(n=null);var r=i.width||10,s=i.height||10,a=i.subdivisions||1,c=i.minHeight||0,l=i.maxHeight||1,u=i.colorFilter||new o.e(.3,.59,.11),h=i.alphaFilter||0,d=i.updatable,f=i.onReady;n=n||R.a.LastCreatedScene;var p=new Ii(e,n);p._subdivisionsX=a,p._subdivisionsY=a,p._width=r,p._height=s,p._maxX=p._width/2,p._maxZ=p._height/2,p._minX=-p._maxX,p._minZ=-p._maxZ,p._setReady(!1);return ye.h.LoadImage(t,function(e){var t=document.createElement("canvas"),i=t.getContext("2d");if(!i)throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");if(!n.isDisposed){var o=e.width,_=e.height;t.width=o,t.height=_,i.drawImage(e,0,0);var m=i.getImageData(0,0,o,_).data;Mi.a.CreateGroundFromHeightMap({width:r,height:s,subdivisions:a,minHeight:c,maxHeight:l,colorFilter:u,buffer:m,bufferWidth:o,bufferHeight:_,alphaFilter:h}).applyToMesh(p,d),f&&f(p),p._setReady(!0)}},function(){},n.offlineProvider),p},e}();Mi.a.CreateTorus=function(e){for(var t=[],i=[],n=[],r=[],s=e.diameter||1,a=e.thickness||.5,c=e.tessellation||16,l=0===e.sideOrientation?0:e.sideOrientation||Mi.a.DEFAULTSIDE,u=c+1,h=0;h<=c;h++)for(var d=h/c,f=h*Math.PI*2/c-Math.PI/2,p=o.j.Translation(s/2,0,0).multiply(o.j.RotationY(f)),_=0;_<=c;_++){var m=1-_/c,g=_*Math.PI*2/c+Math.PI,v=Math.cos(g),y=Math.sin(g),b=new o.x(v,y,0),T=b.scale(a/2),E=new o.w(d,m);T=o.x.TransformCoordinates(T,p),b=o.x.TransformNormal(b,p),i.push(T.x,T.y,T.z),n.push(b.x,b.y,b.z),r.push(E.x,E.y);var x=(h+1)%u,A=(_+1)%u;t.push(h*u+_),t.push(h*u+A),t.push(x*u+_),t.push(h*u+A),t.push(x*u+A),t.push(x*u+_)}Mi.a._ComputeSides(l,i,t,n,r,e.frontUVs,e.backUVs);var P=new Mi.a;return P.indices=t,P.positions=i,P.normals=n,P.uvs=r,P},fe.a.CreateTorus=function(e,t,i,n,r,o,s){var a={diameter:t,thickness:i,tessellation:n,sideOrientation:s,updatable:o};return wi.CreateTorus(e,a,r)};var Li,wi=function(){function e(){}return e.CreateTorus=function(e,t,i){var n=new fe.a(e,i);return t.sideOrientation=fe.a._GetDefaultSideOrientation(t.sideOrientation),n._originalBuilderSideOrientation=t.sideOrientation,Mi.a.CreateTorus(t).applyToMesh(n,t.updatable),n},e}(),Fi=i(54),Ni=function(){function e(t,i){if(void 0===i&&(i=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=e._idCounter++,i)this._gazeTracker=i.clone("gazeTracker");else{this._gazeTracker=fe.a.CreateTorus("gazeTracker",.0035,.0025,20,t,!1),this._gazeTracker.bakeCurrentTransformIntoVertices(),this._gazeTracker.isPickable=!1,this._gazeTracker.isVisible=!1;var n=new Pi.a("targetMat",t);n.specularColor=o.e.Black(),n.emissiveColor=new o.e(.7,.7,.7),n.backFaceCulling=!1,this._gazeTracker.material=n}}return e.prototype._getForwardRay=function(e){return new It.a(o.x.Zero(),new o.x(0,0,e))},e.prototype._selectionPointerDown=function(){this._pointerDownOnMeshAsked=!0,this._currentHit&&this.scene.simulatePointerDown(this._currentHit,{pointerId:this._id})},e.prototype._selectionPointerUp=function(){this._currentHit&&this.scene.simulatePointerUp(this._currentHit,{pointerId:this._id}),this._pointerDownOnMeshAsked=!1},e.prototype._activatePointer=function(){this._activePointer=!0},e.prototype._deactivatePointer=function(){this._activePointer=!1},e.prototype._updatePointerDistance=function(e){void 0===e&&(e=100)},e.prototype.dispose=function(){this._interactionsEnabled=!1,this._teleportationEnabled=!1,this._gazeTracker&&this._gazeTracker.dispose()},e._idCounter=0,e}(),Bi=function(e){function t(t,i,n){var r=e.call(this,i,n)||this;r.webVRController=t,r._laserPointer=fe.a.CreateCylinder("laserPointer",1,.004,2e-4,20,1,i,!1);var s=new Pi.a("laserPointerMat",i);if(s.emissiveColor=new o.e(.7,.7,.7),s.alpha=.6,r._laserPointer.material=s,r._laserPointer.rotation.x=Math.PI/2,r._laserPointer.position.z=-.5,r._laserPointer.isVisible=!1,r._laserPointer.isPickable=!1,!t.mesh){var a=new fe.a("preloadControllerMesh",i),c=new fe.a(Ft.POINTING_POSE,i);c.rotation.x=-.7,a.addChild(c),t.attachToMesh(a)}return r._setLaserPointerParent(t.mesh),r._meshAttachedObserver=t._meshAttachedObservable.add(function(e){r._setLaserPointerParent(e)}),r}return l.d(t,e),t.prototype._getForwardRay=function(e){return this.webVRController.getForwardRay(e)},t.prototype._activatePointer=function(){e.prototype._activatePointer.call(this),this._laserPointer.isVisible=!0},t.prototype._deactivatePointer=function(){e.prototype._deactivatePointer.call(this),this._laserPointer.isVisible=!1},t.prototype._setLaserPointerColor=function(e){this._laserPointer.material.emissiveColor=e},t.prototype._setLaserPointerParent=function(e){var t=function(e){e.isPickable=!1,e.getChildMeshes().forEach(function(e){t(e)})};t(e);var i=e.getChildren(void 0,!1),n=e;this.webVRController._pointingPoseNode=null;for(var r=0;r=0){n=i[r],this.webVRController._pointingPoseNode=n;break}this._laserPointer.parent=n},t.prototype._updatePointerDistance=function(e){void 0===e&&(e=100),this._laserPointer.scaling.y=e,this._laserPointer.position.z=-e/2},t.prototype.dispose=function(){e.prototype.dispose.call(this),this._laserPointer.dispose(),this._meshAttachedObserver&&this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver)},t}(Ni),Ui=function(e){function t(t,i){var n=e.call(this,i)||this;return n.getCamera=t,n}return l.d(t,e),t.prototype._getForwardRay=function(e){var t=this.getCamera();return t?t.getForwardRay(e):new It.a(o.x.Zero(),o.x.Forward())},t}(Ni),Vi=function(){return function(){}}(),ki=function(){function e(e,t){var i=this;if(void 0===t&&(t={}),this.webVROptions=t,this._webVRsupported=!1,this._webVRready=!1,this._webVRrequesting=!1,this._webVRpresenting=!1,this._fullscreenVRpresenting=!1,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._rotationAllowed=!0,this._teleportBackwardsVector=new o.x(0,-1,-1),this._isDefaultTeleportationTarget=!0,this._teleportationFillColor="#444444",this._teleportationBorderColor="#FFFFFF",this._rotationAngle=0,this._haloCenter=new o.x(0,0,0),this._padSensibilityUp=.65,this._padSensibilityDown=.35,this._leftController=null,this._rightController=null,this.onNewMeshSelected=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.requestPointerLockOnFullScreen=!0,this._onResize=function(){i.moveButtonToBottomRight(),i._fullscreenVRpresenting&&i._webVRready&&i.exitVR()},this._onFullscreenChange=function(){var e=document;void 0!==e.fullscreen?i._fullscreenVRpresenting=document.fullscreen:void 0!==e.mozFullScreen?i._fullscreenVRpresenting=e.mozFullScreen:void 0!==e.webkitIsFullScreen?i._fullscreenVRpresenting=e.webkitIsFullScreen:void 0!==e.msIsFullScreen?i._fullscreenVRpresenting=e.msIsFullScreen:void 0!==document.msFullscreenElement&&(i._fullscreenVRpresenting=document.msFullscreenElement),!i._fullscreenVRpresenting&&i._canvas&&(i.exitVR(),i._useCustomVRButton||(i._btnVR.style.top=i._canvas.offsetTop+i._canvas.offsetHeight-70+"px",i._btnVR.style.left=i._canvas.offsetLeft+i._canvas.offsetWidth-100+"px"))},this._cachedAngularSensibility={angularSensibilityX:null,angularSensibilityY:null,angularSensibility:null},this.beforeRender=function(){i._leftController&&i._leftController._activePointer&&i._castRayAndSelectObject(i._leftController),i._rightController&&i._rightController._activePointer&&i._castRayAndSelectObject(i._rightController),i._noControllerIsActive?i._castRayAndSelectObject(i._cameraGazer):i._cameraGazer._gazeTracker.isVisible=!1},this._onNewGamepadConnected=function(e){if(e.type!==Ke.POSE_ENABLED)e.leftStick&&e.onleftstickchanged(function(e){i._teleportationInitialized&&i.teleportationEnabled&&(!i._leftController&&!i._rightController||i._leftController&&!i._leftController._activePointer&&i._rightController&&!i._rightController._activePointer)&&(i._checkTeleportWithRay(e,i._cameraGazer),i._checkTeleportBackwards(e,i._cameraGazer))}),e.rightStick&&e.onrightstickchanged(function(e){i._teleportationInitialized&&i._checkRotate(e,i._cameraGazer)}),e.type===Ke.XBOX&&(e.onbuttondown(function(e){i._interactionsEnabled&&e===Dt.A&&i._cameraGazer._selectionPointerDown()}),e.onbuttonup(function(e){i._interactionsEnabled&&e===Dt.A&&i._cameraGazer._selectionPointerUp()}));else{var t=e,n=new Bi(t,i._scene,i._cameraGazer._gazeTracker);"right"===t.hand||i._leftController&&i._leftController.webVRController!=t?i._rightController=n:i._leftController=n,i._tryEnableInteractionOnController(n)}},this._tryEnableInteractionOnController=function(e){i._interactionsRequested&&!e._interactionsEnabled&&i._enableInteractionOnController(e),i._teleportationRequested&&!e._teleportationEnabled&&i._enableTeleportationOnController(e)},this._onNewGamepadDisconnected=function(e){e instanceof xi&&("left"===e.hand&&null!=i._leftController&&(i._leftController.dispose(),i._leftController=null),"right"===e.hand&&null!=i._rightController&&(i._rightController.dispose(),i._rightController=null))},this._workingVector=o.x.Zero(),this._workingQuaternion=o.q.Identity(),this._workingMatrix=o.j.Identity(),this._scene=e,this._canvas=e.getEngine().getRenderingCanvas(),void 0===t.createFallbackVRDeviceOrientationFreeCamera&&(t.createFallbackVRDeviceOrientationFreeCamera=!0),void 0===t.createDeviceOrientationCamera&&(t.createDeviceOrientationCamera=!0),void 0===t.laserToggle&&(t.laserToggle=!0),void 0===t.defaultHeight&&(t.defaultHeight=1.7),t.useCustomVRButton&&(this._useCustomVRButton=!0,t.customVRButton&&(this._btnVR=t.customVRButton)),t.rayLength&&(this._rayLength=t.rayLength),this._defaultHeight=t.defaultHeight,t.positionScale&&(this._rayLength*=t.positionScale,this._defaultHeight*=t.positionScale),this._hasEnteredVR=!1,this._scene.activeCamera?this._position=this._scene.activeCamera.position.clone():this._position=new o.x(0,this._defaultHeight,0),t.createDeviceOrientationCamera||!this._scene.activeCamera){if(this._deviceOrientationCamera=new xt("deviceOrientationVRHelper",this._position.clone(),e),this._scene.activeCamera&&(this._deviceOrientationCamera.minZ=this._scene.activeCamera.minZ,this._deviceOrientationCamera.maxZ=this._scene.activeCamera.maxZ,this._scene.activeCamera instanceof yt&&this._scene.activeCamera.rotation)){var n=this._scene.activeCamera;n.rotationQuaternion?this._deviceOrientationCamera.rotationQuaternion.copyFrom(n.rotationQuaternion):this._deviceOrientationCamera.rotationQuaternion.copyFrom(o.q.RotationYawPitchRoll(n.rotation.y,n.rotation.x,n.rotation.z)),this._deviceOrientationCamera.rotation=n.rotation.clone()}this._scene.activeCamera=this._deviceOrientationCamera,this._canvas&&this._scene.activeCamera.attachControl(this._canvas)}else this._existingCamera=this._scene.activeCamera;if(t.createFallbackVRDeviceOrientationFreeCamera&&(t.useMultiview&&(t.vrDeviceOrientationCameraMetrics||(t.vrDeviceOrientationCameraMetrics=ci.GetDefault()),t.vrDeviceOrientationCameraMetrics.multiviewEnabled=!0),this._vrDeviceOrientationCamera=new yi("VRDeviceOrientationVRHelper",this._position,this._scene,!0,t.vrDeviceOrientationCameraMetrics),this._vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._webVRCamera=new Ei("WebVRHelper",this._position,this._scene,t),this._webVRCamera.useStandingMatrix(),this._cameraGazer=new Ui(function(){return i.currentVRCamera},e),!this._useCustomVRButton){this._btnVR=document.createElement("BUTTON"),this._btnVR.className="babylonVRicon",this._btnVR.id="babylonVRiconbtn",this._btnVR.title="Click to switch to VR";".babylonVRicon.vrdisplaypresenting { display: none; }";var s=document.createElement("style");s.appendChild(document.createTextNode(".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url(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) }.babylonVRicon.vrdisplaypresenting { display: none; }")),document.getElementsByTagName("head")[0].appendChild(s),this.moveButtonToBottomRight()}this._btnVR&&this._btnVR.addEventListener("click",function(){i.isInVRMode?i.exitVR():i.enterVR()}),window.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,t.createFallbackVRDeviceOrientationFreeCamera?this.displayVRButton():this._scene.getEngine().onVRDisplayChangedObservable.add(function(e){e.vrDisplay&&i.displayVRButton()}),this._onKeyDown=function(e){27===e.keyCode&&i.isInVRMode&&i.exitVR()},document.addEventListener("keydown",this._onKeyDown),this._scene.onPrePointerObservable.add(function(){i.isInVRMode&&(i.exitVR(),i._fullscreenVRpresenting&&i._scene.getEngine().exitFullscreen())},Re.a.POINTERDOUBLETAP,!1),this._onVRDisplayChanged=function(e){return i.onVRDisplayChanged(e)},this._onVrDisplayPresentChange=function(){return i.onVrDisplayPresentChange()},this._onVRRequestPresentStart=function(){i._webVRrequesting=!0,i.updateButtonVisibility()},this._onVRRequestPresentComplete=function(){i._webVRrequesting=!1,i.updateButtonVisibility()},e.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged),e.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart),e.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete),window.addEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChange),e.onDisposeObservable.add(function(){i.dispose()}),this._webVRCamera.onControllerMeshLoadedObservable.add(function(e){return i._onDefaultMeshLoaded(e)}),this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected),this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected),this.updateButtonVisibility(),this._circleEase=new ee,this._circleEase.setEasingMode($.EASINGMODE_EASEINOUT),e.onPointerObservable.add(function(t){i._interactionsEnabled&&e.activeCamera===i.vrDeviceOrientationCamera&&"mouse"===t.event.pointerType&&(t.type===Re.a.POINTERDOWN?i._cameraGazer._selectionPointerDown():t.type===Re.a.POINTERUP&&i._cameraGazer._selectionPointerUp())}),this.webVROptions.floorMeshes&&this.enableTeleportation({floorMeshes:this.webVROptions.floorMeshes})}return Object.defineProperty(e.prototype,"onEnteringVR",{get:function(){return this.onEnteringVRObservable},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onExitingVR",{get:function(){return this.onExitingVRObservable},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onControllerMeshLoaded",{get:function(){return this.onControllerMeshLoadedObservable},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"teleportationTarget",{get:function(){return this._teleportationTarget},set:function(e){e&&(e.name="teleportationTarget",this._isDefaultTeleportationTarget=!1,this._teleportationTarget=e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"gazeTrackerMesh",{get:function(){return this._cameraGazer._gazeTracker},set:function(e){e&&(this._cameraGazer._gazeTracker&&this._cameraGazer._gazeTracker.dispose(),this._leftController&&this._leftController._gazeTracker&&this._leftController._gazeTracker.dispose(),this._rightController&&this._rightController._gazeTracker&&this._rightController._gazeTracker.dispose(),this._cameraGazer._gazeTracker=e,this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices(),this._cameraGazer._gazeTracker.isPickable=!1,this._cameraGazer._gazeTracker.isVisible=!1,this._cameraGazer._gazeTracker.name="gazeTracker",this._leftController&&(this._leftController._gazeTracker=this._cameraGazer._gazeTracker.clone("gazeTracker")),this._rightController&&(this._rightController._gazeTracker=this._cameraGazer._gazeTracker.clone("gazeTracker")))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"leftControllerGazeTrackerMesh",{get:function(){return this._leftController?this._leftController._gazeTracker:null},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"rightControllerGazeTrackerMesh",{get:function(){return this._rightController?this._rightController._gazeTracker:null},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"displayGaze",{get:function(){return this._displayGaze},set:function(e){this._displayGaze=e,e||(this._cameraGazer._gazeTracker.isVisible=!1,this._leftController&&(this._leftController._gazeTracker.isVisible=!1),this._rightController&&(this._rightController._gazeTracker.isVisible=!1))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"displayLaserPointer",{get:function(){return this._displayLaserPointer},set:function(e){this._displayLaserPointer=e,e?(this._rightController&&this._rightController._activatePointer(),this._leftController&&this._leftController._activatePointer()):(this._rightController&&(this._rightController._deactivatePointer(),this._rightController._gazeTracker.isVisible=!1),this._leftController&&(this._leftController._deactivatePointer(),this._leftController._gazeTracker.isVisible=!1))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"deviceOrientationCamera",{get:function(){return this._deviceOrientationCamera},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"currentVRCamera",{get:function(){return this._webVRready?this._webVRCamera:this._scene.activeCamera},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"webVRCamera",{get:function(){return this._webVRCamera},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"vrDeviceOrientationCamera",{get:function(){return this._vrDeviceOrientationCamera},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"_teleportationRequestInitiated",{get:function(){return this._cameraGazer._teleportationRequestInitiated||null!==this._leftController&&this._leftController._teleportationRequestInitiated||null!==this._rightController&&this._rightController._teleportationRequestInitiated},enumerable:!0,configurable:!0}),e.prototype._onDefaultMeshLoaded=function(e){this._leftController&&this._leftController.webVRController==e&&e.mesh&&this._leftController._setLaserPointerParent(e.mesh),this._rightController&&this._rightController.webVRController==e&&e.mesh&&this._rightController._setLaserPointerParent(e.mesh);try{this.onControllerMeshLoadedObservable.notifyObservers(e)}catch(e){p.a.Warn("Error in your custom logic onControllerMeshLoaded: "+e)}},Object.defineProperty(e.prototype,"isInVRMode",{get:function(){return this._webVRpresenting||this._fullscreenVRpresenting},enumerable:!0,configurable:!0}),e.prototype.onVrDisplayPresentChange=function(){var e=this._scene.getEngine().getVRDevice();if(e){var t=this._webVRpresenting;this._webVRpresenting=e.isPresenting,t&&!this._webVRpresenting&&this.exitVR()}else p.a.Warn("Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?");this.updateButtonVisibility()},e.prototype.onVRDisplayChanged=function(e){this._webVRsupported=e.vrSupported,this._webVRready=!!e.vrDisplay,this._webVRpresenting=e.vrDisplay&&e.vrDisplay.isPresenting,this.updateButtonVisibility()},e.prototype.moveButtonToBottomRight=function(){this._canvas&&!this._useCustomVRButton&&(this._btnVR.style.top=this._canvas.offsetTop+this._canvas.offsetHeight-70+"px",this._btnVR.style.left=this._canvas.offsetLeft+this._canvas.offsetWidth-100+"px")},e.prototype.displayVRButton=function(){this._useCustomVRButton||this._btnVRDisplayed||(document.body.appendChild(this._btnVR),this._btnVRDisplayed=!0)},e.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")))},e.prototype.enterVR=function(){var e=this;if(this.onEnteringVRObservable)try{this.onEnteringVRObservable.notifyObservers(this)}catch(e){p.a.Warn("Error in your custom logic onEnteringVR: "+e)}if(this._scene.activeCamera){if(this._position=this._scene.activeCamera.position.clone(),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.rotation=o.q.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles(),this.vrDeviceOrientationCamera.angularSensibility=2e3),this.webVRCamera){var t=this.webVRCamera.deviceRotationQuaternion.toEulerAngles().y,i=o.q.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles().y-t,n=this.webVRCamera.rotationQuaternion.toEulerAngles().y;this.webVRCamera.rotationQuaternion=o.q.FromEulerAngles(0,n+i,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(t){e.onAfterEnteringVRObservable.notifyObservers({success:t})}),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(){e.onAfterEnteringVRObservable.notifyObservers({success:!0})})),this._scene.activeCamera&&this._canvas&&this._scene.activeCamera.attachControl(this._canvas),this._interactionsEnabled&&this._scene.registerBeforeRender(this.beforeRender),this._displayLaserPointer&&[this._leftController,this._rightController].forEach(function(e){e&&e._activatePointer()}),this._hasEnteredVR=!0)},e.prototype.exitVR=function(){if(this._hasEnteredVR){if(this.onExitingVRObservable)try{this.onExitingVRObservable.notifyObservers(this)}catch(e){p.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._canvas&&this._scene.activeCamera.attachControl(this._canvas),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._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 e=this._scene.getEngine();e._onVrDisplayPresentChange&&e._onVrDisplayPresentChange()}},Object.defineProperty(e.prototype,"position",{get:function(){return this._position},set:function(e){this._position=e,this._scene.activeCamera&&(this._scene.activeCamera.position=e)},enumerable:!0,configurable:!0}),e.prototype.enableInteractions=function(){var e=this;this._interactionsEnabled||(this._interactionsRequested=!0,this._leftController&&this._enableInteractionOnController(this._leftController),this._rightController&&this._enableInteractionOnController(this._rightController),this.raySelectionPredicate=function(t){return t.isVisible&&(t.isPickable||t.name===e._floorMeshName)},this.meshSelectionPredicate=function(){return!0},this._raySelectionPredicate=function(t){return!!(e._isTeleportationFloor(t)||-1===t.name.indexOf("gazeTracker")&&-1===t.name.indexOf("teleportationTarget")&&-1===t.name.indexOf("torusTeleportation"))&&e.raySelectionPredicate(t)},this._interactionsEnabled=!0)},Object.defineProperty(e.prototype,"_noControllerIsActive",{get:function(){return!(this._leftController&&this._leftController._activePointer||this._rightController&&this._rightController._activePointer)},enumerable:!0,configurable:!0}),e.prototype._isTeleportationFloor=function(e){for(var t=0;t-1||this._floorMeshesCollection.push(e))},e.prototype.removeFloorMesh=function(e){if(this._floorMeshesCollection){var t=this._floorMeshesCollection.indexOf(e);-1!==t&&this._floorMeshesCollection.splice(t,1)}},e.prototype.enableTeleportation=function(e){if(void 0===e&&(e={}),!this._teleportationInitialized){this._teleportationRequested=!0,this.enableInteractions(),e.floorMeshName&&(this._floorMeshName=e.floorMeshName),e.floorMeshes&&(this._floorMeshesCollection=e.floorMeshes),null!=this._leftController&&this._enableTeleportationOnController(this._leftController),null!=this._rightController&&this._enableTeleportationOnController(this._rightController);var t=new Ai.a;t.vignetteColor=new o.f(0,0,0,0),t.vignetteEnabled=!0,this._postProcessMove=new Ci("postProcessMove",1,this._webVRCamera,void 0,void 0,void 0,void 0,t),this._webVRCamera.detachPostProcess(this._postProcessMove),this._teleportationInitialized=!0,this._isDefaultTeleportationTarget&&(this._createTeleportationCircles(),this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor))}},e.prototype._enableInteractionOnController=function(e){var t=this;e.webVRController.mesh&&(e._interactionsEnabled=!0,this.isInVRMode&&this._displayLaserPointer&&e._activatePointer(),this.webVROptions.laserToggle&&e.webVRController.onMainButtonStateChangedObservable.add(function(i){t._displayLaserPointer&&1===i.value&&(e._activePointer?e._deactivatePointer():e._activatePointer(),t.displayGaze&&(e._gazeTracker.isVisible=e._activePointer))}),e.webVRController.onTriggerStateChangedObservable.add(function(i){var n=e;t._noControllerIsActive&&(n=t._cameraGazer),n._pointerDownOnMeshAsked?i.valuet._padSensibilityUp&&n._selectionPointerDown()}))},e.prototype._checkTeleportWithRay=function(e,t){this._teleportationRequestInitiated&&!t._teleportationRequestInitiated||(t._teleportationRequestInitiated?Math.sqrt(e.y*e.y+e.x*e.x)-this._padSensibilityDown&&(t._rotationLeftAsked=!1):e.x<-this._padSensibilityUp&&t._dpadPressed&&(t._rotationLeftAsked=!0,this._rotationAllowed&&this._rotateCamera(!1)),t._rotationRightAsked?e.xthis._padSensibilityUp&&t._dpadPressed&&(t._rotationRightAsked=!0,this._rotationAllowed&&this._rotateCamera(!0)))},e.prototype._checkTeleportBackwards=function(e,t){if(!t._teleportationRequestInitiated)if(e.y>this._padSensibilityUp&&t._dpadPressed){if(!t._teleportationBackRequestInitiated){if(!this.currentVRCamera)return;var i=o.q.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix()),n=this.currentVRCamera.position;this.currentVRCamera.devicePosition&&this.currentVRCamera.deviceRotationQuaternion&&(i=this.currentVRCamera.deviceRotationQuaternion,n=this.currentVRCamera.devicePosition),i.toEulerAnglesToRef(this._workingVector),this._workingVector.z=0,this._workingVector.x=0,o.q.RotationYawPitchRollToRef(this._workingVector.y,this._workingVector.x,this._workingVector.z,this._workingQuaternion),this._workingQuaternion.toRotationMatrix(this._workingMatrix),o.x.TransformCoordinatesToRef(this._teleportBackwardsVector,this._workingMatrix,this._workingVector);var r=new It.a(n,this._workingVector),s=this._scene.pickWithRay(r,this._raySelectionPredicate);s&&s.pickedPoint&&s.pickedMesh&&this._isTeleportationFloor(s.pickedMesh)&&s.distance<5&&this.teleportCamera(s.pickedPoint),t._teleportationBackRequestInitiated=!0}}else t._teleportationBackRequestInitiated=!1},e.prototype._enableTeleportationOnController=function(e){var t=this;e.webVRController.mesh&&(e._interactionsEnabled||this._enableInteractionOnController(e),e._interactionsEnabled=!0,e._teleportationEnabled=!0,e.webVRController.controllerType===St.VIVE&&(e._dpadPressed=!1,e.webVRController.onPadStateChangedObservable.add(function(t){e._dpadPressed=t.pressed,e._dpadPressed||(e._rotationLeftAsked=!1,e._rotationRightAsked=!1,e._teleportationBackRequestInitiated=!1)})),e.webVRController.onPadValuesChangedObservable.add(function(i){t.teleportationEnabled&&(t._checkTeleportBackwards(i,e),t._checkTeleportWithRay(i,e)),t._checkRotate(i,e)}))},e.prototype._createTeleportationCircles=function(){this._teleportationTarget=fe.a.CreateGround("teleportationTarget",2,2,2,this._scene),this._teleportationTarget.isPickable=!1;var e=new Ri("DynamicTexture",512,this._scene,!0);e.hasAlpha=!0;var t=e.getContext();t.beginPath(),t.arc(256,256,200,0,2*Math.PI,!1),t.fillStyle=this._teleportationFillColor,t.fill(),t.lineWidth=10,t.strokeStyle=this._teleportationBorderColor,t.stroke(),t.closePath(),e.update();var i=new Pi.a("TextPlaneMaterial",this._scene);i.diffuseTexture=e,this._teleportationTarget.material=i;var n=fe.a.CreateTorus("torusTeleportation",.75,.1,25,this._scene,!1);n.isPickable=!1,n.parent=this._teleportationTarget;var r=new B("animationInnerCircle","position.y",30,B.ANIMATIONTYPE_FLOAT,B.ANIMATIONLOOPMODE_CYCLE),o=[];o.push({frame:0,value:0}),o.push({frame:30,value:.4}),o.push({frame:60,value:0}),r.setKeys(o);var s=new ue;s.setEasingMode($.EASINGMODE_EASEINOUT),r.setEasingFunction(s),n.animations=[],n.animations.push(r),this._scene.beginAnimation(n,0,60,!0),this._hideTeleportationTarget()},e.prototype._displayTeleportationTarget=function(){this._teleportActive=!0,this._teleportationInitialized&&(this._teleportationTarget.isVisible=!0,this._isDefaultTeleportationTarget&&(this._teleportationTarget.getChildren()[0].isVisible=!0))},e.prototype._hideTeleportationTarget=function(){this._teleportActive=!1,this._teleportationInitialized&&(this._teleportationTarget.isVisible=!1,this._isDefaultTeleportationTarget&&(this._teleportationTarget.getChildren()[0].isVisible=!1))},e.prototype._rotateCamera=function(e){var t=this;if(this.currentVRCamera instanceof bt){e?this._rotationAngle++:this._rotationAngle--,this.currentVRCamera.animations=[];var i=o.q.FromRotationMatrix(o.j.RotationY(Math.PI/4*this._rotationAngle)),n=new B("animationRotation","rotationQuaternion",90,B.ANIMATIONTYPE_QUATERNION,B.ANIMATIONLOOPMODE_CONSTANT),r=[];r.push({frame:0,value:this.currentVRCamera.rotationQuaternion}),r.push({frame:6,value:i}),n.setKeys(r),n.setEasingFunction(this._circleEase),this.currentVRCamera.animations.push(n),this._postProcessMove.animations=[];var s=new B("animationPP","vignetteWeight",90,B.ANIMATIONTYPE_FLOAT,B.ANIMATIONLOOPMODE_CONSTANT),a=[];a.push({frame:0,value:0}),a.push({frame:3,value:4}),a.push({frame:6,value:0}),s.setKeys(a),s.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(s);var c=new B("animationPP2","vignetteStretch",90,B.ANIMATIONTYPE_FLOAT,B.ANIMATIONLOOPMODE_CONSTANT),l=[];l.push({frame:0,value:0}),l.push({frame:3,value:10}),l.push({frame:6,value:0}),c.setKeys(l),c.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(c),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(){t._webVRCamera.detachPostProcess(t._postProcessMove)}),this._scene.beginAnimation(this.currentVRCamera,0,6,!1,1)}},e.prototype._moveTeleportationSelectorTo=function(e,t,i){if(e.pickedPoint){t._teleportationRequestInitiated&&(this._displayTeleportationTarget(),this._haloCenter.copyFrom(e.pickedPoint),this._teleportationTarget.position.copyFrom(e.pickedPoint));var n=this._convertNormalToDirectionOfRay(e.getNormal(!0,!1),i);if(n){var r=o.x.Cross(o.c.Y,n),s=o.x.Cross(n,r);o.x.RotationFromAxisToRef(s,n,r,this._teleportationTarget.rotation)}this._teleportationTarget.position.y+=.1}},e.prototype.teleportCamera=function(e){var t=this;if(this.currentVRCamera instanceof bt){this.webVRCamera.leftCamera?(this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition),this._workingVector.subtractInPlace(this.webVRCamera.position),e.subtractToRef(this._workingVector,this._workingVector)):this._workingVector.copyFrom(e),this.isInVRMode?this._workingVector.y+=this.webVRCamera.deviceDistanceToRoomGround()*this._webVRCamera.deviceScaleFactor:this._workingVector.y+=this._defaultHeight,this.onBeforeCameraTeleport.notifyObservers(this._workingVector),this.currentVRCamera.animations=[];var i=new B("animationCameraTeleportation","position",90,B.ANIMATIONTYPE_VECTOR3,B.ANIMATIONLOOPMODE_CONSTANT),n=[{frame:0,value:this.currentVRCamera.position},{frame:11,value:this._workingVector}];i.setKeys(n),i.setEasingFunction(this._circleEase),this.currentVRCamera.animations.push(i),this._postProcessMove.animations=[];var r=new B("animationPP","vignetteWeight",90,B.ANIMATIONTYPE_FLOAT,B.ANIMATIONLOOPMODE_CONSTANT),o=[];o.push({frame:0,value:0}),o.push({frame:5,value:8}),o.push({frame:11,value:0}),r.setKeys(o),this._postProcessMove.animations.push(r);var s=new B("animationPP2","vignetteStretch",90,B.ANIMATIONTYPE_FLOAT,B.ANIMATIONLOOPMODE_CONSTANT),a=[];a.push({frame:0,value:0}),a.push({frame:5,value:10}),a.push({frame:11,value:0}),s.setKeys(a),this._postProcessMove.animations.push(s),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._webVRCamera.attachPostProcess(this._postProcessMove),this._scene.beginAnimation(this._postProcessMove,0,11,!1,1,function(){t._webVRCamera.detachPostProcess(t._postProcessMove)}),this._scene.beginAnimation(this.currentVRCamera,0,11,!1,1,function(){t.onAfterCameraTeleport.notifyObservers(t._workingVector)}),this._hideTeleportationTarget()}},e.prototype._convertNormalToDirectionOfRay=function(e,t){e&&(Math.acos(o.x.Dot(e,t.direction))e;){var i=this.rigCameras.pop();i&&i.dispose()}},t.prototype._updateForDualEyeDebugging=function(e){void 0===e&&(e=.01),this._updateNumberOfRigCameras(2),this.rigCameras[0].viewport=new o.z(0,0,.5,1),this.rigCameras[0].position.x=-e/2,this.rigCameras[0].outputRenderTarget=null,this.rigCameras[1].viewport=new o.z(.5,0,.5,1),this.rigCameras[1].position.x=e/2,this.rigCameras[1].outputRenderTarget=null},t.prototype.updateFromXRSessionManager=function(e){var i=this;if(!e._currentXRFrame||!e._currentXRFrame.getDevicePose)return!1;var n=e._currentXRFrame.getDevicePose(e._frameOfReference);return!(!n||!n.poseModelMatrix)&&(o.j.FromFloat32ArrayToRefScaled(n.poseModelMatrix,0,1,t._TmpMatrix),this._scene.useRightHandedSystem||t._TmpMatrix.toggleModelMatrixHandInPlace(),t._TmpMatrix.getTranslationToRef(this.position),t._TmpMatrix.getRotationMatrixToRef(t._TmpMatrix),o.q.FromRotationMatrixToRef(t._TmpMatrix,this.rotationQuaternion),this.computeWorldMatrix(),this._updateNumberOfRigCameras(e._currentXRFrame.views.length),e._currentXRFrame.views.forEach(function(t,r){o.j.FromFloat32ArrayToRefScaled(n.getViewMatrix(t),0,1,i.rigCameras[r]._computedViewMatrix),o.j.FromFloat32ArrayToRefScaled(t.projectionMatrix,0,1,i.rigCameras[r]._projectionMatrix),i._scene.useRightHandedSystem||(i.rigCameras[r]._computedViewMatrix.toggleModelMatrixHandInPlace(),i.rigCameras[r]._projectionMatrix.toggleProjectionMatrixHandInPlace());var s=e._xrSession.baseLayer.getViewport(t),a=e._xrSession.baseLayer.framebufferWidth,c=e._xrSession.baseLayer.framebufferHeight;i.rigCameras[r].viewport.width=s.width/a,i.rigCameras[r].viewport.height=s.height/c,i.rigCameras[r].viewport.x=s.x/a,i.rigCameras[r].viewport.y=s.y/c,i.rigCameras[r].outputRenderTarget=e._sessionRenderTargetTexture}),!0)},t._TmpMatrix=new o.j,t}(bt),zi=function(){function e(e){this.scene=e,this.onXRFrameObservable=new r.c,this.onXRSessionEnded=new r.c,this._sessionRenderTargetTexture=null,this._tmpMatrix=new o.j}return e.prototype.initializeAsync=function(){var e=this;return p.a.Warn("The WebXR APIs are still under development and are subject to change in the future."),this._xrNavigator=navigator,this._xrNavigator.xr?this._xrNavigator.xr.requestDevice().then(function(t){return e._xrDevice=t,e.scene.getEngine()._gl.setCompatibleXRDevice(e._xrDevice)}):Promise.reject("webXR not supported by this browser")},e.prototype.enterXRAsync=function(t,i){var n=this;return this._xrDevice.requestSession(t).then(function(e){return n._xrSession=e,n._xrSession.addEventListener("end",function(){n._sessionRenderTargetTexture=null,n.scene.getEngine().restoreDefaultFramebuffer(),n.scene.getEngine().customAnimationFrameRequester=null,n.onXRSessionEnded.notifyObservers(null),n.scene.getEngine()._renderLoop()},{once:!0}),n._xrSession.baseLayer=new XRWebGLLayer(n._xrSession,n.scene.getEngine()._gl),n._xrSession.requestFrameOfReference(i)}).then(function(t){n._frameOfReference=t,n.scene.getEngine().customAnimationFrameRequester={requestAnimationFrame:n._xrSession.requestAnimationFrame.bind(n._xrSession),renderFunction:function(e,t){n._currentXRFrame=t,n.onXRFrameObservable.notifyObservers(null),n.scene.getEngine()._renderLoop()}},n._sessionRenderTargetTexture=e._CreateRenderTargetTextureFromSession(n._xrSession,n.scene),window.cancelAnimationFrame(n.scene.getEngine()._frameHandler),n.scene.getEngine()._renderLoop()})},e.prototype.exitXRAsync=function(){return this._xrSession.end()},e.prototype.environmentPointHitTestAsync=function(e){var t=this;return new Promise(function(i){var n=new Float32Array([e.origin.x,e.origin.y,e.origin.z]),r=new Float32Array([e.direction.x,e.direction.y,e.direction.z]);t.scene.useRightHandedSystem||(n[2]*=-1,r[2]*=-1),t._xrSession.requestHitTest(n,r,t._frameOfReference).then(function(e){if(e.length>0){o.j.FromFloat32ArrayToRefScaled(e[0].hitMatrix,0,1,t._tmpMatrix);var n=t._tmpMatrix.getTranslation();t.scene.useRightHandedSystem||(n.z*=-1),i(n)}else i(null)}).catch(function(){i(null)})})},e.prototype.supportsSessionAsync=function(e){return this._xrDevice.supportsSession(e).then(function(){return!0}).catch(function(){return!1})},e._CreateRenderTargetTextureFromSession=function(e,t){var i=new ze.a(t.getEngine(),ze.a.DATASOURCE_UNKNOWN,!0);i.width=e.baseLayer.framebufferWidth,i.height=e.baseLayer.framebufferHeight,i._framebuffer=e.baseLayer.framebuffer;var n=new _i("XR renderTargetTexture",{width:i.width,height:i.height},t,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,!0);return n._texture=i,n},e.prototype.dispose=function(){this.onXRFrameObservable.clear(),this.onXRSessionEnded.clear()},e}();!function(e){e[e.ENTERING_XR=0]="ENTERING_XR",e[e.EXITING_XR=1]="EXITING_XR",e[e.IN_XR=2]="IN_XR",e[e.NOT_IN_XR=3]="NOT_IN_XR"}(Li||(Li={}));var ji,Wi=function(){function e(e){this.scene=e,this.state=Li.NOT_IN_XR,this.onStateChangedObservable=new r.c,this._nonVRCamera=null,this._originalSceneAutoClear=!0,this._supported=!1,this.camera=new Gi("",e),this._sessionManager=new zi(e),this.container=new Fe.a("",e),this.camera.parent=this.container}return e.prototype._setState=function(e){this.state=e,this.onStateChangedObservable.notifyObservers(this.state)},e.CreateAsync=function(t){var i=new e(t);return i._sessionManager.initializeAsync().then(function(){return i._supported=!0,i}).catch(function(){return i})},e.prototype.exitXRAsync=function(){return this._setState(Li.EXITING_XR),this._sessionManager.exitXRAsync()},e.prototype.enterXRAsync=function(e,t){var i=this;if(!this._supported)throw"XR session not supported by this browser";return this._setState(Li.ENTERING_XR),this._sessionManager.enterXRAsync(e,t).then(function(){i._originalSceneAutoClear=i.scene.autoClear,i._nonVRCamera=i.scene.activeCamera,i.scene.autoClear=!1,i.scene.activeCamera=i.camera,i._sessionManager.onXRFrameObservable.add(function(){i.camera.updateFromXRSessionManager(i._sessionManager)}),i._sessionManager.onXRSessionEnded.addOnce(function(){i.camera.rigCameras.forEach(function(e){e.outputRenderTarget=null}),i.scene.autoClear=i._originalSceneAutoClear,i.scene.activeCamera=i._nonVRCamera,i._sessionManager.onXRFrameObservable.clear(),i._setState(Li.NOT_IN_XR)}),i._setState(Li.IN_XR)})},e.prototype.environmentPointHitTestAsync=function(e){return this._sessionManager.environmentPointHitTestAsync(e)},e.prototype.setPositionOfCameraUsingContainer=function(t){this.camera.globalPosition.subtractToRef(t,e._TmpVector),this.container.position.subtractInPlace(e._TmpVector)},e.prototype.rotateCameraByQuaternionUsingContainer=function(e){this.container.rotationQuaternion||(this.container.rotationQuaternion=o.q.FromEulerVector(this.container.rotation)),this.container.rotationQuaternion.multiplyInPlace(e),this.container.position.rotateByQuaternionAroundPointToRef(e,this.camera.globalPosition,this.container.position)},e.prototype.supportsSessionAsync=function(e){return this._supported?this._sessionManager.supportsSessionAsync(e):Promise.resolve(!1)},e.prototype.dispose=function(){this.camera.dispose(),this.container.dispose(),this.onStateChangedObservable.clear(),this._sessionManager.dispose()},e._TmpVector=new o.x,e}(),Hi=function(){function e(e,t){this.element=e,this.initializationOptions=t}return e.prototype.update=function(e){},e}(),Xi=function(){return function(){}}(),Yi=function(){function e(e,t){var i=this;if(this.scene=e,this._buttons=[],this._activeButton=null,this.activeButtonChangedObservable=new r.c,this._overlay=document.createElement("div"),this._overlay.style.cssText="z-index:11;position: absolute; right: 20px;bottom: 50px;",t.customButtons)this._buttons=t.customButtons;else{var n=document.createElement("button");n.style.cssText="color: #868686; border-color: #868686; border-style: solid; margin-left: 10px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-repeat:no-repeat; background-position: center; outline: none;",n.innerText="HMD",this._buttons.push(new Hi(n,{immersive:!0,outputContext:t.outputCanvasContext})),this._buttons[this._buttons.length-1].update=function(e){this.element.style.display=null===e||e===this?"":"none",this.element.innerText=e===this?"EXIT":"HMD"};var o=document.createElement("button");o.style.cssText=n.style.cssText,o.innerText="Window",this._buttons.push(new Hi(o,{immersive:!1,environmentIntegration:!0,outputContext:t.outputCanvasContext})),this._buttons[this._buttons.length-1].update=function(e){this.element.style.display=null===e||e===this?"":"none",this.element.innerText=e===this?"EXIT":"Window"},this._updateButtons(null)}var s=e.getEngine().getRenderingCanvas();s&&s.parentNode&&(s.parentNode.appendChild(this._overlay),e.onDisposeObservable.addOnce(function(){i.dispose()}))}return e.CreateAsync=function(t,i,n){var r=this,o=new e(t,n),s=o._buttons.map(function(e){return i.supportsSessionAsync(e.initializationOptions)});return i.onStateChangedObservable.add(function(e){e==Li.NOT_IN_XR&&o._updateButtons(null)}),Promise.all(s).then(function(e){return e.forEach(function(e,t){e&&(o._overlay.appendChild(o._buttons[t].element),o._buttons[t].element.onclick=function(){return l.b(r,void 0,void 0,function(){return l.e(this,function(e){switch(e.label){case 0:return i.state!=Li.IN_XR?[3,2]:(o._updateButtons(null),[4,i.exitXRAsync()]);case 1:return e.sent(),[2];case 2:return i.state!=Li.NOT_IN_XR?[3,4]:(o._updateButtons(o._buttons[t]),[4,i.enterXRAsync(o._buttons[t].initializationOptions,"eye-level")]);case 3:e.sent(),e.label=4;case 4:return[2]}})})})}),o})},e.prototype._updateButtons=function(e){var t=this;this._activeButton=e,this._buttons.forEach(function(e){e.update(t._activeButton)}),this.activeButtonChangedObservable.notifyObservers(this._activeButton)},e.prototype.dispose=function(){var e=this.scene.getEngine().getRenderingCanvas();e&&e.parentNode&&e.parentNode.contains(this._overlay)&&e.parentNode.removeChild(this._overlay),this.activeButtonChangedObservable.clear()},e}(),Ki=function(){function e(e){this.pointer=new Fe.a("controllerPointer",e)}return e.prototype.dispose=function(){this.grip&&this.grip.dispose(),this.pointer.dispose()},e}(),Qi=function(){function e(e){var t=this;this.helper=e,this.controllers=[],this._tmpMatrix=new o.j,this._frameObserver=e._sessionManager.onXRFrameObservable.add(function(){if(e._sessionManager._currentXRFrame&&e._sessionManager._currentXRFrame.getDevicePose){var i=e._sessionManager._currentXRFrame;e._sessionManager._xrSession.getInputSources().forEach(function(n,r){var s=i.getInputPose(n,e._sessionManager._frameOfReference);if(s){t.controllers.length<=r&&t.controllers.push(new Ki(e.container.getScene()));var a=t.controllers[r];s.gripMatrix&&(a.grip||(a.grip=new Fe.a("controllerGrip",e.container.getScene())),o.j.FromFloat32ArrayToRefScaled(s.gripMatrix,0,1,t._tmpMatrix),a.grip.getScene().useRightHandedSystem||t._tmpMatrix.toggleModelMatrixHandInPlace(),a.grip.rotationQuaternion||(a.grip.rotationQuaternion=new o.q),t._tmpMatrix.decompose(a.grip.scaling,a.grip.rotationQuaternion,a.grip.position)),o.j.FromFloat32ArrayToRefScaled(s.targetRay.transformMatrix,0,1,t._tmpMatrix),a.pointer.getScene().useRightHandedSystem||t._tmpMatrix.toggleModelMatrixHandInPlace(),a.pointer.rotationQuaternion||(a.pointer.rotationQuaternion=new o.q),t._tmpMatrix.decompose(a.pointer.scaling,a.pointer.rotationQuaternion,a.pointer.position)}})}})}return e.prototype.dispose=function(){this.controllers.forEach(function(e){e.dispose()}),this.helper._sessionManager.onXRFrameObservable.remove(this._frameObserver)},e}(),qi=function(){function e(e,t){var i=this;this._canvas=null,this.canvasContext=null,t||((t=document.createElement("canvas")).style.cssText="position:absolute; bottom:0px;right:0px;z-index:10;width:100%;height:100%;background-color: #000000;"),this._setManagedOutputCanvas(t),e.onStateChangedObservable.add(function(t){t==Li.ENTERING_XR?i._addCanvas():e.state==Li.NOT_IN_XR&&i._removeCanvas()})}return e.prototype.dispose=function(){this._removeCanvas(),this._setManagedOutputCanvas(null)},e.prototype._setManagedOutputCanvas=function(e){this._removeCanvas(),e?(this._canvas=e,this.canvasContext=this._canvas.getContext("xrpresent")):(this._canvas=null,this.canvasContext=null)},e.prototype._addCanvas=function(){this._canvas&&document.body.appendChild(this._canvas)},e.prototype._removeCanvas=function(){this._canvas&&document.body.contains(this._canvas)&&document.body.removeChild(this._canvas)},e}(),Zi=(ji={root:0,found:!1},function(e,t,i,n){ji.root=0,ji.found=!1;var r=t*t-4*e*i;if(r<0)return ji;var o=Math.sqrt(r),s=(-t-o)/(2*e),a=(-t+o)/(2*e);if(s>a){var c=a;a=s,s=c}return s>0&&s0&&a=0))},e.prototype._canDoCollision=function(e,t,i,n){var r=o.x.Distance(this._basePointWorld,e),s=Math.max(this._radius.x,this._radius.y,this._radius.z);return!(r>this._velocityWorldLength+s+t)&&!!function(e,t,i,n){return!(e.x>i.x+n||i.x-n>t.x||e.y>i.y+n||i.y-n>t.y||e.z>i.z+n||i.z-n>t.z)}(i,n,this._basePointWorld,this._velocityWorldLength+s)},e.prototype._testTriangle=function(e,t,i,n,r,s){var a,c=!1;t||(t=[]),t[e]||(t[e]=new o.n(0,0,0,0),t[e].copyFromPoints(i,n,r));var l=t[e];if(s||l.isFrontFacingTo(this._normalizedVelocity,0)){var u=l.signedDistanceTo(this._basePoint),h=o.x.Dot(l.normal,this._velocity);if(0==h){if(Math.abs(u)>=1)return;c=!0,a=0}else{var d=(1-u)/h;if((a=(-1-u)/h)>d){var f=d;d=a,a=f}if(a>1||d<0)return;a<0&&(a=0),a>1&&(a=1)}this._collisionPoint.copyFromFloats(0,0,0);var p=!1,_=1;if(c||(this._basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this._velocity.scaleToRef(a,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,i,n,r,l.normal)&&(p=!0,_=a,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!p){var m=this._velocity.lengthSquared(),g=m;this._basePoint.subtractToRef(i,this._tempVector);var v=2*o.x.Dot(this._velocity,this._tempVector),y=this._tempVector.lengthSquared()-1,b=Zi(g,v,y,_);b.found&&(_=b.root,p=!0,this._collisionPoint.copyFrom(i)),this._basePoint.subtractToRef(n,this._tempVector),v=2*o.x.Dot(this._velocity,this._tempVector),y=this._tempVector.lengthSquared()-1,(b=Zi(g,v,y,_)).found&&(_=b.root,p=!0,this._collisionPoint.copyFrom(n)),this._basePoint.subtractToRef(r,this._tempVector),v=2*o.x.Dot(this._velocity,this._tempVector),y=this._tempVector.lengthSquared()-1,(b=Zi(g,v,y,_)).found&&(_=b.root,p=!0,this._collisionPoint.copyFrom(r)),n.subtractToRef(i,this._edge),i.subtractToRef(this._basePoint,this._baseToVertex);var T=this._edge.lengthSquared(),E=o.x.Dot(this._edge,this._velocity),x=o.x.Dot(this._edge,this._baseToVertex);if(g=T*-m+E*E,v=T*(2*o.x.Dot(this._velocity,this._baseToVertex))-2*E*x,y=T*(1-this._baseToVertex.lengthSquared())+x*x,(b=Zi(g,v,y,_)).found){var A=(E*b.root-x)/T;A>=0&&A<=1&&(_=b.root,p=!0,this._edge.scaleInPlace(A),i.addToRef(this._edge,this._collisionPoint))}r.subtractToRef(n,this._edge),n.subtractToRef(this._basePoint,this._baseToVertex),T=this._edge.lengthSquared(),E=o.x.Dot(this._edge,this._velocity),x=o.x.Dot(this._edge,this._baseToVertex),g=T*-m+E*E,v=T*(2*o.x.Dot(this._velocity,this._baseToVertex))-2*E*x,y=T*(1-this._baseToVertex.lengthSquared())+x*x,(b=Zi(g,v,y,_)).found&&(A=(E*b.root-x)/T)>=0&&A<=1&&(_=b.root,p=!0,this._edge.scaleInPlace(A),n.addToRef(this._edge,this._collisionPoint)),i.subtractToRef(r,this._edge),r.subtractToRef(this._basePoint,this._baseToVertex),T=this._edge.lengthSquared(),E=o.x.Dot(this._edge,this._velocity),x=o.x.Dot(this._edge,this._baseToVertex),g=T*-m+E*E,v=T*(2*o.x.Dot(this._velocity,this._baseToVertex))-2*E*x,y=T*(1-this._baseToVertex.lengthSquared())+x*x,(b=Zi(g,v,y,_)).found&&(A=(E*b.root-x)/T)>=0&&A<=1&&(_=b.root,p=!0,this._edge.scaleInPlace(A),r.addToRef(this._edge,this._collisionPoint))}if(p){var P=_*this._velocity.length();(!this.collisionFound||P=n)r.copyFrom(e);else{var a=o?o.collisionMask:i.collisionMask;i._initialize(e,t,s);for(var c=0;cthis.capacity&&this._depth-1&&this.entries.splice(i,1)}},e.prototype.addEntries=function(e){for(var t=0;te.occlusionRetryCount))return!1;e.isOcclusionQueryInProgress=!1,e.occlusionInternalRetryCounter=0,e.isOccluded=e.occlusionType!==Fe.a.OCCLUSION_TYPE_OPTIMISTIC&&e.isOccluded}var n=this.getScene();if(n.getBoundingBoxRenderer){var r=n.getBoundingBoxRenderer();this._occlusionQuery||(this._occlusionQuery=t.createQuery()),t.beginOcclusionQuery(e.occlusionQueryAlgorithmType,this._occlusionQuery),r.renderOcclusionBoundingBox(this),t.endOcclusionQuery(e.occlusionQueryAlgorithmType),this._occlusionDataStorage.isOcclusionQueryInProgress=!0}return e.isOccluded};me.b.prototype.createTransformFeedback=function(){return this._gl.createTransformFeedback()},me.b.prototype.deleteTransformFeedback=function(e){this._gl.deleteTransformFeedback(e)},me.b.prototype.bindTransformFeedback=function(e){this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK,e)},me.b.prototype.beginTransformFeedback=function(e){void 0===e&&(e=!0),this._gl.beginTransformFeedback(e?this._gl.POINTS:this._gl.TRIANGLES)},me.b.prototype.endTransformFeedback=function(){this._gl.endTransformFeedback()},me.b.prototype.setTranformFeedbackVaryings=function(e,t){this._gl.transformFeedbackVaryings(e,t,this._gl.INTERLEAVED_ATTRIBS)},me.b.prototype.bindTransformFeedbackBuffer=function(e){this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER,0,e?e.underlyingResource:null)};var pn=i(108),_n=i(92),mn=i(67),gn=i(63),vn=i(44),yn="\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include\nvoid main(void)\n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}";zt.a.ShadersStore.rgbdEncodePixelShader=yn;var bn="\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include\nvoid main(void)\n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}";zt.a.ShadersStore.rgbdDecodePixelShader=bn;var Tn=function(){function e(){}return e.GetEnvInfo=function(t){for(var i=new DataView(t),n=0,r=0;r":""},t.prototype.preProcessor=function(e,t,i){return i||(this._varyingLocationCount=0,this._varyingLocationMap={}),this._replacements=[],this._textureCount=0,this._uniforms=[],e},t.prototype.postProcessor=function(t,i,n){return t=(t=(t=e.prototype.postProcessor.call(this,t,i,n)).replace("","uniform Frame {\n"+this._uniforms.join("\n")+"\n};")).replace("out vec4 glFragColor","layout(location=0) out vec4 glFragColor")},t}(_n.a),Rn=function(){function e(){this.isAsync=!1,this.isReady=!1}return e.prototype._handlesSpectorRebuildCallback=function(e){throw new Error("Not implemented")},e}(),Sn=function(e){function t(t,i){var n=e.call(this)||this;return n.id=t,n.data=i,n}return l.d(t,e),t}(mn.a),Cn=function(){function e(){}return e.POINT=0,e.MINPOINT_MAGPOINT_MIPPOINT=e.POINT,e.BILINEAR=1,e.MINLINEAR_MAGLINEAR_MIPPOINT=e.BILINEAR,e.TRILINEAR=2,e.MINLINEAR_MAGLINEAR_MIPLINEAR=e.TRILINEAR,e.ANISOTROPIC=3,e.POINT_COMPARE=4,e.TRILINEAR_COMPARE=5,e.MINBILINEAR_MAGPOINT=6,e.MINLINEAR_MAGPOINT_MIPLINEAR=e.MINBILINEAR_MAGPOINT,e.MINPOINT_MAGPOINT_MIPLINEAR=7,e.MINPOINT_MAGLINEAR_MIPPOINT=8,e.MINPOINT_MAGLINEAR_MIPLINEAR=9,e.MINLINEAR_MAGPOINT_MIPPOINT=10,e}(),Mn=function(){function e(){}return e.WRAP=0,e.MIRROR=1,e.CLAMP=2,e.BORDER=3,e.MIRROR_ONCE=4,e}(),On=function(){function e(){}return e.REPLACE=0,e.OVER=1,e.UNDER=2,e.INSIDE=3,e.ERASE=4,e.NULL=5,e.CLEAR=6,e.STRAIGHT_REPLACE=7,e.STRAIGHT_OVER=8,e.STRAIGHT_ADD=9,e.ADD=10,e.SCREEN=11,e.MULTIPLY=12,e.MULTIPLY2X=13,e.INTERPOLATE=14,e.MINIMUM=15,e.MAXIMUM=16,e.MAXIMUM_ALPHA=17,e.ADD_ALPHA=18,e.BLACK_REPLACE=19,e.BLACK_OVER=20,e.BLACK_UNDER=21,e.BLACK_INSIDE=22,e.ALPHA_COVERAGE_MASK=23,e.DUAL_COLOR_MULTIPLY_ADD=24,e.COMBINE=25,e.BLEND_OPAQUE=e.REPLACE,e.BLEND_ALPHA_PREMULTIPLIED=e.OVER,e.BLEND_ALPHA_STRAIGHT=e.STRAIGHT_OVER,e}(),In=function(){return function(){this.textureSize=512,this.deterministicLockstep=!1,this.lockstepMaxSteps=4}}(),Dn=function(e){function t(t){void 0===t&&(t=new In);var i=e.call(this,null)||this;return i._native=nativeEngine,i._nextBufferId=0,void 0===t.deterministicLockstep&&(t.deterministicLockstep=!1),void 0===t.lockstepMaxSteps&&(t.lockstepMaxSteps=4),i._options=t,i._webGLVersion=2,i.disableUniformBuffers=!0,i._caps=new me.c,i._caps.maxTexturesImageUnits=16,i._caps.maxVertexTextureImageUnits=16,i._caps.maxTextureSize=512,i._caps.maxCubemapTextureSize=512,i._caps.maxRenderTextureSize=512,i._caps.maxVertexAttribs=16,i._caps.maxVaryingVectors=16,i._caps.maxFragmentUniformVectors=16,i._caps.maxVertexUniformVectors=16,i._caps.standardDerivatives=!0,i._caps.astc=null,i._caps.s3tc=null,i._caps.pvrtc=null,i._caps.etc1=null,i._caps.etc2=null,i._caps.maxAnisotropy=16,i._caps.uintIndices=!1,i._caps.fragmentDepthSupported=!1,i._caps.highPrecisionShaderSupported=!0,i._caps.colorBufferFloat=!1,i._caps.textureFloat=!1,i._caps.textureFloatLinearFiltering=!1,i._caps.textureFloatRender=!1,i._caps.textureHalfFloat=!1,i._caps.textureHalfFloatLinearFiltering=!1,i._caps.textureHalfFloatRender=!1,i._caps.textureLOD=!0,i._caps.drawBuffersExtension=!1,i._caps.depthTextureExtension=!1,i._caps.vertexArrayObject=!0,i._caps.instancedArrays=!1,ye.h.Log("Babylon Native (v"+me.b.Version+") launched"),"undefined"==typeof URL&&(window.URL={createObjectURL:function(){},revokeObjectURL:function(){}}),"undefined"==typeof Blob&&(window.Blob=function(){}),i._shaderProcessor=new Pn,i}return l.d(t,e),t.prototype.isDeterministicLockStep=function(){return this._options.deterministicLockstep},t.prototype.getLockstepMaxSteps=function(){return this._options.lockstepMaxSteps},t.prototype.getHardwareScalingLevel=function(){return 1},t.prototype._queueNewFrame=function(e,t){return this._native.requestAnimationFrame(e),0},t.prototype.clear=function(e,t,i,n){void 0===n&&(n=!1),this._native.clear(e.r,e.g,e.b,e.a,t,i,n)},t.prototype.createIndexBuffer=function(e){var t=this._normalizeIndexData(e),i=new Sn(this._nextBufferId++,t);return i.references=1,i.is32Bits=4===t.BYTES_PER_ELEMENT,i},t.prototype.createVertexBuffer=function(e){var t=new Sn(this._nextBufferId++,e);return t.references=1,t},t.prototype.recordVertexArrayObject=function(e,t,i){var n=this._native.createVertexArray();t&&(t.nativeIndexBuffer||(t.nativeIndexBuffer=this._native.createIndexBuffer(t.data)),this._native.recordIndexBuffer(n,t.nativeIndexBuffer));for(var r={},o=i.getAttributesNames(),s=0;s=0){var c=e[o[s]];if(c)if(h=c.getBuffer())(u=r[h.id])||(u={buffer:h,byteStride:c.byteStride,infos:[]},r[h.id]=u),u.infos.push({location:a,numElements:c.getSize(),type:c.type,normalized:c.normalized,byteOffset:c.byteOffset})}}for(var l in r){var u,h;if(!(h=(u=r[l]).buffer).nativeVertexBuffer){var d=ArrayBuffer.isView(h.data)?h.data:new Float32Array(h.data);h.nativeVertexBuffer=this._native.createVertexBuffer(d,u.byteStride,u.infos)}this._native.recordVertexBuffer(n,h.nativeVertexBuffer)}return n},t.prototype.bindVertexArrayObject=function(e){this._native.bindVertexArray(e)},t.prototype.releaseVertexArrayObject=function(e){this._native.deleteVertexArray(e)},t.prototype.getAttributes=function(e,t){var i=e;return this._native.getAttributes(i.nativeProgram,t)},t.prototype.drawElementsType=function(e,t,i,n){this._drawCalls.addCount(1,!1),this._native.drawIndexed(e,t,i)},t.prototype.drawArraysType=function(e,t,i,n){this._drawCalls.addCount(1,!1),this._native.draw(e,t,i)},t.prototype.createEffect=function(e,t,i,n,r,o,s,a,c){var l=(e.vertexElement||e.vertex||e)+"+"+(e.fragmentElement||e.fragment||e)+"@"+(r||t.defines);if(this._compiledEffects[l]){var u=this._compiledEffects[l];return s&&u.isReady()&&s(u),u}var h=new zt.a(e,t,i,n,this,r,o,s,a,c,!1);return h._key=l,this._compiledEffects[l]=h,h},t.prototype.createPipelineContext=function(){return new Rn},t.prototype._preparePipelineContext=function(e,t,i,n,r,o,s){var a=e;a.nativeProgram=n?this.createRawShaderProgram(e,t,i,void 0,s):this.createShaderProgram(e,t,i,o,void 0,s)},t.prototype._isRenderingStateCompiled=function(e){return!0},t.prototype._executeWhenRenderingStateIsCompiled=function(e,t){t()},t.prototype.createRawShaderProgram=function(e,t,i,n,r){throw void 0===r&&(r=null),new Error("Not Supported")},t.prototype.createShaderProgram=function(e,t,i,n,r,o){void 0===o&&(o=null),this.onBeforeShaderCompilationObservable.notifyObservers(this);var s=this._native.createProgram(t,i);return this.onAfterShaderCompilationObservable.notifyObservers(this),s},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,t){var i=e;return this._native.getUniforms(i.nativeProgram,t)},t.prototype.bindUniformBlock=function(e,t,i){throw new Error("Not Implemented")},t.prototype.bindSamplers=function(e){var t=e.getPipelineContext();this._setProgram(t.nativeProgram);for(var i=e.getSamplers(),n=0;n-1?d.substring(g).toLowerCase():""),y=null,b=0,T=me.b._TextureLoaders;b-1?e.substring(p).toLowerCase():"")))throw new Error("Cannot load cubemap: non-ENV format not supported.");if(i&&6===i.length)throw new Error("Multi-file loading not yet supported.");return this._loadFile(e,function(e){e=e;var t=Tn.GetEnvInfo(e);if(f.width=t.width,f.height=t.width,Tn.UploadEnvSpherical(f,t),1!==t.version)throw new Error('Unsupported babylon environment map version "'+t.version+'"');var i=t.specular;if(!i)throw new Error("Nothing else parsed so far");f._lodGenerationScale=i.lodGenerationScale;var n=Tn.CreateImageDataArrayBufferViews(e,t);f.format=me.b.TEXTUREFORMAT_RGBA,f.type=me.b.TEXTURETYPE_UNSIGNED_INT,f.generateMipMaps=!0,f.getEngine().updateTextureSamplingMode(Ge.a.TRILINEAR_SAMPLINGMODE,f),f._isRGBD=!0,f.invertY=!0,d._native.loadCubeTexture(f._webGLTexture,n,!0),f.isReady=!0,r&&r()},void 0,void 0,!0,function(e,t){o&&e&&o(e.status+" "+e.statusText,t)}),this._internalTexturesCache.push(f),f},t.prototype._getSamplingFilter=function(e){switch(e){case me.b.TEXTURE_BILINEAR_SAMPLINGMODE:return Cn.MINLINEAR_MAGLINEAR_MIPPOINT;case me.b.TEXTURE_TRILINEAR_SAMPLINGMODE:return Cn.MINLINEAR_MAGLINEAR_MIPLINEAR;case me.b.TEXTURE_NEAREST_SAMPLINGMODE:return Cn.MINPOINT_MAGPOINT_MIPLINEAR;case me.b.TEXTURE_NEAREST_NEAREST_MIPNEAREST:return Cn.MINPOINT_MAGPOINT_MIPPOINT;case me.b.TEXTURE_NEAREST_LINEAR_MIPNEAREST:return Cn.MINLINEAR_MAGPOINT_MIPPOINT;case me.b.TEXTURE_NEAREST_LINEAR_MIPLINEAR:case me.b.TEXTURE_NEAREST_LINEAR:return Cn.MINLINEAR_MAGPOINT_MIPLINEAR;case me.b.TEXTURE_NEAREST_NEAREST:return Cn.MINPOINT_MAGPOINT_MIPPOINT;case me.b.TEXTURE_LINEAR_NEAREST_MIPNEAREST:return Cn.MINPOINT_MAGLINEAR_MIPPOINT;case me.b.TEXTURE_LINEAR_NEAREST_MIPLINEAR:return Cn.MINPOINT_MAGLINEAR_MIPLINEAR;case me.b.TEXTURE_LINEAR_LINEAR:return Cn.MINLINEAR_MAGLINEAR_MIPLINEAR;case me.b.TEXTURE_LINEAR_NEAREST:return Cn.MINPOINT_MAGLINEAR_MIPLINEAR;default:throw new Error("Unexpected sampling mode: "+e+".")}},t.prototype.createRenderTargetTexture=function(e,t){var i=new xn.a;void 0!==t&&"object"==typeof t?(i.generateMipMaps=t.generateMipMaps,i.generateDepthBuffer=void 0===t.generateDepthBuffer||t.generateDepthBuffer,i.generateStencilBuffer=i.generateDepthBuffer&&t.generateStencilBuffer,i.type=void 0===t.type?me.b.TEXTURETYPE_UNSIGNED_INT:t.type,i.samplingMode=void 0===t.samplingMode?Ge.a.TRILINEAR_SAMPLINGMODE:t.samplingMode):(i.generateMipMaps=t,i.generateDepthBuffer=!0,i.generateStencilBuffer=!1,i.type=me.b.TEXTURETYPE_UNSIGNED_INT,i.samplingMode=Ge.a.TRILINEAR_SAMPLINGMODE);var n=new ze.a(this,ze.a.DATASOURCE_RENDERTARGET),r=e.width||e,o=e.height||e;return n._depthStencilBuffer={},n._framebuffer={},n.baseWidth=r,n.baseHeight=o,n.width=r,n.height=o,n.isReady=!0,n.samples=1,n.generateMipMaps=!!i.generateMipMaps,n.samplingMode=i.samplingMode,n.type=i.type,n._generateDepthBuffer=i.generateDepthBuffer,n._generateStencilBuffer=!!i.generateStencilBuffer,this._internalTexturesCache.push(n),n},t.prototype.updateTextureSamplingMode=function(e,t){if(t._webGLTexture){var i=this._getSamplingFilter(e);this._native.setTextureSampling(t._webGLTexture,i)}t.samplingMode=e},t.prototype.bindFramebuffer=function(e,t,i,n,r){throw new Error("bindFramebuffer not yet implemented.")},t.prototype.unBindFramebuffer=function(e,t,i){throw void 0===t&&(t=!1),new Error("unBindFramebuffer not yet implemented.")},t.prototype.createDynamicVertexBuffer=function(e){throw new Error("createDynamicVertexBuffer not yet implemented.")},t.prototype.updateDynamicIndexBuffer=function(e,t,i){throw void 0===i&&(i=0),new Error("updateDynamicIndexBuffer not yet implemented.")},t.prototype.updateDynamicVertexBuffer=function(e,t,i,n){throw new Error("updateDynamicVertexBuffer not yet implemented.")},t.prototype._setTexture=function(e,t,i,n){void 0===i&&(i=!1),void 0===n&&(n=!1);var r,o=this._boundUniforms[e];if(!o)return!1;if(!t)return null!=this._boundTexturesCache[e]&&(this._activeChannel=e,this._native.setTexture(o,null)),!1;if(t.video)this._activeChannel=e,t.update();else if(t.delayLoadState===me.b.DELAYLOADSTATE_NOTLOADED)return t.delayLoad(),!1;return r=n?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:this.emptyTexture,this._activeChannel=e,!(!r||!r._webGLTexture)&&(this._native.setTextureWrapMode(r._webGLTexture,this._getAddressMode(t.wrapU),this._getAddressMode(t.wrapV),this._getAddressMode(t.wrapR)),this._updateAnisotropicLevel(t),this._native.setTexture(o,r._webGLTexture),!0)},t.prototype._updateAnisotropicLevel=function(e){var t=e.getInternalTexture(),i=e.anisotropicFilteringLevel;t&&t._webGLTexture&&t._cachedAnisotropicFilteringLevel!==i&&(this._native.setTextureAnisotropicLevel(t._webGLTexture,i),t._cachedAnisotropicFilteringLevel=i)},t.prototype._getAddressMode=function(e){switch(e){case me.b.TEXTURE_WRAP_ADDRESSMODE:return Mn.WRAP;case me.b.TEXTURE_CLAMP_ADDRESSMODE:return Mn.CLAMP;case me.b.TEXTURE_MIRROR_ADDRESSMODE:return Mn.MIRROR;default:throw new Error("Unexpected wrap mode: "+e+".")}},t.prototype._bindTexture=function(e,t){throw new Error("_bindTexture not implemented.")},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,t,i,n,r,o,s){throw void 0===o&&(o=0),void 0===s&&(s=0),new Error("_uploadCompressedDataToTextureDirectly not implemented.")},t.prototype._uploadDataToTextureDirectly=function(e,t,i,n){throw void 0===i&&(i=0),void 0===n&&(n=0),new Error("_uploadDataToTextureDirectly not implemented.")},t.prototype._uploadArrayBufferViewToTexture=function(e,t,i,n){throw void 0===i&&(i=0),void 0===n&&(n=0),new Error("_uploadArrayBufferViewToTexture not implemented.")},t.prototype._uploadImageToTexture=function(e,t,i,n){throw void 0===i&&(i=0),void 0===n&&(n=0),new Error("_uploadArrayBufferViewToTexture not implemented.")},t}(me.b),Ln=function(){function e(){}return e.COPY=1,e.CUT=2,e.PASTE=3,e}(),wn=function(){function e(e,t){this.type=e,this.event=t}return e.GetTypeFromCharacter=function(e){switch(e){case 67:return Ln.COPY;case 86:return Ln.PASTE;case 88:return Ln.CUT;default:return-1}},e}(),Fn=i(60),Nn=i(55),Bn=function(){function e(e,t,i){this.lengthComputable=e,this.loaded=t,this.total=i}return e.FromProgressEvent=function(t){return new e(t.lengthComputable,t.loaded,t.total)},e}(),Un=function(){function e(){}return Object.defineProperty(e,"ForceFullSceneLoadingForIncremental",{get:function(){return Nn.a.ForceFullSceneLoadingForIncremental},set:function(e){Nn.a.ForceFullSceneLoadingForIncremental=e},enumerable:!0,configurable:!0}),Object.defineProperty(e,"ShowLoadingScreen",{get:function(){return Nn.a.ShowLoadingScreen},set:function(e){Nn.a.ShowLoadingScreen=e},enumerable:!0,configurable:!0}),Object.defineProperty(e,"loggingLevel",{get:function(){return Nn.a.loggingLevel},set:function(e){Nn.a.loggingLevel=e},enumerable:!0,configurable:!0}),Object.defineProperty(e,"CleanBoneMatrixWeights",{get:function(){return Nn.a.CleanBoneMatrixWeights},set:function(e){Nn.a.CleanBoneMatrixWeights=e},enumerable:!0,configurable:!0}),e._getDefaultPlugin=function(){return e._registeredPlugins[".babylon"]},e._getPluginForExtension=function(t){var i=e._registeredPlugins[t];return i||(p.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: http://doc.babylonjs.com/how_to/load_from_any_file_type"),e._getDefaultPlugin())},e._getPluginForDirectLoad=function(t){for(var i in e._registeredPlugins){var n=e._registeredPlugins[i].plugin;if(n.canDirectLoad&&n.canDirectLoad(t))return e._registeredPlugins[i]}return e._getDefaultPlugin()},e._getPluginForFilename=function(t){var i=t.indexOf("?");-1!==i&&(t=t.substring(0,i));var n=t.lastIndexOf("."),r=t.substring(n,t.length).toLowerCase();return e._getPluginForExtension(r)},e._getDirectLoad=function(e){return"data:"===e.substr(0,5)?e.substr(5):null},e._loadData=function(t,i,n,r,o,s,a){var c,l=e._getDirectLoad(t.name),u=a?e._getPluginForExtension(a):l?e._getPluginForDirectLoad(t.name):e._getPluginForFilename(t.name);if(!(c=u.plugin.createPlugin?u.plugin.createPlugin():u.plugin))throw"The loader plugin corresponding to the file type you are trying to load has not been found. If using es6, please import the plugin you wish to use before.";var h,d=u.isBinary;e.OnPluginActivatedObservable.notifyObservers(c);var f=function(e,t){i.isDisposed?o("Scene has been disposed"):(i.offlineProvider=h,n(c,e,t))},p=null,_=!1,m=c.onDisposeObservable;m&&m.add(function(){_=!0,p&&(p.abort(),p=null),s()});var g=function(){_||(p=ye.h.LoadFile(t.url,f,r?function(e){r(Bn.FromProgressEvent(e))}:void 0,h,d,function(e,t){o("Failed to load scene."+(t?" "+t.message:""),t)}))};if(l)return f(l),c;var v=t.file||Fn.a.FilesToLoad[t.name.toLowerCase()];if(-1===t.rootUrl.indexOf("file:")||-1!==t.rootUrl.indexOf("file:")&&!v){var y=i.getEngine(),b=y.enableOfflineSupport;if(b){for(var T=!1,E=0,x=i.disableOfflineSupportExceptionRules;Ea.snapDistance?(r=Math.floor(Math.abs(u)/a.snapDistance),u<0&&(r*=-1),u%=a.snapDistance,h.scaleToRef(a.snapDistance*r,h),n=!0):h.scaleInPlace(0)),a.attachedMesh.scaling.addInPlace(h),n&&(d.snapDistance=a.snapDistance*r,a.onSnapObservable.notifyObservers(d))}}),a._pointerObserver=n.utilityLayerScene.onPointerObservable.add(function(e){if(!a._customMeshSet){var t=e.pickInfo&&-1!=a._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh)?a._hoverMaterial:a._coloredMaterial;a._rootMesh.getChildMeshes().forEach(function(e){e.material=t,e.color&&(e.color=t.diffuseColor)})}});var f=n._getSharedGizmoLight();return f.includedOnlyMeshes=f.includedOnlyMeshes.concat(a._rootMesh.getChildMeshes()),a}return l.d(t,e),t.prototype._attachedMeshChanged=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.attachedMesh=null},enumerable:!0,configurable:!0}),t.prototype.dispose=function(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._arrow&&this._arrow.dispose(),[this._coloredMaterial,this._hoverMaterial].forEach(function(e){e&&e.dispose()}),e.prototype.dispose.call(this)},t.prototype.setCustomMesh=function(t,i){var n=this;void 0===i&&(i=!1),e.prototype.setCustomMesh.call(this,t),i&&(this._rootMesh.getChildMeshes().forEach(function(e){e.material=n._coloredMaterial,e.color&&(e.color=n._coloredMaterial.diffuseColor)}),this._customMeshSet=!1)},t}(Kn.a),Zn=i(47),Jn=i(42),$n=function(e){function t(t,i){void 0===t&&(t=o.e.Gray()),void 0===i&&(i=Qn.a.DefaultKeepDepthUtilityLayer);var n=e.call(this,i)||this;n._boundingDimensions=new o.x(1,1,1),n._renderObserver=null,n._pointerObserver=null,n._scaleDragSpeed=.2,n._tmpQuaternion=new o.q,n._tmpVector=new o.x(0,0,0),n._tmpRotationMatrix=new o.j,n.ignoreChildren=!1,n.includeChildPredicate=null,n.rotationSphereSize=.1,n.scaleBoxSize=.1,n.fixedDragMeshScreenSize=!1,n.fixedDragMeshScreenSizeDistanceFactor=10,n.onDragStartObservable=new r.c,n.onScaleBoxDragObservable=new r.c,n.onScaleBoxDragEndObservable=new r.c,n.onRotationSphereDragObservable=new r.c,n.onRotationSphereDragEndObservable=new r.c,n.scalePivot=null,n._existingMeshScale=new o.x,n._dragMesh=null,n.pointerDragBehavior=new Le.a,n._updateScale=!1,n._anchorMesh=new Fe.a("anchor",i.utilityLayerScene),n.coloredMaterial=new Pi.a("",i.utilityLayerScene),n.coloredMaterial.disableLighting=!0,n.hoverColoredMaterial=new Pi.a("",i.utilityLayerScene),n.hoverColoredMaterial.disableLighting=!0,n._lineBoundingBox=new Fe.a("",i.utilityLayerScene),n._lineBoundingBox.rotationQuaternion=new o.q;var s=[];s.push(Jn.a.CreateLines("lines",{points:[new o.x(0,0,0),new o.x(n._boundingDimensions.x,0,0)]},i.utilityLayerScene)),s.push(Jn.a.CreateLines("lines",{points:[new o.x(0,0,0),new o.x(0,n._boundingDimensions.y,0)]},i.utilityLayerScene)),s.push(Jn.a.CreateLines("lines",{points:[new o.x(0,0,0),new o.x(0,0,n._boundingDimensions.z)]},i.utilityLayerScene)),s.push(Jn.a.CreateLines("lines",{points:[new o.x(n._boundingDimensions.x,0,0),new o.x(n._boundingDimensions.x,n._boundingDimensions.y,0)]},i.utilityLayerScene)),s.push(Jn.a.CreateLines("lines",{points:[new o.x(n._boundingDimensions.x,0,0),new o.x(n._boundingDimensions.x,0,n._boundingDimensions.z)]},i.utilityLayerScene)),s.push(Jn.a.CreateLines("lines",{points:[new o.x(0,n._boundingDimensions.y,0),new o.x(n._boundingDimensions.x,n._boundingDimensions.y,0)]},i.utilityLayerScene)),s.push(Jn.a.CreateLines("lines",{points:[new o.x(0,n._boundingDimensions.y,0),new o.x(0,n._boundingDimensions.y,n._boundingDimensions.z)]},i.utilityLayerScene)),s.push(Jn.a.CreateLines("lines",{points:[new o.x(0,0,n._boundingDimensions.z),new o.x(n._boundingDimensions.x,0,n._boundingDimensions.z)]},i.utilityLayerScene)),s.push(Jn.a.CreateLines("lines",{points:[new o.x(0,0,n._boundingDimensions.z),new o.x(0,n._boundingDimensions.y,n._boundingDimensions.z)]},i.utilityLayerScene)),s.push(Jn.a.CreateLines("lines",{points:[new o.x(n._boundingDimensions.x,n._boundingDimensions.y,n._boundingDimensions.z),new o.x(0,n._boundingDimensions.y,n._boundingDimensions.z)]},i.utilityLayerScene)),s.push(Jn.a.CreateLines("lines",{points:[new o.x(n._boundingDimensions.x,n._boundingDimensions.y,n._boundingDimensions.z),new o.x(n._boundingDimensions.x,0,n._boundingDimensions.z)]},i.utilityLayerScene)),s.push(Jn.a.CreateLines("lines",{points:[new o.x(n._boundingDimensions.x,n._boundingDimensions.y,n._boundingDimensions.z),new o.x(n._boundingDimensions.x,n._boundingDimensions.y,0)]},i.utilityLayerScene)),s.forEach(function(e){e.color=t,e.position.addInPlace(new o.x(-n._boundingDimensions.x/2,-n._boundingDimensions.y/2,-n._boundingDimensions.z/2)),e.isPickable=!1,n._lineBoundingBox.addChild(e)}),n._rootMesh.addChild(n._lineBoundingBox),n.setColor(t),n._rotateSpheresParent=new Fe.a("",i.utilityLayerScene),n._rotateSpheresParent.rotationQuaternion=new o.q;for(var a=function(e){var t=Zn.a.CreateSphere("",{diameter:1},i.utilityLayerScene);t.rotationQuaternion=new o.q,t.material=c.coloredMaterial,(d=new Le.a({})).moveAttached=!1,d.updateDragPlane=!1,t.addBehavior(d);var r=new o.x(1,0,0),s=0;d.onDragStartObservable.add(function(){r.copyFrom(t.forward),s=0}),d.onDragObservable.add(function(t){if(n.onRotationSphereDragObservable.notifyObservers({}),n.attachedMesh){var i=n.attachedMesh.parent;if(i&&i.scaling&&i.scaling.isNonUniformWithinEpsilon(.001))return void p.a.Warn("BoundingBoxGizmo controls are not supported on child meshes with non-uniform parent scaling");Be.a._RemoveAndStorePivotPoint(n.attachedMesh);var a=r,c=t.dragPlaneNormal.scale(o.x.Dot(t.dragPlaneNormal,a)),l=a.subtract(c).normalizeToNew(),u=o.x.Dot(l,t.delta)<0?Math.abs(t.delta.length()):-Math.abs(t.delta.length());u=u/n._boundingDimensions.length()*n._anchorMesh.scaling.length(),n.attachedMesh.rotationQuaternion||(n.attachedMesh.rotationQuaternion=o.q.RotationYawPitchRoll(n.attachedMesh.rotation.y,n.attachedMesh.rotation.x,n.attachedMesh.rotation.z)),n._anchorMesh.rotationQuaternion||(n._anchorMesh.rotationQuaternion=o.q.RotationYawPitchRoll(n._anchorMesh.rotation.y,n._anchorMesh.rotation.x,n._anchorMesh.rotation.z)),s+=u,Math.abs(s)<=2*Math.PI&&(e>=8?o.q.RotationYawPitchRollToRef(0,0,u,n._tmpQuaternion):e>=4?o.q.RotationYawPitchRollToRef(u,0,0,n._tmpQuaternion):o.q.RotationYawPitchRollToRef(0,u,0,n._tmpQuaternion),n._anchorMesh.addChild(n.attachedMesh),n._anchorMesh.rotationQuaternion.multiplyToRef(n._tmpQuaternion,n._anchorMesh.rotationQuaternion),n._anchorMesh.removeChild(n.attachedMesh),n.attachedMesh.setParent(i)),n.updateBoundingBox(),Be.a._RestorePivotPoint(n.attachedMesh)}n._updateDummy()}),d.onDragStartObservable.add(function(){n.onDragStartObservable.notifyObservers({}),n._selectNode(t)}),d.onDragEndObservable.add(function(){n.onRotationSphereDragEndObservable.notifyObservers({}),n._selectNode(null),n._updateDummy()}),c._rotateSpheresParent.addChild(t)},c=this,l=0;l<12;l++)a(l);n._rootMesh.addChild(n._rotateSpheresParent),n._scaleBoxesParent=new Fe.a("",i.utilityLayerScene),n._scaleBoxesParent.rotationQuaternion=new o.q;for(var u=0;u<2;u++)for(var h=0;h<2;h++)for(var d,f=function(){var e=Yn.a.CreateBox("",{size:1},i.utilityLayerScene);e.material=_.coloredMaterial;var t=new o.x(0==u?-1:1,0==h?-1:1,0==m?-1:1);(d=new Le.a({dragAxis:t})).moveAttached=!1,e.addBehavior(d),d.onDragObservable.add(function(t){if(n.onScaleBoxDragObservable.notifyObservers({}),n.attachedMesh){var i=n.attachedMesh.parent;if(i&&i.scaling&&i.scaling.isNonUniformWithinEpsilon(.001))return void p.a.Warn("BoundingBoxGizmo controls are not supported on child meshes with non-uniform parent scaling");Be.a._RemoveAndStorePivotPoint(n.attachedMesh);var r=t.dragDistance/n._boundingDimensions.length()*n._anchorMesh.scaling.length(),s=new o.x(r,r,r);s.scaleInPlace(n._scaleDragSpeed),n.updateBoundingBox(),n.scalePivot?(n.attachedMesh.getWorldMatrix().getRotationMatrixToRef(n._tmpRotationMatrix),n._boundingDimensions.scaleToRef(.5,n._tmpVector),o.x.TransformCoordinatesToRef(n._tmpVector,n._tmpRotationMatrix,n._tmpVector),n._anchorMesh.position.subtractInPlace(n._tmpVector),n._boundingDimensions.multiplyToRef(n.scalePivot,n._tmpVector),o.x.TransformCoordinatesToRef(n._tmpVector,n._tmpRotationMatrix,n._tmpVector),n._anchorMesh.position.addInPlace(n._tmpVector)):(e.absolutePosition.subtractToRef(n._anchorMesh.position,n._tmpVector),n._anchorMesh.position.subtractInPlace(n._tmpVector)),n._anchorMesh.addChild(n.attachedMesh),n._anchorMesh.scaling.addInPlace(s),(n._anchorMesh.scaling.x<0||n._anchorMesh.scaling.y<0||n._anchorMesh.scaling.z<0)&&n._anchorMesh.scaling.subtractInPlace(s),n._anchorMesh.removeChild(n.attachedMesh),n.attachedMesh.setParent(i),Be.a._RestorePivotPoint(n.attachedMesh)}n._updateDummy()}),d.onDragStartObservable.add(function(){n.onDragStartObservable.notifyObservers({}),n._selectNode(e)}),d.onDragEndObservable.add(function(){n.onScaleBoxDragEndObservable.notifyObservers({}),n._selectNode(null),n._updateDummy()}),_._scaleBoxesParent.addChild(e)},_=this,m=0;m<2;m++)f();n._rootMesh.addChild(n._scaleBoxesParent);var g=new Array;return n._pointerObserver=i.utilityLayerScene.onPointerObservable.add(function(e){g[e.event.pointerId]?e.pickInfo&&e.pickInfo.pickedMesh!=g[e.event.pointerId]&&(g[e.event.pointerId].material=n.coloredMaterial,delete g[e.event.pointerId]):n._rotateSpheresParent.getChildMeshes().concat(n._scaleBoxesParent.getChildMeshes()).forEach(function(t){e.pickInfo&&e.pickInfo.pickedMesh==t&&(g[e.event.pointerId]=t,t.material=n.hoverColoredMaterial)})}),n._renderObserver=n.gizmoLayer.originalScene.onBeforeRenderObservable.add(function(){n.attachedMesh&&!n._existingMeshScale.equals(n.attachedMesh.scaling)?n.updateBoundingBox():n.fixedDragMeshScreenSize&&(n._updateRotationSpheres(),n._updateScaleBoxes()),n._dragMesh&&n.attachedMesh&&n.pointerDragBehavior.dragging&&(n._lineBoundingBox.position.rotateByQuaternionToRef(n._rootMesh.rotationQuaternion,n._tmpVector),n.attachedMesh.setAbsolutePosition(n._dragMesh.position.add(n._tmpVector.scale(-1))))}),n.updateBoundingBox(),n}return l.d(t,e),t.prototype.setColor=function(e){this.coloredMaterial.emissiveColor=e,this.hoverColoredMaterial.emissiveColor=e.clone().add(new o.e(.3,.3,.3)),this._lineBoundingBox.getChildren().forEach(function(t){t.color&&(t.color=e)})},t.prototype._attachedMeshChanged=function(e){var t=this;if(e){Be.a._RemoveAndStorePivotPoint(e);var i=e.parent;this._anchorMesh.addChild(e),this._anchorMesh.removeChild(e),e.setParent(i),Be.a._RestorePivotPoint(e),this.updateBoundingBox(),e.getChildMeshes(!1).forEach(function(e){e.markAsDirty("scaling")}),this.gizmoLayer.utilityLayerScene.onAfterRenderObservable.addOnce(function(){t._updateDummy()})}},t.prototype._selectNode=function(e){this._rotateSpheresParent.getChildMeshes().concat(this._scaleBoxesParent.getChildMeshes()).forEach(function(t){t.isVisible=!e||t==e})},t.prototype.updateBoundingBox=function(){if(this.attachedMesh){Be.a._RemoveAndStorePivotPoint(this.attachedMesh);var e=this.attachedMesh.parent;this.attachedMesh.setParent(null);var t=null;this.attachedMesh.skeleton&&(t=this.attachedMesh.skeleton.overrideMesh,this.attachedMesh.skeleton.overrideMesh=null),this._update(),this.attachedMesh.rotationQuaternion||(this.attachedMesh.rotationQuaternion=o.q.RotationYawPitchRoll(this.attachedMesh.rotation.y,this.attachedMesh.rotation.x,this.attachedMesh.rotation.z)),this._anchorMesh.rotationQuaternion||(this._anchorMesh.rotationQuaternion=o.q.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=t)}this._updateRotationSpheres(),this._updateScaleBoxes(),this.attachedMesh&&(this._existingMeshScale.copyFrom(this.attachedMesh.scaling),Be.a._RestorePivotPoint(this.attachedMesh))},t.prototype._updateRotationSpheres=function(){for(var e=this._rotateSpheresParent.getChildMeshes(),t=0;t<3;t++)for(var i=0;i<2;i++)for(var n=0;n<2;n++){var r=4*t+2*i+n;if(0==t&&(e[r].position.set(this._boundingDimensions.x/2,this._boundingDimensions.y*i,this._boundingDimensions.z*n),e[r].position.addInPlace(new o.x(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),e[r].lookAt(o.x.Cross(e[r].position.normalizeToNew(),o.x.Right()).normalizeToNew().add(e[r].position))),1==t&&(e[r].position.set(this._boundingDimensions.x*i,this._boundingDimensions.y/2,this._boundingDimensions.z*n),e[r].position.addInPlace(new o.x(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),e[r].lookAt(o.x.Cross(e[r].position.normalizeToNew(),o.x.Up()).normalizeToNew().add(e[r].position))),2==t&&(e[r].position.set(this._boundingDimensions.x*i,this._boundingDimensions.y*n,this._boundingDimensions.z/2),e[r].position.addInPlace(new o.x(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),e[r].lookAt(o.x.Cross(e[r].position.normalizeToNew(),o.x.Forward()).normalizeToNew().add(e[r].position))),this.fixedDragMeshScreenSize&&this.gizmoLayer.utilityLayerScene.activeCamera){e[r].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position,this._tmpVector);var s=this.rotationSphereSize*this._tmpVector.length()/this.fixedDragMeshScreenSizeDistanceFactor;e[r].scaling.set(s,s,s)}else e[r].scaling.set(this.rotationSphereSize,this.rotationSphereSize,this.rotationSphereSize)}},t.prototype._updateScaleBoxes=function(){for(var e=this._scaleBoxesParent.getChildMeshes(),t=0;t<2;t++)for(var i=0;i<2;i++)for(var n=0;n<2;n++){var r=4*t+2*i+n;if(e[r])if(e[r].position.set(this._boundingDimensions.x*t,this._boundingDimensions.y*i,this._boundingDimensions.z*n),e[r].position.addInPlace(new o.x(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),this.fixedDragMeshScreenSize&&this.gizmoLayer.utilityLayerScene.activeCamera){e[r].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position,this._tmpVector);var s=this.scaleBoxSize*this._tmpVector.length()/this.fixedDragMeshScreenSizeDistanceFactor;e[r].scaling.set(s,s,s)}else e[r].scaling.set(this.scaleBoxSize,this.scaleBoxSize,this.scaleBoxSize)}},t.prototype.setEnabledRotationAxis=function(e){this._rotateSpheresParent.getChildMeshes().forEach(function(t,i){i<4?t.setEnabled(-1!=e.indexOf("x")):i<8?t.setEnabled(-1!=e.indexOf("y")):t.setEnabled(-1!=e.indexOf("z"))})},t.prototype.setEnabledScaling=function(e){this._scaleBoxesParent.getChildMeshes().forEach(function(t,i){t.setEnabled(e)})},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=fe.a.CreateBox("dummy",1,this.gizmoLayer.utilityLayerScene),this._dragMesh.visibility=0,this._dragMesh.rotationQuaternion=new o.q,this.pointerDragBehavior.useObjectOrienationForDragging=!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(),e.prototype.dispose.call(this)},t.MakeNotPickableAndWrapInBoundingBox=function(e){var t=function(e){e.isPickable=!1,e.getChildMeshes().forEach(function(e){t(e)})};t(e),e.rotationQuaternion||(e.rotationQuaternion=o.q.RotationYawPitchRoll(e.rotation.y,e.rotation.x,e.rotation.z));var i=e.position.clone(),n=e.rotationQuaternion.clone();e.rotationQuaternion.set(0,0,0,1),e.position.set(0,0,0);var r=Yn.a.CreateBox("box",{size:1},e.getScene()),s=e.getHierarchyBoundingVectors();return s.max.subtractToRef(s.min,r.scaling),0===r.scaling.y&&(r.scaling.y=o.h),0===r.scaling.x&&(r.scaling.x=o.h),0===r.scaling.z&&(r.scaling.z=o.h),r.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(r),e.rotationQuaternion.copyFrom(n),e.position.copyFrom(i),e.removeChild(r),r.addChild(e),r.visibility=0,r},t.prototype.setCustomMesh=function(e){p.a.Error("Custom meshes are not supported on this gizmo")},t}(Kn.a),er=function(e){function t(t,i,n,s,a){void 0===i&&(i=o.e.Gray()),void 0===n&&(n=Qn.a.DefaultUtilityLayer),void 0===s&&(s=32),void 0===a&&(a=null);var c=e.call(this,n)||this;c._pointerObserver=null,c.snapDistance=0,c.onSnapObservable=new r.c,c._isEnabled=!0,c._parent=null,c._parent=a;var l=new Pi.a("",n.utilityLayerScene);l.diffuseColor=i,l.specularColor=i.subtract(new o.e(.1,.1,.1));var u=new Pi.a("",n.utilityLayerScene);u.diffuseColor=i.add(new o.e(.3,.3,.3));var h=new Fe.a("",n.utilityLayerScene),d=fe.a.CreateTorus("",.6,.03,s,n.utilityLayerScene);d.visibility=0;var f=fe.a.CreateTorus("",.6,.005,s,n.utilityLayerScene);f.material=l,f.rotation.x=Math.PI/2,d.rotation.x=Math.PI/2,h.addChild(f),h.addChild(d),h.lookAt(c._rootMesh.position.add(t)),c._rootMesh.addChild(h),h.scaling.scaleInPlace(1/3),c.dragBehavior=new Le.a({dragPlaneNormal:t}),c.dragBehavior.moveAttached=!1,c.dragBehavior.maxDragAngle=9*Math.PI/20,c.dragBehavior._useAlternatePickedPointAboveMaxDragAngle=!0,c._rootMesh.addBehavior(c.dragBehavior);var p=new o.x;c.dragBehavior.onDragStartObservable.add(function(e){c.attachedMesh&&p.copyFrom(e.dragPlanePoint)});var _=new o.j,m=new o.x,g=new o.x,v={snapDistance:0},y=0,b=new o.j,T=new o.x,E=new o.q;c.dragBehavior.onDragObservable.add(function(e){if(c.attachedMesh){c.attachedMesh.rotationQuaternion||(c.attachedMesh.rotationQuaternion=o.q.RotationYawPitchRoll(c.attachedMesh.rotation.y,c.attachedMesh.rotation.x,c.attachedMesh.rotation.z));var i=c.attachedMesh.parent;i&&c.attachedMesh.setParent(null);var r=e.dragPlanePoint.subtract(c.attachedMesh.absolutePosition).normalize(),s=p.subtract(c.attachedMesh.absolutePosition).normalize(),a=o.x.Cross(r,s),l=o.x.Dot(r,s),u=Math.atan2(a.length(),l);if(m.copyFrom(t),g.copyFrom(t),c.updateGizmoRotationToMatchAttachedMesh&&(c.attachedMesh.rotationQuaternion.toRotationMatrix(_),g=o.x.TransformCoordinates(m,_)),n.utilityLayerScene.activeCamera){var h=n.utilityLayerScene.activeCamera.position.subtract(c.attachedMesh.position);o.x.Dot(h,g)>0&&(m.scaleInPlace(-1),g.scaleInPlace(-1))}o.x.Dot(g,a)>0&&(u=-u);var d=!1;if(0!=c.snapDistance)if(y+=u,Math.abs(y)>c.snapDistance){var f=Math.floor(Math.abs(y)/c.snapDistance);y<0&&(f*=-1),y%=c.snapDistance,u=c.snapDistance*f,d=!0}else u=0;b.reset(),c.attachedMesh.parent&&(c.attachedMesh.parent.computeWorldMatrix().invertToRef(b),b.getRotationMatrixToRef(b),o.x.TransformCoordinatesToRef(m,b,m));var x=Math.sin(u/2);E.set(m.x*x,m.y*x,m.z*x,Math.cos(u/2)),b.determinant()>0&&(E.toEulerAnglesToRef(T),o.q.RotationYawPitchRollToRef(T.y,-T.x,-T.z,E)),c.updateGizmoRotationToMatchAttachedMesh?c.attachedMesh.rotationQuaternion.multiplyToRef(E,c.attachedMesh.rotationQuaternion):E.multiplyToRef(c.attachedMesh.rotationQuaternion,c.attachedMesh.rotationQuaternion),p.copyFrom(e.dragPlanePoint),d&&(v.snapDistance=u,c.onSnapObservable.notifyObservers(v)),i&&c.attachedMesh.setParent(i)}}),c._pointerObserver=n.utilityLayerScene.onPointerObservable.add(function(e){if(!c._customMeshSet){var t=e.pickInfo&&-1!=c._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh)?u:l;c._rootMesh.getChildMeshes().forEach(function(e){e.material=t,e.color&&(e.color=t.diffuseColor)})}});var x=n._getSharedGizmoLight();return x.includedOnlyMeshes=x.includedOnlyMeshes.concat(c._rootMesh.getChildMeshes(!1)),c}return l.d(t,e),t.prototype._attachedMeshChanged=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.attachedMesh=null},enumerable:!0,configurable:!0}),t.prototype.dispose=function(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),e.prototype.dispose.call(this)},t}(Kn.a),tr=function(e){function t(t,i){void 0===t&&(t=Qn.a.DefaultUtilityLayer),void 0===i&&(i=32);var n=e.call(this,t)||this;return n.onDragStartObservable=new r.c,n.onDragEndObservable=new r.c,n.xGizmo=new er(new o.x(1,0,0),o.e.Red().scale(.5),t,i,n),n.yGizmo=new er(new o.x(0,1,0),o.e.Green().scale(.5),t,i,n),n.zGizmo=new er(new o.x(0,0,1),o.e.Blue().scale(.5),t,i,n),[n.xGizmo,n.yGizmo,n.zGizmo].forEach(function(e){e.dragBehavior.onDragStartObservable.add(function(){n.onDragStartObservable.notifyObservers({})}),e.dragBehavior.onDragEndObservable.add(function(){n.onDragEndObservable.notifyObservers({})})}),n.attachedMesh=null,n}return l.d(t,e),Object.defineProperty(t.prototype,"attachedMesh",{get:function(){return this._meshAttached},set:function(e){this._meshAttached=e,[this.xGizmo,this.yGizmo,this.zGizmo].forEach(function(t){t.isEnabled?t.attachedMesh=e:t.attachedMesh=null})},enumerable:!0,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:!0,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:!0,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:!0,configurable:!0}),t.prototype.dispose=function(){this.xGizmo.dispose(),this.yGizmo.dispose(),this.zGizmo.dispose(),this.onDragStartObservable.clear(),this.onDragEndObservable.clear()},t.prototype.setCustomMesh=function(e){p.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}(Kn.a),ir=i(39),nr=i(73),rr=function(e){function t(i,n,s,a){void 0===n&&(n=o.e.Gray()),void 0===s&&(s=Qn.a.DefaultUtilityLayer),void 0===a&&(a=null);var c=e.call(this,s)||this;c._pointerObserver=null,c.snapDistance=0,c.onSnapObservable=new r.c,c._isEnabled=!1,c._parent=null,c._parent=a,c._coloredMaterial=new Pi.a("",s.utilityLayerScene),c._coloredMaterial.diffuseColor=n,c._coloredMaterial.specularColor=n.subtract(new o.e(.1,.1,.1)),c._hoverMaterial=new Pi.a("",s.utilityLayerScene),c._hoverMaterial.diffuseColor=n.add(new o.e(.3,.3,.3)),c._plane=t._CreatePlane(s.utilityLayerScene,c._coloredMaterial),c._plane.lookAt(c._rootMesh.position.add(i)),c._plane.scaling.scaleInPlace(1/3),c._plane.parent=c._rootMesh;var l=0,u=new o.x,h={snapDistance:0};c.dragBehavior=new Le.a({dragPlaneNormal:i}),c.dragBehavior.moveAttached=!1,c._rootMesh.addBehavior(c.dragBehavior);var d=new o.x,f=new o.j;c.dragBehavior.onDragObservable.add(function(e){if(c.attachedMesh)if(c.attachedMesh.parent?(c.attachedMesh.parent.computeWorldMatrix().invertToRef(f),f.setTranslationFromFloats(0,0,0),o.x.TransformCoordinatesToRef(e.delta,f,d)):d.copyFrom(e.delta),0==c.snapDistance)c.attachedMesh.position.addInPlace(d);else if(l+=e.dragDistance,Math.abs(l)>c.snapDistance){var t=Math.floor(Math.abs(l)/c.snapDistance);l%=c.snapDistance,d.normalizeToRef(u),u.scaleInPlace(c.snapDistance*t),c.attachedMesh.position.addInPlace(u),h.snapDistance=c.snapDistance*t,c.onSnapObservable.notifyObservers(h)}}),c._pointerObserver=s.utilityLayerScene.onPointerObservable.add(function(e){if(!c._customMeshSet){var t=e.pickInfo&&-1!=c._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh)?c._hoverMaterial:c._coloredMaterial;c._rootMesh.getChildMeshes().forEach(function(e){e.material=t})}});var p=s._getSharedGizmoLight();return p.includedOnlyMeshes=p.includedOnlyMeshes.concat(c._rootMesh.getChildMeshes(!1)),c}return l.d(t,e),t._CreatePlane=function(e,t){var i=new ir.a("plane",e),n=nr.a.CreatePlane("dragPlane",{width:.1375,height:.1375,sideOrientation:2},e);return n.material=t,n.parent=i,n.material=t,i},t._CreateArrowInstance=function(e,t){for(var i=new ir.a("arrow",e),n=0,r=t.getChildMeshes();n=t.length)?0:e.type||0,u=e.size,h=e.sizeX||u||1,d=e.sizeY||u||1,f=e.sizeZ||u||1,p=e.custom||t[l],_=p.face.length,m=e.faceUV||new Array(_),g=e.faceColors,v=void 0===e.flat||e.flat,y=0===e.sideOrientation?0:e.sideOrientation||Mi.a.DEFAULTSIDE,b=new Array,T=new Array,E=new Array,x=new Array,A=new Array,P=0,R=0,S=new Array,C=0,M=0;if(v)for(M=0;M<_;M++)g&&void 0===g[M]&&(g[M]=new o.f(1,1,1,1)),m&&void 0===m[M]&&(m[M]=new o.y(0,0,1,1));if(v)for(M=0;M<_;M++){var O=p.face[M].length;for(r=2*Math.PI/O,s=.5*Math.tan(r/2),a=.5,C=0;C0?this._setDefaultFixedFrustumShadowProjectionMatrix(e):this._setDefaultAutoExtendShadowProjectionMatrix(e,t,i)},t.prototype._setDefaultFixedFrustumShadowProjectionMatrix=function(e){var t=this.getScene().activeCamera;t&&o.j.OrthoLHToRef(this.shadowFrustumSize,this.shadowFrustumSize,void 0!==this.shadowMinZ?this.shadowMinZ:t.minZ,void 0!==this.shadowMaxZ?this.shadowMaxZ:t.maxZ,e)},t.prototype._setDefaultAutoExtendShadowProjectionMatrix=function(e,t,i){var n=this.getScene().activeCamera;if(n){if(this.autoUpdateExtends||this._orthoLeft===Number.MAX_VALUE){var r=o.x.Zero();this._orthoLeft=Number.MAX_VALUE,this._orthoRight=Number.MIN_VALUE,this._orthoTop=Number.MIN_VALUE,this._orthoBottom=Number.MAX_VALUE;for(var s=0;sthis._orthoRight&&(this._orthoRight=r.x),r.y>this._orthoTop&&(this._orthoTop=r.y)}}var u=this._orthoRight-this._orthoLeft,h=this._orthoTop-this._orthoBottom;o.j.OrthoOffCenterLHToRef(this._orthoLeft-u*this.shadowOrthoScale,this._orthoRight+u*this.shadowOrthoScale,this._orthoBottom-h*this.shadowOrthoScale,this._orthoTop+h*this.shadowOrthoScale,void 0!==this.shadowMinZ?this.shadowMinZ:n.minZ,void 0!==this.shadowMaxZ?this.shadowMaxZ:n.maxZ,e)}},t.prototype._buildUniformLayout=function(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",3),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()},t.prototype.transferToEffect=function(e,t){return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z,1,t),this):(this._uniformBuffer.updateFloat4("vLightData",this.direction.x,this.direction.y,this.direction.z,1,t),this)},t.prototype.getDepthMinZ=function(e){return 1},t.prototype.getDepthMaxZ=function(e){return 1},t.prototype.prepareLightSpecificDefines=function(e,t){e["DIRLIGHT"+t]=!0},l.c([Object(L.c)()],t.prototype,"shadowFrustumSize",null),l.c([Object(L.c)()],t.prototype,"shadowOrthoScale",null),l.c([Object(L.c)()],t.prototype,"autoUpdateExtends",void 0),t}(ur);fe.a.CreateHemisphere=function(e,t,i,n){var r={segments:t,diameter:i};return dr.CreateHemisphere(e,r,n)};var dr=function(){function e(){}return e.CreateHemisphere=function(e,t,i){t.diameter||(t.diameter=1),t.segments||(t.segments=16);var n=Zn.a.CreateSphere("",{slice:.5,diameter:t.diameter,segments:t.segments},i),r=fe.a.CreateDisc("",t.diameter/2,3*t.segments+(4-t.segments),i);r.rotation.x=-Math.PI/2,r.parent=n;var o=fe.a.MergeMeshes([r,n],!0);return o.name=e,o},e}();F.a.AddNodeConstructor("Light_Type_2",function(e,t){return function(){return new fr(e,o.x.Zero(),o.x.Zero(),0,0,t)}});var fr=function(e){function t(t,i,n,r,s,a){var c=e.call(this,t,a)||this;return c._innerAngle=0,c._projectionTextureMatrix=o.j.Zero(),c._projectionTextureLightNear=1e-6,c._projectionTextureLightFar=1e3,c._projectionTextureUpDirection=o.x.Up(),c._projectionTextureViewLightDirty=!0,c._projectionTextureProjectionLightDirty=!0,c._projectionTextureDirty=!0,c._projectionTextureViewTargetVector=o.x.Zero(),c._projectionTextureViewLightMatrix=o.j.Zero(),c._projectionTextureProjectionLightMatrix=o.j.Zero(),c._projectionTextureScalingMatrix=o.j.FromValues(.5,0,0,0,0,.5,0,0,0,0,.5,0,.5,.5,.5,1),c.position=i,c.direction=n,c.angle=r,c.exponent=s,c}return l.d(t,e),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:!0,configurable:!0}),Object.defineProperty(t.prototype,"innerAngle",{get:function(){return this._innerAngle},set:function(e){this._innerAngle=e,this._computeAngleValues()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"shadowAngleScale",{get:function(){return this._shadowAngleScale},set:function(e){this._shadowAngleScale=e,this.forceProjectionMatrixCompute()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"projectionTextureMatrix",{get:function(){return this._projectionTextureMatrix},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"projectionTextureLightNear",{get:function(){return this._projectionTextureLightNear},set:function(e){this._projectionTextureLightNear=e,this._projectionTextureProjectionLightDirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"projectionTextureLightFar",{get:function(){return this._projectionTextureLightFar},set:function(e){this._projectionTextureLightFar=e,this._projectionTextureProjectionLightDirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"projectionTextureUpDirection",{get:function(){return this._projectionTextureUpDirection},set:function(e){this._projectionTextureUpDirection=e,this._projectionTextureProjectionLightDirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"projectionTexture",{get:function(){return this._projectionTexture},set:function(e){var t=this;if(this._projectionTexture!==e&&(this._projectionTexture=e,this._projectionTextureDirty=!0,this._projectionTexture&&!this._projectionTexture.isReady())){var i=this._projectionTexture;i.onLoadObservable&&i.onLoadObservable.addOnce(function(){t._markMeshesAsLightDirty()})}},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"SpotLight"},t.prototype.getTypeID=function(){return lr.a.LIGHTTYPEID_SPOTLIGHT},t.prototype._setDirection=function(t){e.prototype._setDirection.call(this,t),this._projectionTextureViewLightDirty=!0},t.prototype._setPosition=function(t){e.prototype._setPosition.call(this,t),this._projectionTextureViewLightDirty=!0},t.prototype._setDefaultShadowProjectionMatrix=function(e,t,i){var n=this.getScene().activeCamera;if(n){this._shadowAngleScale=this._shadowAngleScale||1;var r=this._shadowAngleScale*this._angle;o.j.PerspectiveFovLHToRef(r,1,this.getDepthMinZ(n),this.getDepthMaxZ(n),e)}},t.prototype._computeProjectionTextureViewLightMatrix=function(){this._projectionTextureViewLightDirty=!1,this._projectionTextureDirty=!0,this.position.addToRef(this.direction,this._projectionTextureViewTargetVector),o.j.LookAtLHToRef(this.position,this._projectionTextureViewTargetVector,this._projectionTextureUpDirection,this._projectionTextureViewLightMatrix)},t.prototype._computeProjectionTextureProjectionLightMatrix=function(){this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0;var e=this.projectionTextureLightFar,t=this.projectionTextureLightNear,i=e/(e-t),n=-i*t,r=1/Math.tan(this._angle/2);o.j.FromValuesToRef(r/1,0,0,0,0,r,0,0,0,0,i,1,0,0,n,0,this._projectionTextureProjectionLightMatrix)},t.prototype._computeProjectionTextureMatrix=function(){this._projectionTextureDirty=!1,this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix,this._projectionTextureMatrix),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",3),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.transferToEffect=function(e,t){var i;return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,this.exponent,t),i=o.x.Normalize(this.transformedDirection)):(this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,this.exponent,t),i=o.x.Normalize(this.direction)),this._uniformBuffer.updateFloat4("vLightDirection",i.x,i.y,i.z,this._cosHalfAngle,t),this._uniformBuffer.updateFloat4("vLightFalloff",this.range,this._inverseSquaredRange,this._lightAngleScale,this._lightAngleOffset,t),this.projectionTexture&&this.projectionTexture.isReady()&&(this._projectionTextureViewLightDirty&&this._computeProjectionTextureViewLightMatrix(),this._projectionTextureProjectionLightDirty&&this._computeProjectionTextureProjectionLightMatrix(),this._projectionTextureDirty&&this._computeProjectionTextureMatrix(),e.setMatrix("textureProjectionMatrix"+t,this._projectionTextureMatrix),e.setTexture("projectionLightSampler"+t,this.projectionTexture)),this},t.prototype.dispose=function(){e.prototype.dispose.call(this),this._projectionTexture&&this._projectionTexture.dispose()},t.prototype.prepareLightSpecificDefines=function(e,t){e["SPOTLIGHT"+t]=!0,e["PROJECTEDLIGHTTEXTURE"+t]=!(!this.projectionTexture||!this.projectionTexture.isReady())},l.c([Object(L.c)()],t.prototype,"angle",null),l.c([Object(L.c)()],t.prototype,"innerAngle",null),l.c([Object(L.c)()],t.prototype,"shadowAngleScale",null),l.c([Object(L.c)()],t.prototype,"exponent",void 0),l.c([Object(L.c)()],t.prototype,"projectionTextureLightNear",null),l.c([Object(L.c)()],t.prototype,"projectionTextureLightFar",null),l.c([Object(L.c)()],t.prototype,"projectionTextureUpDirection",null),l.c([Object(L.m)("projectedLightTexture")],t.prototype,"_projectionTexture",void 0),t}(ur),pr=function(e){function t(t){var i=e.call(this,t)||this;return i.cachedPosition=new o.x,i.cachedForward=new o.x(0,0,1),i._light=null,i.attachedMesh=new Fe.a("",i.gizmoLayer.utilityLayerScene),i._material=new Pi.a("light",i.gizmoLayer.originalScene),i._material.diffuseColor=new o.e(.5,.5,.5),i._material.specularColor=new o.e(.1,.1,.1),i}return l.d(t,e),Object.defineProperty(t.prototype,"light",{get:function(){return this._light},set:function(e){var i=this;if(this._light=e,e){this._lightMesh&&this._lightMesh.dispose(),e instanceof Ti.a?this._lightMesh=t._CreateHemisphericLightMesh(this.gizmoLayer.utilityLayerScene):this._lightMesh=e instanceof hr?t._CreateDirectionalLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof fr?t._CreateSpotLightMesh(this.gizmoLayer.utilityLayerScene):t._CreatePointLightMesh(this.gizmoLayer.utilityLayerScene),this._lightMesh.getChildMeshes(!1).forEach(function(e){e.material=i._material}),this._lightMesh.parent=this._rootMesh;var n=this.gizmoLayer._getSharedGizmoLight();n.includedOnlyMeshes=n.includedOnlyMeshes.concat(this._lightMesh.getChildMeshes(!1)),this._lightMesh.rotationQuaternion=new o.q,this.attachedMesh.reservedDataStore||(this.attachedMesh.reservedDataStore={}),this.attachedMesh.reservedDataStore.lightGizmo=this,e.position&&this.attachedMesh.position.copyFrom(e.position),e.direction&&this.attachedMesh.setDirection(e.direction),this._update()}},enumerable:!0,configurable:!0}),t.prototype._update=function(){e.prototype._update.call(this),this._light&&(this._light.position&&(this.attachedMesh.position.equals(this.cachedPosition)?this.attachedMesh.position.copyFrom(this._light.position):(this._light.position.copyFrom(this.attachedMesh.position),this.cachedPosition.copyFrom(this.attachedMesh.position))),this._light.direction&&(o.x.DistanceSquared(this.attachedMesh.forward,this.cachedForward)>1e-4?(this._light.direction.copyFrom(this.attachedMesh.forward),this.cachedForward.copyFrom(this.attachedMesh.forward)):o.x.DistanceSquared(this.attachedMesh.forward,this._light.direction)>1e-4&&(this.attachedMesh.setDirection(this._light.direction),this.cachedForward.copyFrom(this._lightMesh.forward))),this._light.isEnabled()?this._material.diffuseColor.set(this._light.diffuse.r/3,this._light.diffuse.g/3,this._light.diffuse.b/3):this._material.diffuseColor.set(0,0,0))},t.prototype.dispose=function(){this._material.dispose(),e.prototype.dispose.call(this)},t._CreateHemisphericLightMesh=function(e){var i=new fe.a("hemisphereLight",e),n=dr.CreateHemisphere(i.name,{segments:10,diameter:1},e);n.position.z=-.15,n.rotation.x=Math.PI/2,n.parent=i;var r=this._createLightLines(3,e);return r.parent=i,r.position.z,i.scaling.scaleInPlace(t._Scale),i.rotation.x=Math.PI/2,i},t._CreatePointLightMesh=function(e){var i=new fe.a("pointLight",e),n=Zn.a.CreateSphere(i.name,{segments:10,diameter:1},e);return n.rotation.x=Math.PI/2,n.parent=i,this._createLightLines(5,e).parent=i,i.scaling.scaleInPlace(t._Scale),i.rotation.x=Math.PI/2,i},t._CreateSpotLightMesh=function(e){var i=new fe.a("spotLight",e);Zn.a.CreateSphere(i.name,{segments:10,diameter:1},e).parent=i;var n=dr.CreateHemisphere(i.name,{segments:10,diameter:2},e);return n.parent=i,n.rotation.x=-Math.PI/2,this._createLightLines(2,e).parent=i,i.scaling.scaleInPlace(t._Scale),i.rotation.x=Math.PI/2,i},t._CreateDirectionalLightMesh=function(e){var i=new fe.a("directionalLight",e),n=new fe.a(i.name,e);n.parent=i,Zn.a.CreateSphere(i.name,{diameter:1.2,segments:10},e).parent=n;var r=fe.a.CreateCylinder(i.name,6,.3,.3,6,1,e);r.parent=n,(o=r.clone(i.name)).scaling.y=.5,o.position.x+=1.25,(s=r.clone(i.name)).scaling.y=.5,s.position.x+=-1.25;var o,s,a=fe.a.CreateCylinder(i.name,1,0,.6,6,1,e);return a.position.y+=3,a.parent=n,(o=a.clone(i.name)).position.y=1.5,o.position.x+=1.25,(s=a.clone(i.name)).position.y=1.5,s.position.x+=-1.25,n.scaling.scaleInPlace(t._Scale),n.rotation.z=Math.PI/2,n.rotation.y=Math.PI/2,i},t._Scale=.007,t._createLightLines=function(e,t){var i=new fe.a("root",t);i.rotation.x=Math.PI/2;var n=new fe.a("linePivot",t);n.parent=i;var r=fe.a.CreateCylinder("line",2,.2,.3,6,1,t);if(r.position.y=r.scaling.y/2+1.2,r.parent=n,e<2)return n;for(var o=0;o<4;o++){(s=n.clone("lineParentClone")).rotation.z=Math.PI/4,s.rotation.y=Math.PI/2+Math.PI/2*o,s.getChildMeshes()[0].scaling.y=.5,s.getChildMeshes()[0].scaling.x=s.getChildMeshes()[0].scaling.z=.8,s.getChildMeshes()[0].position.y=s.getChildMeshes()[0].scaling.y/2+1.2}if(e<3)return i;for(o=0;o<4;o++){(s=n.clone("linePivotClone")).rotation.z=Math.PI/2,s.rotation.y=Math.PI/2*o}if(e<4)return i;for(o=0;o<4;o++){var s;(s=n.clone("linePivotClone")).rotation.z=Math.PI+Math.PI/4,s.rotation.y=Math.PI/2+Math.PI/2*o,s.getChildMeshes()[0].scaling.y=.5,s.getChildMeshes()[0].scaling.x=s.getChildMeshes()[0].scaling.z=.8,s.getChildMeshes()[0].position.y=s.getChildMeshes()[0].scaling.y/2+1.2}return e<5?i:((s=n.clone("linePivotClone")).rotation.z=Math.PI,i)},t}(Kn.a);zt.a.IncludesShadersStore.kernelBlurVaryingDeclaration="varying vec2 sampleCoord{X};";var _r="#ifdef DOF\nfactor=sampleCoC(sampleCoord{X});\ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif";zt.a.IncludesShadersStore.kernelBlurFragment=_r;var mr="#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif";zt.a.IncludesShadersStore.kernelBlurFragment2=mr;var gr="\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g;\nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth;\n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r;\nreturn coc;\n}\n#endif\n#include[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT\nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT;\nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include[0..varyingCount]\n#include[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}";zt.a.ShadersStore.kernelBlurPixelShader=gr;zt.a.IncludesShadersStore.kernelBlurVertex="sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};";var vr="\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nsampleCenter=(position*madd+madd);\n#include[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}";zt.a.ShadersStore.kernelBlurVertexShader=vr;var yr=function(e){function t(t,i,n,r,o,s,a,c,l,u,h){void 0===s&&(s=Ge.a.BILINEAR_SAMPLINGMODE),void 0===l&&(l=_.a.TEXTURETYPE_UNSIGNED_INT),void 0===u&&(u=""),void 0===h&&(h=!1);var d=e.call(this,t,"kernelBlur",["delta","direction","cameraMinMaxZ"],["circleOfConfusionSampler"],r,o,s,a,c,null,l,"kernelBlur",{varyingCount:0,depCount:0},!0)||this;return d.direction=i,d.blockCompilation=h,d._packedFloat=!1,d._staticDefines="",d._staticDefines=u,d.onApplyObservable.add(function(e){d._outputTexture?e.setFloat2("delta",1/d._outputTexture.width*d.direction.x,1/d._outputTexture.height*d.direction.y):e.setFloat2("delta",1/d.width*d.direction.x,1/d.height*d.direction.y)}),d.kernel=n,d}return l.d(t,e),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:!0,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:!0,configurable:!0}),t.prototype.updateEffect=function(e,t,i,n,r,o){void 0===e&&(e=null),void 0===t&&(t=null),void 0===i&&(i=null),this._updateParameters(r,o)},t.prototype._updateParameters=function(t,i){for(var n=this._kernel,r=(n-1)/2,o=[],s=[],a=0,c=0;c0)return Math.max(r,3)}return Math.max(t,3)},t.prototype._gaussianWeight=function(e){var t=-e*e/(1/3*2*(1/3));return 1/(Math.sqrt(2*Math.PI)*(1/3))*Math.exp(t)},t.prototype._glslFloat=function(e,t){return void 0===t&&(t=8),e.toFixed(t).replace(/0+$/,"")},t}(Wt),br=function(e){function t(t,i,n,r,s,a,c){void 0===s&&(s=_.a.TEXTURETYPE_UNSIGNED_INT),void 0===a&&(a=Ge.a.BILINEAR_SAMPLINGMODE),void 0===c&&(c=!0);var l=e.call(this,t,i,n,r,!0,s,!1,a,c)||this;return l.scene=n,l.mirrorPlane=new o.n(0,1,0,1),l._transformMatrix=o.j.Zero(),l._mirrorMatrix=o.j.Zero(),l._adaptiveBlurKernel=0,l._blurKernelX=0,l._blurKernelY=0,l._blurRatio=1,l.ignoreCameraViewport=!0,l._updateGammaSpace(),l._imageProcessingConfigChangeObserver=n.imageProcessingConfiguration.onUpdateParameters.add(function(){l._updateGammaSpace}),l.onBeforeRenderObservable.add(function(){o.j.ReflectionToRef(l.mirrorPlane,l._mirrorMatrix),l._savedViewMatrix=n.getViewMatrix(),l._mirrorMatrix.multiplyToRef(l._savedViewMatrix,l._transformMatrix),n.setTransformMatrix(l._transformMatrix,n.getProjectionMatrix()),n.clipPlane=l.mirrorPlane,n.getEngine().cullBackFaces=!1,n._mirroredCameraPosition=o.x.TransformCoordinates(n.activeCamera.globalPosition,l._mirrorMatrix)}),l.onAfterRenderObservable.add(function(){n.setTransformMatrix(l._savedViewMatrix,n.getProjectionMatrix()),n.getEngine().cullBackFaces=!0,n._mirroredCameraPosition=null,n.clipPlane=null}),l}return l.d(t,e),Object.defineProperty(t.prototype,"blurRatio",{get:function(){return this._blurRatio},set:function(e){this._blurRatio!==e&&(this._blurRatio=e,this._preparePostProcesses())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"adaptiveBlurKernel",{set:function(e){this._adaptiveBlurKernel=e,this._autoComputeBlurKernel()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"blurKernel",{set:function(e){this.blurKernelX=e,this.blurKernelY=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"blurKernelX",{get:function(){return this._blurKernelX},set:function(e){this._blurKernelX!==e&&(this._blurKernelX=e,this._preparePostProcesses())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"blurKernelY",{get:function(){return this._blurKernelY},set:function(e){this._blurKernelY!==e&&(this._blurKernelY=e,this._preparePostProcesses())},enumerable:!0,configurable:!0}),t.prototype._autoComputeBlurKernel=function(){var e=this.getScene().getEngine(),t=this.getRenderWidth()/e.getRenderWidth(),i=this.getRenderHeight()/e.getRenderHeight();this.blurKernelX=this._adaptiveBlurKernel*t,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(),t=e.getCaps().textureFloatRender?_.a.TEXTURETYPE_FLOAT:_.a.TEXTURETYPE_HALF_FLOAT;this._blurX=new yr("horizontal blur",new o.w(1,0),this._blurKernelX,this._blurRatio,null,Ge.a.BILINEAR_SAMPLINGMODE,e,!1,t),this._blurX.autoClear=!1,1===this._blurRatio&&this.samples<2&&this._texture?this._blurX.inputTexture=this._texture:this._blurX.alwaysForcePOT=!0,this._blurY=new yr("vertical blur",new o.w(0,1),this._blurKernelY,this._blurRatio,null,Ge.a.BILINEAR_SAMPLINGMODE,e,!1,t),this._blurY.autoClear=!1,this._blurY.alwaysForcePOT=1!==this._blurRatio,this.addPostProcess(this._blurX),this.addPostProcess(this._blurY)}else this._blurY&&(this.removePostProcess(this._blurY),this._blurY.dispose(),this._blurY=null),this._blurX&&(this.removePostProcess(this._blurX),this._blurX.dispose(),this._blurX=null)},t.prototype.clone=function(){var e=this.getScene();if(!e)return this;var i=this.getSize(),n=new t(this.name,i.width,e,this._renderTargetOptions.generateMipMaps,this._renderTargetOptions.type,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer);return n.hasAlpha=this.hasAlpha,n.level=this.level,n.mirrorPlane=this.mirrorPlane.clone(),this.renderList&&(n.renderList=this.renderList.slice(0)),n},t.prototype.serialize=function(){if(!this.name)return null;var t=e.prototype.serialize.call(this);return t.mirrorPlane=this.mirrorPlane.asArray(),t},t.prototype.dispose=function(){e.prototype.dispose.call(this),this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver)},t}(_i);Ge.a._CreateMirror=function(e,t,i,n){return new br(e,t,i,n)},me.b.prototype._createDepthStencilCubeTexture=function(e,t){var i=new ze.a(this,ze.a.DATASOURCE_UNKNOWN);if(i.isCube=!0,1===this.webGLVersion)return p.a.Error("Depth cube texture is not supported by WebGL 1."),i;var n=l.a({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1},t),r=this._gl;this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,i,!0),this._setupDepthStencilTexture(i,e,n.generateStencil,n.bilinearFiltering,n.comparisonFunction);for(var o=0;o<6;o++)n.generateStencil?r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+o,0,r.DEPTH24_STENCIL8,e,e,0,r.DEPTH_STENCIL,r.UNSIGNED_INT_24_8,null):r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+o,0,r.DEPTH_COMPONENT24,e,e,0,r.DEPTH_COMPONENT,r.UNSIGNED_INT,null);return this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,null),i},me.b.prototype._partialLoadFile=function(e,t,i,n,r){void 0===r&&(r=null);this._loadFile(e,function(e){i[t]=e,i._internalCount++,6===i._internalCount&&n(i)},void 0,void 0,!0,function(e,t){r&&e&&r(e.status+" "+e.statusText,t)})},me.b.prototype._cascadeLoadFiles=function(e,t,i,n){void 0===n&&(n=null);var r=[];r._internalCount=0;for(var o=0;o<6;o++)this._partialLoadFile(i[o],o,r,t,n)},me.b.prototype._cascadeLoadImgs=function(e,t,i,n){void 0===n&&(n=null);var r=[];r._internalCount=0;for(var o=0;o<6;o++)this._partialLoadImg(i[o],o,r,e,t,n)},me.b.prototype._partialLoadImg=function(e,t,i,n,r,o){var s;void 0===o&&(o=null);s=ye.h.LoadImage(e,function(){i[t]=s,i._internalCount++,n&&n._removePendingData(s),6===i._internalCount&&r(i)},function(e,t){n&&n._removePendingData(s),o&&o(e,t)},n?n.offlineProvider:null),n&&n._addPendingData(s)},me.b.prototype.createCubeTexture=function(e,t,i,n,r,o,s,a,c,l,u,h,d){var f=this;void 0===r&&(r=null),void 0===o&&(o=null),void 0===a&&(a=null),void 0===c&&(c=!1),void 0===l&&(l=0),void 0===u&&(u=0),void 0===h&&(h=null),void 0===d&&(d=[]);var _=this._gl,m=h||new ze.a(this,ze.a.DATASOURCE_CUBE);m.isCube=!0,m.url=e,m.generateMipMaps=!n,m._lodGenerationScale=l,m._lodGenerationOffset=u,this._doNotHandleContextLost||(m._extension=a,m._files=i);for(var g=e.lastIndexOf("."),v=a||(g>-1?e.substring(g).toLowerCase():""),y=null,b=0,T=me.b._TextureLoaders;b-1?t.substring(g).toLowerCase():""),y=".dds"===v,b=".env"===v;if(b?(m.gammaSpace=!1,m._prefiltered=!1):(m._prefiltered=u,u&&(m.gammaSpace=!1)),m._texture=m._getFromCache(t,r),!s&&(b||y||n||(n=["_px.jpg","_py.jpg","_pz.jpg","_nx.jpg","_ny.jpg","_nz.jpg"]),s=[],n))for(var T=0;T0,o.REFLECTIONMAP_OPPOSITEZ=this.getScene().useRightHandedSystem?!a.invertZ:a.invertZ,o.LODINREFLECTIONALPHA=a.lodLevelInAlpha,o.EQUIRECTANGULAR_RELFECTION_FOV=this.useEquirectangularFOV,o.REFLECTIONBGR=this.switchToBGR,a.coordinatesMode===Ge.a.INVCUBIC_MODE&&(o.INVERTCUBICMAP=!0),o.REFLECTIONMAP_3D=a.isCube,a.coordinatesMode){case Ge.a.EXPLICIT_MODE:o.REFLECTIONMAP_EXPLICIT=!0;break;case Ge.a.PLANAR_MODE:o.REFLECTIONMAP_PLANAR=!0;break;case Ge.a.PROJECTION_MODE:o.REFLECTIONMAP_PROJECTION=!0;break;case Ge.a.SKYBOX_MODE:o.REFLECTIONMAP_SKYBOX=!0,o.REFLECTIONMAP_SKYBOX_TRANSFORMED=!a.getReflectionTextureMatrix().isIdentity();break;case Ge.a.SPHERICAL_MODE:o.REFLECTIONMAP_SPHERICAL=!0;break;case Ge.a.EQUIRECTANGULAR_MODE:o.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case Ge.a.FIXED_EQUIRECTANGULAR_MODE:o.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case Ge.a.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:o.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case Ge.a.CUBIC_MODE:case Ge.a.INVCUBIC_MODE:default:o.REFLECTIONMAP_CUBIC=!0}this.reflectionFresnel?(o.REFLECTIONFRESNEL=!0,o.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):(o.REFLECTIONFRESNEL=!1,o.REFLECTIONFALLOFF=!1)}else o.REFLECTION=!1,o.REFLECTIONFRESNEL=!1,o.REFLECTIONFALLOFF=!1,o.REFLECTIONBLUR=!1,o.REFLECTIONMAP_3D=!1,o.REFLECTIONMAP_SPHERICAL=!1,o.REFLECTIONMAP_PLANAR=!1,o.REFLECTIONMAP_CUBIC=!1,o.REFLECTIONMAP_PROJECTION=!1,o.REFLECTIONMAP_SKYBOX=!1,o.REFLECTIONMAP_SKYBOX_TRANSFORMED=!1,o.REFLECTIONMAP_EXPLICIT=!1,o.REFLECTIONMAP_EQUIRECTANGULAR=!1,o.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,o.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,o.INVERTCUBICMAP=!1,o.REFLECTIONMAP_OPPOSITEZ=!1,o.LODINREFLECTIONALPHA=!1,o.GAMMAREFLECTION=!1,o.RGBDREFLECTION=!1}o.PREMULTIPLYALPHA=this.alphaMode===_.a.ALPHA_PREMULTIPLIED||this.alphaMode===_.a.ALPHA_PREMULTIPLIED_PORTERDUFF,o.USERGBCOLOR=this._useRGBColor,o.NOISE=this._enableNoise}if(o._areLightsDirty&&(o.USEHIGHLIGHTANDSHADOWCOLORS=!this._useRGBColor&&(0!==this._primaryColorShadowLevel||0!==this._primaryColorHighlightLevel)),o._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(o)}if(Er.a.PrepareDefinesForMisc(e,r,!1,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),o),Er.a.PrepareDefinesForFrameBoundValues(r,s,o,i),Er.a.PrepareDefinesForAttributes(e,o,!1,!0,!1)&&e&&(r.getEngine().getCaps().standardDerivatives||e.isVerticesDataPresent(Oi.b.NormalKind)||(e.createNormals(!0),p.a.Warn("BackgroundMaterial: Normals have been created for the mesh: "+e.name))),o.isDirty){o.markAsProcessed(),r.resetCachedMaterial();var c=new zt.c;o.FOG&&c.addFallback(0,"FOG"),o.POINTSIZE&&c.addFallback(1,"POINTSIZE"),o.MULTIVIEW&&c.addFallback(0,"MULTIVIEW"),Er.a.HandleFallbacksForShadows(o,c,this._maxSimultaneousLights),o.NUM_BONE_INFLUENCERS>0&&c.addCPUSkinningFallback(0,e);var l=[Oi.b.PositionKind];o.NORMAL&&l.push(Oi.b.NormalKind),o.UV1&&l.push(Oi.b.UVKind),o.UV2&&l.push(Oi.b.UV2Kind),Er.a.PrepareAttributesForBones(l,e,o,c),Er.a.PrepareAttributesForInstances(l,o);var u=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","vClipPlane","vClipPlane2","vClipPlane3","vClipPlane4","mBones","vPrimaryColor","vPrimaryColorShadow","vReflectionInfos","reflectionMatrix","vReflectionMicrosurfaceInfos","fFovMultiplier","shadowLevel","alpha","vBackgroundCenter","vReflectionControl","vDiffuseInfos","diffuseMatrix"],h=["diffuseSampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh"],d=["Material","Scene"];Ai.a&&(Ai.a.PrepareUniforms(u,o),Ai.a.PrepareSamplers(h,o)),Er.a.PrepareUniformsAndSamplersList({uniformsNames:u,uniformBuffersNames:d,samplers:h,defines:o,maxSimultaneousLights:this._maxSimultaneousLights});var f=o.toString();t.setEffect(r.getEngine().createEffect("background",{attributes:l,uniformsNames:u,uniformBuffersNames:d,samplers:h,defines:f,fallbacks:c,onCompiled:function(e){n.onCompiled&&n.onCompiled(e),n.bindSceneUniformBuffer(e,r.getSceneUniformBuffer())},onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights}},s),o),this.buildUniformLayout()}return!(!t.effect||!t.effect.isReady())&&(o._renderId=r.getRenderId(),this._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(){0===this._primaryColorShadowLevel&&0===this._primaryColorHighlightLevel||(this._primaryColor.scaleToRef(this._primaryColorShadowLevel,this._primaryShadowColor),this._primaryColor.subtractToRef(this._primaryShadowColor,this._primaryShadowColor),this._white.subtractToRef(this._primaryColor,this._primaryHighlightColor),this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel,this._primaryHighlightColor),this._primaryColor.addToRef(this._primaryHighlightColor,this._primaryHighlightColor))},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),e.prototype.unbind.call(this)},t.prototype.bindOnlyWorldMatrix=function(e){this._activeEffect.setMatrix("world",e)},t.prototype.bindForSubMesh=function(e,t,i){var n=this.getScene(),r=i._materialDefines;if(r){var o=i.effect;if(o){this._activeEffect=o,this.bindOnlyWorldMatrix(e),Er.a.BindBonesParameters(t,this._activeEffect);var s=this._mustRebind(n,o,t.visibility);if(s){this._uniformBuffer.bindToEffect(o,"Material"),this.bindViewProjection(o);var a=this._reflectionTexture;this._uniformBuffer.useUbo&&this.isFrozen&&this._uniformBuffer.isSync||(n.texturesEnabled&&(this._diffuseTexture&&Pr.a.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),Er.a.BindTextureMatrix(this._diffuseTexture,this._uniformBuffer,"diffuse")),a&&Pr.a.ReflectionTextureEnabled&&(this._uniformBuffer.updateMatrix("reflectionMatrix",a.getReflectionTextureMatrix()),this._uniformBuffer.updateFloat2("vReflectionInfos",a.level,this._reflectionBlur),this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos",a.getSize().width,a.lodGenerationScale,a.lodGenerationOffset))),this.shadowLevel>0&&this._uniformBuffer.updateFloat("shadowLevel",this.shadowLevel),this._uniformBuffer.updateFloat("alpha",this.alpha),this.pointsCloud&&this._uniformBuffer.updateFloat("pointSize",this.pointSize),r.USEHIGHLIGHTANDSHADOWCOLORS?(this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryHighlightColor,1),this._uniformBuffer.updateColor4("vPrimaryColorShadow",this._primaryShadowColor,1)):this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryColor,1)),this._uniformBuffer.updateFloat("fFovMultiplier",this._fovMultiplier),n.texturesEnabled&&(this._diffuseTexture&&Pr.a.DiffuseTextureEnabled&&this._uniformBuffer.setTexture("diffuseSampler",this._diffuseTexture),a&&Pr.a.ReflectionTextureEnabled&&(r.REFLECTIONBLUR&&r.TEXTURELODSUPPORT?this._uniformBuffer.setTexture("reflectionSampler",a):r.REFLECTIONBLUR?(this._uniformBuffer.setTexture("reflectionSampler",a._lodTextureMid||a),this._uniformBuffer.setTexture("reflectionSamplerLow",a._lodTextureLow||a),this._uniformBuffer.setTexture("reflectionSamplerHigh",a._lodTextureHigh||a)):this._uniformBuffer.setTexture("reflectionSampler",a),r.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)))),Er.a.BindClipPlane(this._activeEffect,n),Er.a.BindEyePosition(o,n)}!s&&this.isFrozen||(n.lightsEnabled&&Er.a.BindLights(n,t,this._activeEffect,r,this._maxSimultaneousLights,!1),this.bindView(o),Er.a.BindFogParameters(n,t,this._activeEffect,!0),this._imageProcessingConfiguration&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._uniformBuffer.update(),this._afterBind(t,this._activeEffect)}}},t.prototype.dispose=function(t,i){void 0===t&&(t=!1),void 0===i&&(i=!1),i&&(this.diffuseTexture&&this.diffuseTexture.dispose(),this.reflectionTexture&&this.reflectionTexture.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e.prototype.dispose.call(this,t)},t.prototype.clone=function(e){var i=this;return L.a.Clone(function(){return new t(e,i.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,i,n){return L.a.Parse(function(){return new t(e.name,i)},e,i,n)},t.StandardReflectance0=.05,t.StandardReflectance90=.5,l.c([Object(L.e)()],t.prototype,"_primaryColor",void 0),l.c([Object(L.b)("_markAllSubMeshesAsLightsDirty")],t.prototype,"primaryColor",void 0),l.c([Object(L.e)()],t.prototype,"__perceptualColor",void 0),l.c([Object(L.c)()],t.prototype,"_primaryColorShadowLevel",void 0),l.c([Object(L.c)()],t.prototype,"_primaryColorHighlightLevel",void 0),l.c([Object(L.b)("_markAllSubMeshesAsLightsDirty")],t.prototype,"primaryColorHighlightLevel",null),l.c([Object(L.m)()],t.prototype,"_reflectionTexture",void 0),l.c([Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"reflectionTexture",void 0),l.c([Object(L.c)()],t.prototype,"_reflectionBlur",void 0),l.c([Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"reflectionBlur",void 0),l.c([Object(L.m)()],t.prototype,"_diffuseTexture",void 0),l.c([Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"diffuseTexture",void 0),l.c([Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"shadowLights",void 0),l.c([Object(L.c)()],t.prototype,"_shadowLevel",void 0),l.c([Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"shadowLevel",void 0),l.c([Object(L.o)()],t.prototype,"_sceneCenter",void 0),l.c([Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"sceneCenter",void 0),l.c([Object(L.c)()],t.prototype,"_opacityFresnel",void 0),l.c([Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"opacityFresnel",void 0),l.c([Object(L.c)()],t.prototype,"_reflectionFresnel",void 0),l.c([Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"reflectionFresnel",void 0),l.c([Object(L.c)()],t.prototype,"_reflectionFalloffDistance",void 0),l.c([Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"reflectionFalloffDistance",void 0),l.c([Object(L.c)()],t.prototype,"_reflectionAmount",void 0),l.c([Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"reflectionAmount",void 0),l.c([Object(L.c)()],t.prototype,"_reflectionReflectance0",void 0),l.c([Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"reflectionReflectance0",void 0),l.c([Object(L.c)()],t.prototype,"_reflectionReflectance90",void 0),l.c([Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"reflectionReflectance90",void 0),l.c([Object(L.c)()],t.prototype,"_useRGBColor",void 0),l.c([Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useRGBColor",void 0),l.c([Object(L.c)()],t.prototype,"_enableNoise",void 0),l.c([Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"enableNoise",void 0),l.c([Object(L.c)()],t.prototype,"_maxSimultaneousLights",void 0),l.c([Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"maxSimultaneousLights",void 0),l.c([Object(L.i)()],t.prototype,"_imageProcessingConfiguration",void 0),t}(Ar.a);s.a.RegisteredTypes["BABYLON.BackgroundMaterial"]=Dr;var Lr=function(){function e(t,i){var n=this;this._errorHandler=function(e,t){n.onErrorObservable.notifyObservers({message:e,exception:t})},this._options=l.a({},e._getDefaultOptions(),t),this._scene=i,this.onErrorObservable=new r.c,this._setupBackground(),this._setupImageProcessing()}return e._getDefaultOptions=function(){return{createGround:!0,groundSize:15,groundTexture:this._groundTextureCDNUrl,groundColor:new o.e(.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:_.a.TEXTURETYPE_UNSIGNED_INT,groundYBias:1e-5,createSkybox:!0,skyboxSize:20,skyboxTexture:this._skyboxTextureCDNUrl,skyboxColor:new o.e(.2,.2,.3).toLinearSpace().scale(3),backgroundYRotation:0,sizeAuto:!0,rootPosition:o.x.Zero(),setupImageProcessing:!0,environmentTexture:this._environmentTextureCDNUrl,cameraExposure:.8,cameraContrast:1.2,toneMappingEnabled:!0}},Object.defineProperty(e.prototype,"rootMesh",{get:function(){return this._rootMesh},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"skybox",{get:function(){return this._skybox},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"skyboxTexture",{get:function(){return this._skyboxTexture},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"skyboxMaterial",{get:function(){return this._skyboxMaterial},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"ground",{get:function(){return this._ground},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"groundTexture",{get:function(){return this._groundTexture},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"groundMirror",{get:function(){return this._groundMirror},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"groundMirrorRenderList",{get:function(){return this._groundMirror?this._groundMirror.renderList:null},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"groundMaterial",{get:function(){return this._groundMaterial},enumerable:!0,configurable:!0}),e.prototype.updateOptions=function(e){var t=l.a({},this._options,e);this._ground&&!t.createGround&&(this._ground.dispose(),this._ground=null),this._groundMaterial&&!t.createGround&&(this._groundMaterial.dispose(),this._groundMaterial=null),this._groundTexture&&this._options.groundTexture!=t.groundTexture&&(this._groundTexture.dispose(),this._groundTexture=null),this._skybox&&!t.createSkybox&&(this._skybox.dispose(),this._skybox=null),this._skyboxMaterial&&!t.createSkybox&&(this._skyboxMaterial.dispose(),this._skyboxMaterial=null),this._skyboxTexture&&this._options.skyboxTexture!=t.skyboxTexture&&(this._skyboxTexture.dispose(),this._skyboxTexture=null),this._groundMirror&&!t.enableGroundMirror&&(this._groundMirror.dispose(),this._groundMirror=null),this._scene.environmentTexture&&this._options.environmentTexture!=t.environmentTexture&&this._scene.environmentTexture.dispose(),this._options=t,this._setupBackground(),this._setupImageProcessing()},e.prototype.setMainColor=function(e){this.groundMaterial&&(this.groundMaterial.primaryColor=e),this.skyboxMaterial&&(this.skyboxMaterial.primaryColor=e),this.groundMirror&&(this.groundMirror.clearColor=new o.f(e.r,e.g,e.b,1))},e.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())},e.prototype._setupEnvironmentTexture=function(){if(!this._scene.environmentTexture)if(this._options.environmentTexture instanceof vn.a)this._scene.environmentTexture=this._options.environmentTexture;else{var e=Tr.CreateFromPrefilteredData(this._options.environmentTexture,this._scene);this._scene.environmentTexture=e}},e.prototype._setupBackground=function(){this._rootMesh||(this._rootMesh=new fe.a("BackgroundHelper",this._scene)),this._rootMesh.rotation.y=this._options.backgroundYRotation;var e=this._getSceneSize();this._options.createGround&&(this._setupGround(e),this._setupGroundMaterial(),this._setupGroundDiffuseTexture(),this._options.enableGroundMirror&&this._setupGroundMirrorTexture(e),this._setupMirrorInGroundMaterial()),this._options.createSkybox&&(this._setupSkybox(e),this._setupSkyboxMaterial(),this._setupSkyboxReflectionTexture()),this._rootMesh.position.x=e.rootPosition.x,this._rootMesh.position.z=e.rootPosition.z,this._rootMesh.position.y=e.rootPosition.y},e.prototype._getSceneSize=function(){var e=this,t=this._options.groundSize,i=this._options.skyboxSize,n=this._options.rootPosition;if(!this._scene.meshes||1===this._scene.meshes.length)return{groundSize:t,skyboxSize:i,rootPosition:n};var r=this._scene.getWorldExtends(function(t){return t!==e._ground&&t!==e._rootMesh&&t!==e._skybox}),o=r.max.subtract(r.min);if(this._options.sizeAuto){this._scene.activeCamera instanceof Et&&this._scene.activeCamera.upperRadiusLimit&&(i=t=2*this._scene.activeCamera.upperRadiusLimit);var s=o.length();s>t&&(i=t=2*s),t*=1.1,i*=1.5,(n=r.min.add(o.scale(.5))).y=r.min.y-this._options.groundYBias}return{groundSize:t,skyboxSize:i,rootPosition:n}},e.prototype._setupGround=function(e){var t=this;this._ground&&!this._ground.isDisposed()||(this._ground=fe.a.CreatePlane("BackgroundPlane",e.groundSize,this._scene),this._ground.rotation.x=Math.PI/2,this._ground.parent=this._rootMesh,this._ground.onDisposeObservable.add(function(){t._ground=null})),this._ground.receiveShadows=this._options.enableGroundShadow},e.prototype._setupGroundMaterial=function(){this._groundMaterial||(this._groundMaterial=new Dr("BackgroundPlaneMaterial",this._scene)),this._groundMaterial.alpha=this._options.groundOpacity,this._groundMaterial.alphaMode=_.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)},e.prototype._setupGroundDiffuseTexture=function(){if(this._groundMaterial&&!this._groundTexture)if(this._options.groundTexture instanceof vn.a)this._groundMaterial.diffuseTexture=this._options.groundTexture;else{var e=new Ge.a(this._options.groundTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler);e.gammaSpace=!1,e.hasAlpha=!0,this._groundMaterial.diffuseTexture=e}},e.prototype._setupGroundMirrorTexture=function(e){var t=Ge.a.CLAMP_ADDRESSMODE;if(!this._groundMirror&&(this._groundMirror=new br("BackgroundPlaneMirrorTexture",{ratio:this._options.groundMirrorSizeRatio},this._scene,!1,this._options.groundMirrorTextureType,Ge.a.BILINEAR_SAMPLINGMODE,!0),this._groundMirror.mirrorPlane=new o.n(0,-1,0,e.rootPosition.y),this._groundMirror.anisotropicFilteringLevel=1,this._groundMirror.wrapU=t,this._groundMirror.wrapV=t,this._groundMirror.gammaSpace=!1,this._groundMirror.renderList))for(var i=0;i0&&e.push(this._texture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._tintTexture&&this._tintTexture.animations&&this._tintTexture.animations.length>0&&e.push(this._tintTexture)},e.prototype.dispose=function(e){e&&(this._texture&&this._texture.dispose(),this._bumpTexture&&this._bumpTexture.dispose(),this._tintTexture&&this._tintTexture.dispose())},e.prototype.getClassName=function(){return"PBRClearCoatConfiguration"},e.AddFallbacks=function(e,t,i){return e.CLEARCOAT_BUMP&&t.addFallback(i++,"CLEARCOAT_BUMP"),e.CLEARCOAT_TINT&&t.addFallback(i++,"CLEARCOAT_TINT"),e.CLEARCOAT&&t.addFallback(i++,"CLEARCOAT"),i},e.AddUniforms=function(e){e.push("vClearCoatTangentSpaceParams","vClearCoatParams","vClearCoatRefractionParams","vClearCoatTintParams","clearCoatColorAtDistance","clearCoatMatrix","clearCoatBumpMatrix","clearCoatTintMatrix","vClearCoatInfos","vClearCoatBumpInfos","vClearCoatTintInfos")},e.AddSamplers=function(e){e.push("clearCoatSampler","clearCoatBumpSampler","clearCoatTintSampler")},e.PrepareUniformBuffer=function(e){e.addUniform("vClearCoatParams",2),e.addUniform("vClearCoatRefractionParams",4),e.addUniform("vClearCoatInfos",2),e.addUniform("clearCoatMatrix",16),e.addUniform("vClearCoatBumpInfos",2),e.addUniform("vClearCoatTangentSpaceParams",2),e.addUniform("clearCoatBumpMatrix",16),e.addUniform("vClearCoatTintParams",4),e.addUniform("clearCoatColorAtDistance",1),e.addUniform("vClearCoatTintInfos",2),e.addUniform("clearCoatTintMatrix",16)},e.prototype.copyTo=function(e){L.a.Clone(function(){return e},this)},e.prototype.serialize=function(){return L.a.Serialize(this)},e.prototype.parse=function(e){var t=this;L.a.Parse(function(){return t},e,null)},e._DefaultIndiceOfRefraction=1.5,l.c([Object(L.c)()],e.prototype,"_isEnabled",void 0),l.c([Object(L.b)("_markAllSubMeshesAsTexturesDirty")],e.prototype,"isEnabled",void 0),l.c([Object(L.c)()],e.prototype,"intensity",void 0),l.c([Object(L.c)()],e.prototype,"roughness",void 0),l.c([Object(L.c)()],e.prototype,"_indiceOfRefraction",void 0),l.c([Object(L.b)("_markAllSubMeshesAsTexturesDirty")],e.prototype,"indiceOfRefraction",void 0),l.c([Object(L.m)()],e.prototype,"_texture",void 0),l.c([Object(L.b)("_markAllSubMeshesAsTexturesDirty")],e.prototype,"texture",void 0),l.c([Object(L.m)()],e.prototype,"_bumpTexture",void 0),l.c([Object(L.b)("_markAllSubMeshesAsTexturesDirty")],e.prototype,"bumpTexture",void 0),l.c([Object(L.c)()],e.prototype,"_isTintEnabled",void 0),l.c([Object(L.b)("_markAllSubMeshesAsTexturesDirty")],e.prototype,"isTintEnabled",void 0),l.c([Object(L.e)()],e.prototype,"tintColor",void 0),l.c([Object(L.c)()],e.prototype,"tintColorAtDistance",void 0),l.c([Object(L.c)()],e.prototype,"tintThickness",void 0),l.c([Object(L.m)()],e.prototype,"_tintTexture",void 0),l.c([Object(L.b)("_markAllSubMeshesAsTexturesDirty")],e.prototype,"tintTexture",void 0),e}(),Br=function(){function e(e){this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.direction=new o.w(1,0),this._texture=null,this.texture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e}return e.prototype._markAllSubMeshesAsTexturesDirty=function(){this._internalMarkAllSubMeshesAsTexturesDirty()},e.prototype.isReadyForSubMesh=function(e,t){return!(e._areTexturesDirty&&t.texturesEnabled&&this._texture&&Pr.a.AnisotropicTextureEnabled&&!this._texture.isReadyOrNotBlocking())},e.prototype.prepareDefines=function(e,t,i){this._isEnabled?(e.ANISOTROPIC=this._isEnabled,this._isEnabled&&!t.isVerticesDataPresent(Oi.b.TangentKind)&&(e._needUVs=!0,e.MAINUV1=!0),e._areTexturesDirty&&i.texturesEnabled&&(this._texture&&Pr.a.AnisotropicTextureEnabled?Er.a.PrepareDefinesForMergedUV(this._texture,e,"ANISOTROPIC_TEXTURE"):e.ANISOTROPIC_TEXTURE=!1)):(e.ANISOTROPIC=!1,e.ANISOTROPIC_TEXTURE=!1)},e.prototype.bindForSubMesh=function(e,t,i){e.useUbo&&i&&e.isSync||(this._texture&&Pr.a.AnisotropicTextureEnabled&&(e.updateFloat2("vAnisotropyInfos",this._texture.coordinatesIndex,this._texture.level),Er.a.BindTextureMatrix(this._texture,e,"anisotropy")),e.updateFloat3("vAnisotropy",this.direction.x,this.direction.y,this.intensity)),t.texturesEnabled&&this._texture&&Pr.a.AnisotropicTextureEnabled&&e.setTexture("anisotropySampler",this._texture)},e.prototype.hasTexture=function(e){return this._texture===e},e.prototype.getActiveTextures=function(e){this._texture&&e.push(this._texture)},e.prototype.getAnimatables=function(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture)},e.prototype.dispose=function(e){e&&this._texture&&this._texture.dispose()},e.prototype.getClassName=function(){return"PBRAnisotropicConfiguration"},e.AddFallbacks=function(e,t,i){return e.ANISOTROPIC&&t.addFallback(i++,"ANISOTROPIC"),i},e.AddUniforms=function(e){e.push("vAnisotropy","vAnisotropyInfos","anisotropyMatrix")},e.PrepareUniformBuffer=function(e){e.addUniform("vAnisotropy",3),e.addUniform("vAnisotropyInfos",2),e.addUniform("anisotropyMatrix",16)},e.AddSamplers=function(e){e.push("anisotropySampler")},e.prototype.copyTo=function(e){L.a.Clone(function(){return e},this)},e.prototype.serialize=function(){return L.a.Serialize(this)},e.prototype.parse=function(e){var t=this;L.a.Parse(function(){return t},e,null)},l.c([Object(L.c)()],e.prototype,"_isEnabled",void 0),l.c([Object(L.b)("_markAllSubMeshesAsTexturesDirty")],e.prototype,"isEnabled",void 0),l.c([Object(L.c)()],e.prototype,"intensity",void 0),l.c([Object(L.n)()],e.prototype,"direction",void 0),l.c([Object(L.m)()],e.prototype,"_texture",void 0),l.c([Object(L.b)("_markAllSubMeshesAsTexturesDirty")],e.prototype,"texture",void 0),e}(),Ur=function(){function e(t){this._useEnergyConservation=e.DEFAULT_USE_ENERGY_CONSERVATION,this.useEnergyConservation=e.DEFAULT_USE_ENERGY_CONSERVATION,this._useSmithVisibilityHeightCorrelated=e.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this.useSmithVisibilityHeightCorrelated=e.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this._useSphericalHarmonics=e.DEFAULT_USE_SPHERICAL_HARMONICS,this.useSphericalHarmonics=e.DEFAULT_USE_SPHERICAL_HARMONICS,this._internalMarkAllSubMeshesAsMiscDirty=t}return e.prototype._markAllSubMeshesAsMiscDirty=function(){this._internalMarkAllSubMeshesAsMiscDirty()},e.prototype.prepareDefines=function(e){e.BRDF_V_HEIGHT_CORRELATED=this._useSmithVisibilityHeightCorrelated,e.MS_BRDF_ENERGY_CONSERVATION=this._useEnergyConservation&&this._useSmithVisibilityHeightCorrelated,e.SPHERICAL_HARMONICS=this._useSphericalHarmonics},e.prototype.getClassName=function(){return"PBRBRDFConfiguration"},e.prototype.copyTo=function(e){L.a.Clone(function(){return e},this)},e.prototype.serialize=function(){return L.a.Serialize(this)},e.prototype.parse=function(e){var t=this;L.a.Parse(function(){return t},e,null)},e.DEFAULT_USE_ENERGY_CONSERVATION=!0,e.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED=!0,e.DEFAULT_USE_SPHERICAL_HARMONICS=!0,l.c([Object(L.c)()],e.prototype,"_useEnergyConservation",void 0),l.c([Object(L.b)("_markAllSubMeshesAsMiscDirty")],e.prototype,"useEnergyConservation",void 0),l.c([Object(L.c)()],e.prototype,"_useSmithVisibilityHeightCorrelated",void 0),l.c([Object(L.b)("_markAllSubMeshesAsMiscDirty")],e.prototype,"useSmithVisibilityHeightCorrelated",void 0),l.c([Object(L.c)()],e.prototype,"_useSphericalHarmonics",void 0),l.c([Object(L.b)("_markAllSubMeshesAsMiscDirty")],e.prototype,"useSphericalHarmonics",void 0),e}(),Vr=function(){function e(e){this._isEnabled=!1,this.isEnabled=!1,this._linkSheenWithAlbedo=!1,this.linkSheenWithAlbedo=!1,this.intensity=1,this.color=o.e.White(),this._texture=null,this.texture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e}return e.prototype._markAllSubMeshesAsTexturesDirty=function(){this._internalMarkAllSubMeshesAsTexturesDirty()},e.prototype.isReadyForSubMesh=function(e,t){return!(e._areTexturesDirty&&t.texturesEnabled&&this._texture&&Pr.a.SheenTextureEnabled&&!this._texture.isReadyOrNotBlocking())},e.prototype.prepareDefines=function(e,t){this._isEnabled?(e.SHEEN=this._isEnabled,e.SHEEN_LINKWITHALBEDO=this._linkSheenWithAlbedo,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&Pr.a.SheenTextureEnabled?Er.a.PrepareDefinesForMergedUV(this._texture,e,"SHEEN_TEXTURE"):e.SHEEN_TEXTURE=!1)):(e.SHEEN=!1,e.SHEEN_TEXTURE=!1,e.SHEEN_LINKWITHALBEDO=!1)},e.prototype.bindForSubMesh=function(e,t,i){e.useUbo&&i&&e.isSync||(this._texture&&Pr.a.SheenTextureEnabled&&(e.updateFloat2("vSheenInfos",this._texture.coordinatesIndex,this._texture.level),Er.a.BindTextureMatrix(this._texture,e,"sheen")),e.updateFloat4("vSheenColor",this.color.r,this.color.g,this.color.b,this.intensity)),t.texturesEnabled&&this._texture&&Pr.a.SheenTextureEnabled&&e.setTexture("sheenSampler",this._texture)},e.prototype.hasTexture=function(e){return this._texture===e},e.prototype.getActiveTextures=function(e){this._texture&&e.push(this._texture)},e.prototype.getAnimatables=function(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture)},e.prototype.dispose=function(e){e&&this._texture&&this._texture.dispose()},e.prototype.getClassName=function(){return"PBRSheenConfiguration"},e.AddFallbacks=function(e,t,i){return e.SHEEN&&t.addFallback(i++,"SHEEN"),i},e.AddUniforms=function(e){e.push("vSheenColor","vSheenInfos","sheenMatrix")},e.PrepareUniformBuffer=function(e){e.addUniform("vSheenColor",4),e.addUniform("vSheenInfos",2),e.addUniform("sheenMatrix",16)},e.AddSamplers=function(e){e.push("sheenSampler")},e.prototype.copyTo=function(e){L.a.Clone(function(){return e},this)},e.prototype.serialize=function(){return L.a.Serialize(this)},e.prototype.parse=function(e){var t=this;L.a.Parse(function(){return t},e,null)},l.c([Object(L.c)()],e.prototype,"_isEnabled",void 0),l.c([Object(L.b)("_markAllSubMeshesAsTexturesDirty")],e.prototype,"isEnabled",void 0),l.c([Object(L.c)()],e.prototype,"_linkSheenWithAlbedo",void 0),l.c([Object(L.b)("_markAllSubMeshesAsTexturesDirty")],e.prototype,"linkSheenWithAlbedo",void 0),l.c([Object(L.c)()],e.prototype,"intensity",void 0),l.c([Object(L.e)()],e.prototype,"color",void 0),l.c([Object(L.m)()],e.prototype,"_texture",void 0),l.c([Object(L.b)("_markAllSubMeshesAsTexturesDirty")],e.prototype,"texture",void 0),e}(),kr=function(){function e(e){this._isRefractionEnabled=!1,this.isRefractionEnabled=!1,this._isTranslucencyEnabled=!1,this.isTranslucencyEnabled=!1,this._isScatteringEnabled=!1,this.refractionIntensity=1,this.translucencyIntensity=1,this.scatteringIntensity=1,this._thicknessTexture=null,this.thicknessTexture=null,this._refractionTexture=null,this.refractionTexture=null,this._indexOfRefraction=1,this.indexOfRefraction=1,this._invertRefractionY=!1,this.invertRefractionY=!1,this._linkRefractionWithTransparency=!1,this.linkRefractionWithTransparency=!1,this.minimumThickness=0,this.maximumThickness=1,this.tintColor=o.e.White(),this.tintColorAtDistance=1,this.diffusionDistance=o.e.White(),this._useMaskFromThicknessTexture=!1,this.useMaskFromThicknessTexture=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e}return e.prototype._markAllSubMeshesAsTexturesDirty=function(){this._internalMarkAllSubMeshesAsTexturesDirty()},e.prototype.isReadyForSubMesh=function(e,t){if(e._areTexturesDirty&&t.texturesEnabled){if(this._thicknessTexture&&Pr.a.ThicknessTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1;var i=this._getRefractionTexture(t);if(i&&Pr.a.RefractionTextureEnabled&&!i.isReadyOrNotBlocking())return!1}return!0},e.prototype.prepareDefines=function(e,t){if(e._areTexturesDirty&&(e.SUBSURFACE=!1,e.SS_TRANSLUCENCY=this._isTranslucencyEnabled,e.SS_SCATERRING=this._isScatteringEnabled,e.SS_THICKNESSANDMASK_TEXTURE=!1,e.SS_MASK_FROM_THICKNESS_TEXTURE=!1,e.SS_REFRACTION=!1,e.SS_REFRACTIONMAP_3D=!1,e.SS_GAMMAREFRACTION=!1,e.SS_RGBDREFRACTION=!1,e.SS_LINEARSPECULARREFRACTION=!1,e.SS_REFRACTIONMAP_OPPOSITEZ=!1,e.SS_LODINREFRACTIONALPHA=!1,e.SS_LINKREFRACTIONTOTRANSPARENCY=!1,(this._isRefractionEnabled||this._isTranslucencyEnabled||this._isScatteringEnabled)&&(e.SUBSURFACE=!0,e._areTexturesDirty&&t.texturesEnabled&&this._thicknessTexture&&Pr.a.ThicknessTextureEnabled&&Er.a.PrepareDefinesForMergedUV(this._thicknessTexture,e,"SS_THICKNESSANDMASK_TEXTURE"),e.SS_MASK_FROM_THICKNESS_TEXTURE=this._useMaskFromThicknessTexture),this._isRefractionEnabled&&t.texturesEnabled)){var i=this._getRefractionTexture(t);i&&Pr.a.RefractionTextureEnabled&&(e.SS_REFRACTION=!0,e.SS_REFRACTIONMAP_3D=i.isCube,e.SS_GAMMAREFRACTION=i.gammaSpace,e.SS_RGBDREFRACTION=i.isRGBD,e.SS_LINEARSPECULARREFRACTION=i.linearSpecularLOD,e.SS_REFRACTIONMAP_OPPOSITEZ=i.invertZ,e.SS_LODINREFRACTIONALPHA=i.lodLevelInAlpha,e.SS_LINKREFRACTIONTOTRANSPARENCY=this._linkRefractionWithTransparency)}},e.prototype.bindForSubMesh=function(e,t,i,n,r){var o=this._getRefractionTexture(t);if(!e.useUbo||!n||!e.isSync){if(this._thicknessTexture&&Pr.a.ThicknessTextureEnabled&&(e.updateFloat2("vThicknessInfos",this._thicknessTexture.coordinatesIndex,this._thicknessTexture.level),Er.a.BindTextureMatrix(this._thicknessTexture,e,"thickness")),e.updateFloat2("vThicknessParam",this.minimumThickness,this.maximumThickness-this.minimumThickness),o&&Pr.a.RefractionTextureEnabled){e.updateMatrix("refractionMatrix",o.getReflectionTextureMatrix());var s=1;o.isCube||o.depth&&(s=o.depth),e.updateFloat4("vRefractionInfos",o.level,1/this._indexOfRefraction,s,this._invertRefractionY?-1:1),e.updateFloat3("vRefractionMicrosurfaceInfos",o.getSize().width,o.lodGenerationScale,o.lodGenerationOffset)}e.updateColor3("vDiffusionDistance",this.diffusionDistance),e.updateFloat4("vTintColor",this.tintColor.r,this.tintColor.g,this.tintColor.b,this.tintColorAtDistance),e.updateFloat3("vSubSurfaceIntensity",this.refractionIntensity,this.translucencyIntensity,this.scatteringIntensity)}t.texturesEnabled&&(this._thicknessTexture&&Pr.a.ThicknessTextureEnabled&&e.setTexture("thicknessSampler",this._thicknessTexture),o&&Pr.a.RefractionTextureEnabled&&(r?e.setTexture("refractionSampler",o):(e.setTexture("refractionSampler",o._lodTextureMid||o),e.setTexture("refractionSamplerLow",o._lodTextureLow||o),e.setTexture("refractionSamplerHigh",o._lodTextureHigh||o))))},e.prototype.unbind=function(e){return!(!this._refractionTexture||!this._refractionTexture.isRenderTarget)&&(e.setTexture("refractionSampler",null),!0)},e.prototype._getRefractionTexture=function(e){return this._refractionTexture?this._refractionTexture:this._isRefractionEnabled?e.environmentTexture:null},Object.defineProperty(e.prototype,"disableAlphaBlending",{get:function(){return this.isRefractionEnabled&&this._linkRefractionWithTransparency},enumerable:!0,configurable:!0}),e.prototype.fillRenderTargetTextures=function(e){Pr.a.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&e.push(this._refractionTexture)},e.prototype.hasTexture=function(e){return this._thicknessTexture===e||this._refractionTexture===e},e.prototype.hasRenderTargetTextures=function(){return!!(Pr.a.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget)},e.prototype.getActiveTextures=function(e){this._thicknessTexture&&e.push(this._thicknessTexture),this._refractionTexture&&e.push(this._refractionTexture)},e.prototype.getAnimatables=function(e){this._thicknessTexture&&this._thicknessTexture.animations&&this._thicknessTexture.animations.length>0&&e.push(this._thicknessTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture)},e.prototype.dispose=function(e){e&&(this._thicknessTexture&&this._thicknessTexture.dispose(),this._refractionTexture&&this._refractionTexture.dispose())},e.prototype.getClassName=function(){return"PBRSubSurfaceConfiguration"},e.AddFallbacks=function(e,t,i){return e.SS_SCATERRING&&t.addFallback(i++,"SS_SCATERRING"),e.SS_TRANSLUCENCY&&t.addFallback(i++,"SS_TRANSLUCENCY"),i},e.AddUniforms=function(e){e.push("vDiffusionDistance","vTintColor","vSubSurfaceIntensity","vRefractionMicrosurfaceInfos","vRefractionInfos","vThicknessInfos","vThicknessParam","refractionMatrix","thicknessMatrix")},e.AddSamplers=function(e){e.push("thicknessSampler","refractionSampler","refractionSamplerLow","refractionSamplerHigh")},e.PrepareUniformBuffer=function(e){e.addUniform("vRefractionMicrosurfaceInfos",3),e.addUniform("vRefractionInfos",4),e.addUniform("refractionMatrix",16),e.addUniform("vThicknessInfos",2),e.addUniform("thicknessMatrix",16),e.addUniform("vThicknessParam",2),e.addUniform("vDiffusionDistance",3),e.addUniform("vTintColor",4),e.addUniform("vSubSurfaceIntensity",3)},e.prototype.copyTo=function(e){L.a.Clone(function(){return e},this)},e.prototype.serialize=function(){return L.a.Serialize(this)},e.prototype.parse=function(e){var t=this;L.a.Parse(function(){return t},e,null)},l.c([Object(L.c)()],e.prototype,"_isRefractionEnabled",void 0),l.c([Object(L.b)("_markAllSubMeshesAsTexturesDirty")],e.prototype,"isRefractionEnabled",void 0),l.c([Object(L.c)()],e.prototype,"_isTranslucencyEnabled",void 0),l.c([Object(L.b)("_markAllSubMeshesAsTexturesDirty")],e.prototype,"isTranslucencyEnabled",void 0),l.c([Object(L.c)()],e.prototype,"_isScatteringEnabled",void 0),l.c([Object(L.c)()],e.prototype,"refractionIntensity",void 0),l.c([Object(L.c)()],e.prototype,"translucencyIntensity",void 0),l.c([Object(L.c)()],e.prototype,"scatteringIntensity",void 0),l.c([Object(L.m)()],e.prototype,"_thicknessTexture",void 0),l.c([Object(L.b)("_markAllSubMeshesAsTexturesDirty")],e.prototype,"thicknessTexture",void 0),l.c([Object(L.m)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],e.prototype,"refractionTexture",void 0),l.c([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],e.prototype,"indexOfRefraction",void 0),l.c([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],e.prototype,"invertRefractionY",void 0),l.c([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],e.prototype,"linkRefractionWithTransparency",void 0),l.c([Object(L.c)()],e.prototype,"minimumThickness",void 0),l.c([Object(L.c)()],e.prototype,"maximumThickness",void 0),l.c([Object(L.e)()],e.prototype,"tintColor",void 0),l.c([Object(L.c)()],e.prototype,"tintColorAtDistance",void 0),l.c([Object(L.e)()],e.prototype,"diffusionDistance",void 0),l.c([Object(L.c)()],e.prototype,"_useMaskFromThicknessTexture",void 0),l.c([Object(L.b)("_markAllSubMeshesAsTexturesDirty")],e.prototype,"useMaskFromThicknessTexture",void 0),e}(),Gr="uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float visibility;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec4 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(SS_REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize;\n#endif\n#endif\n\n#ifdef CLEARCOAT\nuniform vec2 vClearCoatParams;\nuniform vec4 vClearCoatRefractionParams;\n#ifdef CLEARCOAT_TEXTURE\nuniform vec2 vClearCoatInfos;\nuniform mat4 clearCoatMatrix;\n#endif\n#ifdef CLEARCOAT_BUMP\nuniform vec2 vClearCoatBumpInfos;\nuniform vec2 vClearCoatTangentSpaceParams;\nuniform mat4 clearCoatBumpMatrix;\n#endif\n#ifdef CLEARCOAT_TINT\nuniform vec4 vClearCoatTintParams;\nuniform float clearCoatColorAtDistance;\n#ifdef CLEARCOAT_TINT_TEXTURE\nuniform vec2 vClearCoatTintInfos;\nuniform mat4 clearCoatTintMatrix;\n#endif\n#endif\n#endif\n\n#ifdef ANISOTROPIC\nuniform vec3 vAnisotropy;\n#ifdef ANISOTROPIC_TEXTURE\nuniform vec2 vAnisotropyInfos;\nuniform mat4 anisotropyMatrix;\n#endif\n#endif\n\n#ifdef SHEEN\nuniform vec4 vSheenColor;\n#ifdef SHEEN_TEXTURE\nuniform vec2 vSheenInfos;\nuniform mat4 sheenMatrix;\n#endif\n#endif\n\n#ifdef SUBSURFACE\n#ifdef SS_REFRACTION\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\n#endif\n#ifdef SS_THICKNESSANDMASK_TEXTURE\nuniform vec2 vThicknessInfos;\nuniform mat4 thicknessMatrix;;\n#endif\nuniform vec2 vThicknessParam;\nuniform vec3 vDiffusionDistance;\nuniform vec4 vTintColor;\nuniform vec3 vSubSurfaceIntensity;\n#endif";zt.a.IncludesShadersStore.pbrFragmentDeclaration=Gr;var zr="layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec4 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize;\nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float pointSize;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float visibility;\nuniform vec2 vClearCoatParams;\nuniform vec4 vClearCoatRefractionParams;\nuniform vec2 vClearCoatInfos;\nuniform mat4 clearCoatMatrix;\nuniform vec2 vClearCoatBumpInfos;\nuniform vec2 vClearCoatTangentSpaceParams;\nuniform mat4 clearCoatBumpMatrix;\nuniform vec4 vClearCoatTintParams;\nuniform float clearCoatColorAtDistance;\nuniform vec2 vClearCoatTintInfos;\nuniform mat4 clearCoatTintMatrix;\nuniform vec3 vAnisotropy;\nuniform vec2 vAnisotropyInfos;\nuniform mat4 anisotropyMatrix;\nuniform vec4 vSheenColor;\nuniform vec2 vSheenInfos;\nuniform mat4 sheenMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec2 vThicknessInfos;\nuniform mat4 thicknessMatrix;\nuniform vec2 vThicknessParam;\nuniform vec3 vDiffusionDistance;\nuniform vec4 vTintColor;\nuniform vec3 vSubSurfaceIntensity;\n};\nuniform Scene {\nmat4 viewProjection;\n#ifdef MULTIVIEW\nmat4 viewProjectionR;\n#endif\nmat4 view;\n};";zt.a.IncludesShadersStore.pbrUboDeclaration=zr;var jr="uniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#if DEBUGMODE>0\nuniform vec2 vDebugMode;\nvarying vec4 vClipSpacePosition;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif";zt.a.IncludesShadersStore.pbrFragmentExtraDeclaration=jr;var Wr="#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n#ifdef CLEARCOAT\n#ifdef CLEARCOAT_TEXTURE\n#if CLEARCOAT_TEXTUREDIRECTUV == 1\n#define vClearCoatUV vMainUV1\n#elif CLEARCOAT_TEXTUREDIRECTUV == 2\n#define vClearCoatUV vMainUV2\n#else\nvarying vec2 vClearCoatUV;\n#endif\nuniform sampler2D clearCoatSampler;\n#endif\n#ifdef CLEARCOAT_BUMP\n#if CLEARCOAT_BUMPDIRECTUV == 1\n#define vClearCoatBumpUV vMainUV1\n#elif CLEARCOAT_BUMPDIRECTUV == 2\n#define vClearCoatBumpUV vMainUV2\n#else\nvarying vec2 vClearCoatBumpUV;\n#endif\nuniform sampler2D clearCoatBumpSampler;\n#endif\n#ifdef CLEARCOAT_TINT_TEXTURE\n#if CLEARCOAT_TINT_TEXTUREDIRECTUV == 1\n#define vClearCoatTintUV vMainUV1\n#elif CLEARCOAT_TINT_TEXTUREDIRECTUV == 2\n#define vClearCoatTintUV vMainUV2\n#else\nvarying vec2 vClearCoatTintUV;\n#endif\nuniform sampler2D clearCoatTintSampler;\n#endif\n#endif\n#ifdef SHEEN\n#ifdef SHEEN_TEXTURE\n#if SHEEN_TEXTUREDIRECTUV == 1\n#define vSheenUV vMainUV1\n#elif SHEEN_TEXTUREDIRECTUV == 2\n#define vSheenUV vMainUV2\n#else\nvarying vec2 vSheenUV;\n#endif\nuniform sampler2D sheenSampler;\n#endif\n#endif\n#ifdef ANISOTROPIC\n#ifdef ANISOTROPIC_TEXTURE\n#if ANISOTROPIC_TEXTUREDIRECTUV == 1\n#define vAnisotropyUV vMainUV1\n#elif ANISOTROPIC_TEXTUREDIRECTUV == 2\n#define vAnisotropyUV vMainUV2\n#else\nvarying vec2 vAnisotropyUV;\n#endif\nuniform sampler2D anisotropySampler;\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#ifdef USEIRRADIANCEMAP\nuniform samplerCube irradianceSampler;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform sampler2D reflectionSamplerLow;\nuniform sampler2D reflectionSamplerHigh;\n#endif\n#ifdef USEIRRADIANCEMAP\nuniform sampler2D irradianceSampler;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifdef SUBSURFACE\n#ifdef SS_REFRACTION\n#ifdef SS_REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n#ifdef SS_THICKNESSANDMASK_TEXTURE\n#if SS_THICKNESSANDMASK_TEXTUREDIRECTUV == 1\n#define vThicknessUV vMainUV1\n#elif SS_THICKNESSANDMASK_TEXTUREDIRECTUV == 2\n#define vThicknessUV vMainUV2\n#else\nvarying vec2 vThicknessUV;\n#endif\nuniform sampler2D thicknessSampler;\n#endif\n#endif";zt.a.IncludesShadersStore.pbrFragmentSamplersDeclaration=Wr;i(89);var Hr="\n#define RECIPROCAL_PI2 0.15915494\n#define RECIPROCAL_PI 0.31830988618\n\n#define MINIMUMVARIANCE 0.0005\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nreturn square(roughness)+MINIMUMVARIANCE;\n}\nfloat fresnelGrazingReflectance(float reflectance0) {\n\n\nfloat reflectance90=saturate(reflectance0*25.0);\nreturn reflectance90;\n}\nvec2 getAARoughnessFactors(vec3 normalVector) {\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalVector.xyz);\nvec3 nDfdy=dFdy(normalVector.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(saturate(slopeSquare),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n\ngeometricAlphaGFactor*=0.75;\nreturn vec2(geometricRoughnessFactor,geometricAlphaGFactor);\n#else\nreturn vec2(0.);\n#endif\n}\n#ifdef ANISOTROPIC\n\n\nvec2 getAnisotropicRoughness(float alphaG,float anisotropy) {\nfloat alphaT=max(alphaG*(1.0+anisotropy),MINIMUMVARIANCE);\nfloat alphaB=max(alphaG*(1.0-anisotropy),MINIMUMVARIANCE);\nreturn vec2(alphaT,alphaB);\n}\n\n\nvec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy) {\nvec3 anisotropicFrameDirection=anisotropy>=0.0 ? B : T;\nvec3 anisotropicFrameTangent=cross(normalize(anisotropicFrameDirection),V);\nvec3 anisotropicFrameNormal=cross(anisotropicFrameTangent,anisotropicFrameDirection);\nvec3 anisotropicNormal=normalize(mix(N,anisotropicFrameNormal,abs(anisotropy)));\nreturn anisotropicNormal;\n\n}\n#endif\n#if defined(CLEARCOAT) || defined(SS_REFRACTION)\n\n\n\nvec3 cocaLambert(vec3 alpha,float distance) {\nreturn exp(-alpha*distance);\n}\n\nvec3 cocaLambert(float NdotVRefract,float NdotLRefract,vec3 alpha,float thickness) {\nreturn cocaLambert(alpha,(thickness*((NdotLRefract+NdotVRefract)/(NdotLRefract*NdotVRefract))));\n}\n\nvec3 computeColorAtDistanceInMedia(vec3 color,float distance) {\nreturn -log(color)/distance;\n}\nvec3 computeClearCoatAbsorption(float NdotVRefract,float NdotLRefract,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {\nvec3 clearCoatAbsorption=mix(vec3(1.0),\ncocaLambert(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness),\nclearCoatIntensity);\nreturn clearCoatAbsorption;\n}\n#endif\n\n\n\n\n#ifdef MICROSURFACEAUTOMATIC\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n#endif";zt.a.IncludesShadersStore.pbrHelperFunctions=Hr;var Xr="#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifdef SPHERICAL_HARMONICS\nuniform vec3 vSphericalL00;\nuniform vec3 vSphericalL1_1;\nuniform vec3 vSphericalL10;\nuniform vec3 vSphericalL11;\nuniform vec3 vSphericalL2_2;\nuniform vec3 vSphericalL2_1;\nuniform vec3 vSphericalL20;\nuniform vec3 vSphericalL21;\nuniform vec3 vSphericalL22;\n\n\n\n\n\n\n\nvec3 computeEnvironmentIrradiance(vec3 normal) {\nreturn vSphericalL00\n+vSphericalL1_1*(normal.y)\n+vSphericalL10*(normal.z)\n+vSphericalL11*(normal.x)\n+vSphericalL2_2*(normal.y*normal.x)\n+vSphericalL2_1*(normal.y*normal.z)\n+vSphericalL20*((3.0*normal.z*normal.z)-1.0)\n+vSphericalL21*(normal.z*normal.x)\n+vSphericalL22*(normal.x*normal.x-(normal.y*normal.y));\n}\n#else\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\n\nvec3 computeEnvironmentIrradiance(vec3 normal) {\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif\n#endif";zt.a.IncludesShadersStore.harmonicsFunctions=Xr;var Yr="\nstruct preLightingInfo\n{\n\nvec3 lightOffset;\nfloat lightDistanceSquared;\nfloat lightDistance;\n\nfloat attenuation;\n\nvec3 L;\nvec3 H;\nfloat NdotV;\nfloat NdotLUnclamped;\nfloat NdotL;\nfloat VdotH;\nfloat roughness;\n};\npreLightingInfo computePointAndSpotPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {\npreLightingInfo result;\n\nresult.lightOffset=lightData.xyz-vPositionW;\nresult.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);\n\nresult.lightDistance=sqrt(result.lightDistanceSquared);\n\nresult.L=normalize(result.lightOffset);\nresult.H=normalize(V+result.L);\nresult.VdotH=saturate(dot(V,result.H));\nresult.NdotLUnclamped=dot(N,result.L);\nresult.NdotL=saturateEps(result.NdotLUnclamped);\nreturn result;\n}\npreLightingInfo computeDirectionalPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {\npreLightingInfo result;\n\nresult.lightDistance=length(-lightData.xyz);\n\nresult.L=normalize(-lightData.xyz);\nresult.H=normalize(V+result.L);\nresult.VdotH=saturate(dot(V,result.H));\nresult.NdotLUnclamped=dot(N,result.L);\nresult.NdotL=saturateEps(result.NdotLUnclamped);\nreturn result;\n}\npreLightingInfo computeHemisphericPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {\npreLightingInfo result;\n\n\nresult.NdotL=dot(N,lightData.xyz)*0.5+0.5;\nresult.NdotL=saturateEps(result.NdotL);\nresult.NdotLUnclamped=result.NdotL;\n#ifdef SPECULARTERM\nresult.L=normalize(lightData.xyz);\nresult.H=normalize(V+result.L);\nresult.VdotH=saturate(dot(V,result.H));\n#endif\nreturn result;\n}";zt.a.IncludesShadersStore.pbrDirectLightingSetupFunctions=Yr;var Kr="float computeDistanceLightFalloff_Standard(vec3 lightOffset,float range)\n{\nreturn max(0.,1.0-length(lightOffset)/range);\n}\nfloat computeDistanceLightFalloff_Physical(float lightDistanceSquared)\n{\nreturn 1.0/maxEps(lightDistanceSquared);\n}\nfloat computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange)\n{\nfloat lightDistanceFalloff=1.0/maxEps(lightDistanceSquared);\nfloat factor=lightDistanceSquared*inverseSquaredRange;\nfloat attenuation=saturate(1.0-factor*factor);\nattenuation*=attenuation;\n\nlightDistanceFalloff*=attenuation;\nreturn lightDistanceFalloff;\n}\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDistanceLightFalloff_Physical(lightDistanceSquared);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange);\n#else\nreturn computeDistanceLightFalloff_Standard(lightOffset,range);\n#endif\n}\nfloat computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\nfloat cosAngle=maxEps(dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle)\n{\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977;\n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfloat falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset)\n{\n\n\n\nfloat cd=dot(-lightDirection,directionToLightCenterW);\nfloat falloff=saturate(cd*lightAngleScale+lightAngleOffset);\n\nfalloff*=falloff;\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset);\n#else\nreturn computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent);\n#endif\n}";zt.a.IncludesShadersStore.pbrDirectLightingFalloffFunctions=Kr;var Qr="\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\n\n\n\n#ifdef MS_BRDF_ENERGY_CONSERVATION\n\n\nvec3 getEnergyConservationFactor(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {\nreturn 1.0+specularEnvironmentR0*(1.0/environmentBrdf.y-1.0);\n}\n#endif\n#ifdef ENVIRONMENTBRDF\nvec3 getBRDFLookup(float NdotV,float perceptualRoughness) {\n\nvec2 UV=vec2(NdotV,perceptualRoughness);\n\nvec4 brdfLookup=texture2D(environmentBrdfSampler,UV);\n#ifdef ENVIRONMENTBRDF_RGBD\nbrdfLookup.rgb=fromRGBD(brdfLookup.rgba);\n#endif\nreturn brdfLookup.rgb;\n}\nvec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {\n#ifdef BRDF_V_HEIGHT_CORRELATED\nvec3 reflectance=mix(environmentBrdf.xxx,environmentBrdf.yyy,specularEnvironmentR0);\n#else\nvec3 reflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#endif\nreturn reflectance;\n}\n#endif\n#if !defined(ENVIRONMENTBRDF) || defined(REFLECTIONMAP_SKYBOX) || defined(ALPHAFRESNEL)\nvec3 getReflectanceFromAnalyticalBRDFLookup_Jones(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));\n}\n#endif\n#if defined(SHEEN) && defined(REFLECTION)\n\nvec3 getSheenReflectanceFromBRDFLookup(const vec3 reflectance0,const vec3 environmentBrdf) {\nvec3 sheenEnvironmentReflectance=reflectance0*environmentBrdf.b;\nreturn sheenEnvironmentReflectance;\n}\n#endif\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);\n}\nfloat fresnelSchlickGGX(float VdotH,float reflectance0,float reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);\n}\n#ifdef CLEARCOAT\n\n\n\n\n\nvec3 getR0RemappedForClearCoat(vec3 f0) {\n#ifdef CLEARCOAT_DEFAULTIOR\n#ifdef MOBILE\nreturn saturate(f0*(f0*0.526868+0.529324)-0.0482256);\n#else\nreturn saturate(f0*(f0*(0.941892-0.263008*f0)+0.346479)-0.0285998);\n#endif\n#else\nvec3 s=sqrt(f0);\nvec3 t=(vClearCoatRefractionParams.z+vClearCoatRefractionParams.w*s)/(vClearCoatRefractionParams.w+vClearCoatRefractionParams.z*s);\nreturn t*t;\n#endif\n}\n#endif\n\n\n\n\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\n#ifdef SHEEN\n\nfloat normalDistributionFunction_CharlieSheen(float NdotH,float alphaG)\n{\nfloat invR=1./alphaG;\nfloat cos2h=NdotH*NdotH;\nfloat sin2h=1.-cos2h;\nreturn (2.+invR)*pow(sin2h,invR*.5)/(2.*PI);\n}\n#endif\n#ifdef ANISOTROPIC\n\n\nfloat normalDistributionFunction_BurleyGGX_Anisotropic(float NdotH,float TdotH,float BdotH,const vec2 alphaTB) {\nfloat a2=alphaTB.x*alphaTB.y;\nvec3 v=vec3(alphaTB.y*TdotH,alphaTB.x*BdotH,a2*NdotH);\nfloat v2=dot(v,v);\nfloat w2=a2/v2;\nreturn a2*w2*w2*RECIPROCAL_PI;\n}\n#endif\n\n\n\n\n#ifdef BRDF_V_HEIGHT_CORRELATED\n\n\n\nfloat smithVisibility_GGXCorrelated(float NdotL,float NdotV,float alphaG) {\n#ifdef MOBILE\n\nfloat GGXV=NdotL*(NdotV*(1.0-alphaG)+alphaG);\nfloat GGXL=NdotV*(NdotL*(1.0-alphaG)+alphaG);\nreturn 0.5/(GGXV+GGXL);\n#else\nfloat a2=alphaG*alphaG;\nfloat GGXV=NdotL*sqrt(NdotV*(NdotV-a2*NdotV)+a2);\nfloat GGXL=NdotV*sqrt(NdotL*(NdotL-a2*NdotL)+a2);\nreturn 0.5/(GGXV+GGXL);\n#endif\n}\n#else\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfloat smithVisibilityG1_TrowbridgeReitzGGXFast(float dot,float alphaG)\n{\n#ifdef MOBILE\n\nreturn 1.0/(dot+alphaG+(1.0-alphaG)*dot ));\n#else\nfloat alphaSquared=alphaG*alphaG;\nreturn 1.0/(dot+sqrt(alphaSquared+(1.0-alphaSquared)*dot*dot));\n#endif\n}\nfloat smithVisibility_TrowbridgeReitzGGXFast(float NdotL,float NdotV,float alphaG)\n{\nfloat visibility=smithVisibilityG1_TrowbridgeReitzGGXFast(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGXFast(NdotV,alphaG);\n\nreturn visibility;\n}\n#endif\n#ifdef ANISOTROPIC\n\n\nfloat smithVisibility_GGXCorrelated_Anisotropic(float NdotL,float NdotV,float TdotV,float BdotV,float TdotL,float BdotL,const vec2 alphaTB) {\nfloat lambdaV=NdotL*length(vec3(alphaTB.x*TdotV,alphaTB.y*BdotV,NdotV));\nfloat lambdaL=NdotV*length(vec3(alphaTB.x*TdotL,alphaTB.y*BdotL,NdotL));\nfloat v=0.5/(lambdaV+lambdaL);\nreturn v;\n}\n#endif\n#ifdef CLEARCOAT\nfloat visibility_Kelemen(float VdotH) {\n\n\n\nreturn 0.25/(VdotH*VdotH);\n}\n#endif\n#ifdef SHEEN\n\n\n\nfloat visibility_Ashikhmin(float NdotL,float NdotV)\n{\nreturn 1./(4.*(NdotL+NdotV-NdotL*NdotV));\n}\n#endif\n\n\n\n\n\n\n\nfloat diffuseBRDF_Burley(float NdotL,float NdotV,float VdotH,float roughness) {\n\n\nfloat diffuseFresnelNV=pow5(saturateEps(1.0-NdotL));\nfloat diffuseFresnelNL=pow5(saturateEps(1.0-NdotV));\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel/PI;\n}\n#ifdef SS_TRANSLUCENCY\n\n\nvec3 transmittanceBRDF_Burley(const vec3 tintColor,const vec3 diffusionDistance,float thickness) {\nvec3 S=1./maxEps(diffusionDistance);\nvec3 temp=exp((-0.333333333*thickness)*S);\nreturn tintColor.rgb*0.25*(temp*temp*temp+3.0*temp);\n}\n\n\nfloat computeWrappedDiffuseNdotL(float NdotL,float w) {\nfloat t=1.0+w;\nfloat invt2=1.0/square(t);\nreturn saturate((NdotL+w)*invt2);\n}\n#endif\n";zt.a.IncludesShadersStore.pbrBRDFFunctions=Qr;var qr="#define CLEARCOATREFLECTANCE90 1.0\n\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef CLEARCOAT\n\n\nvec4 clearCoat;\n#endif\n#ifdef SHEEN\nvec3 sheen;\n#endif\n};\n\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance) {\n#if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF)\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=saturate(lightRoughness+roughness);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nvec3 computeHemisphericDiffuseLighting(preLightingInfo info,vec3 lightColor,vec3 groundColor) {\nreturn mix(groundColor,lightColor,info.NdotL);\n}\nvec3 computeDiffuseLighting(preLightingInfo info,vec3 lightColor) {\nfloat diffuseTerm=diffuseBRDF_Burley(info.NdotL,info.NdotV,info.VdotH,info.roughness);\nreturn diffuseTerm*info.attenuation*info.NdotL*lightColor;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}\n#ifdef SS_TRANSLUCENCY\nvec3 computeDiffuseAndTransmittedLighting(preLightingInfo info,vec3 lightColor,vec3 transmittance) {\nfloat NdotL=absEps(info.NdotLUnclamped);\n\nfloat wrapNdotL=computeWrappedDiffuseNdotL(NdotL,0.02);\n\nfloat trAdapt=step(0.,info.NdotLUnclamped);\nvec3 transmittanceNdotL=mix(transmittance*wrapNdotL,vec3(wrapNdotL),trAdapt);\nfloat diffuseTerm=diffuseBRDF_Burley(NdotL,info.NdotV,info.VdotH,info.roughness);\nreturn diffuseTerm*transmittanceNdotL*info.attenuation*lightColor;\n}\n#endif\n#ifdef SPECULARTERM\nvec3 computeSpecularLighting(preLightingInfo info,vec3 N,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {\nfloat NdotH=saturateEps(dot(N,info.H));\nfloat roughness=max(info.roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nvec3 fresnel=fresnelSchlickGGX(info.VdotH,reflectance0,reflectance90);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\n#ifdef BRDF_V_HEIGHT_CORRELATED\nfloat visibility=smithVisibility_GGXCorrelated(info.NdotL,info.NdotV,alphaG);\n#else\nfloat visibility=smithVisibility_TrowbridgeReitzGGXFast(info.NdotL,info.NdotV,alphaG);\n#endif\nvec3 specTerm=fresnel*distribution*visibility;\nreturn specTerm*info.attenuation*info.NdotL*lightColor;\n}\n#endif\n#ifdef ANISOTROPIC\nvec3 computeAnisotropicSpecularLighting(preLightingInfo info,vec3 V,vec3 N,vec3 T,vec3 B,float anisotropy,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {\nfloat NdotH=saturateEps(dot(N,info.H));\nfloat TdotH=dot(T,info.H);\nfloat BdotH=dot(B,info.H);\nfloat TdotV=dot(T,V);\nfloat BdotV=dot(B,V);\nfloat TdotL=dot(T,info.L);\nfloat BdotL=dot(B,info.L);\nfloat alphaG=convertRoughnessToAverageSlope(info.roughness);\nvec2 alphaTB=getAnisotropicRoughness(alphaG,anisotropy);\nalphaTB=max(alphaTB,square(geometricRoughnessFactor));\nvec3 fresnel=fresnelSchlickGGX(info.VdotH,reflectance0,reflectance90);\nfloat distribution=normalDistributionFunction_BurleyGGX_Anisotropic(NdotH,TdotH,BdotH,alphaTB);\nfloat visibility=smithVisibility_GGXCorrelated_Anisotropic(info.NdotL,info.NdotV,TdotV,BdotV,TdotL,BdotL,alphaTB);\nvec3 specTerm=fresnel*distribution*visibility;\nreturn specTerm*info.attenuation*info.NdotL*lightColor;\n}\n#endif\n#ifdef CLEARCOAT\nvec4 computeClearCoatLighting(preLightingInfo info,vec3 Ncc,float geometricRoughnessFactor,float clearCoatIntensity,vec3 lightColor) {\nfloat NccdotL=saturateEps(dot(Ncc,info.L));\nfloat NccdotH=saturateEps(dot(Ncc,info.H));\nfloat clearCoatRoughness=max(info.roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(clearCoatRoughness);\nfloat fresnel=fresnelSchlickGGX(info.VdotH,vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);\nfresnel*=clearCoatIntensity;\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NccdotH,alphaG);\nfloat visibility=visibility_Kelemen(info.VdotH);\nfloat clearCoatTerm=fresnel*distribution*visibility;\nreturn vec4(\nclearCoatTerm*info.attenuation*NccdotL*lightColor,\n1.0-fresnel\n);\n}\nvec3 computeClearCoatLightingAbsorption(float NdotVRefract,vec3 L,vec3 Ncc,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {\nvec3 LRefract=-refract(L,Ncc,vClearCoatRefractionParams.y);\nfloat NdotLRefract=saturateEps(dot(Ncc,LRefract));\nvec3 absorption=computeClearCoatAbsorption(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness,clearCoatIntensity);\nreturn absorption;\n}\n#endif\n#ifdef SHEEN\nvec3 computeSheenLighting(preLightingInfo info,vec3 N,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {\nfloat NdotH=saturateEps(dot(N,info.H));\nfloat roughness=max(info.roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n\nvec3 fresnel=reflectance0;\nfloat distribution=normalDistributionFunction_CharlieSheen(NdotH,alphaG);\nfloat visibility=visibility_Ashikhmin(info.NdotL,info.NdotV);\nvec3 sheenTerm=fresnel*distribution*visibility;\nreturn sheenTerm*info.attenuation*info.NdotL*lightColor;\n}\n#endif\n";zt.a.IncludesShadersStore.pbrDirectLightingFunctions=qr;var Zr="#if defined(REFLECTION) || defined(SS_REFRACTION)\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float microsurfaceAverageSlope) {\nfloat microsurfaceAverageSlopeTexels=cubeMapDimensionPixels*microsurfaceAverageSlope;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat getLinearLodFromRoughness(float cubeMapDimensionPixels,float roughness) {\nfloat lod=log2(cubeMapDimensionPixels)*roughness;\nreturn lod;\n}\n#endif\n#if defined(ENVIRONMENTBRDF) && defined(RADIANCEOCCLUSION)\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn saturate(square(temp)-1.0+ambientOcclusion);\n}\n#endif\n#if defined(ENVIRONMENTBRDF) && defined(HORIZONOCCLUSION)\nfloat environmentHorizonOcclusion(vec3 view,vec3 normal) {\n\nvec3 reflection=reflect(view,normal);\nfloat temp=saturate(1.0+1.1*dot(reflection,normal));\nreturn square(temp);\n}\n#endif\n\n\n\n\n#if defined(LODINREFLECTIONALPHA) || defined(SS_LODINREFRACTIONALPHA)\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nreturn getLodFromAlphaG(cubeMapDimensionPixels,microsurfaceAverageSlope);\n}\n#endif";zt.a.IncludesShadersStore.pbrIBLFunctions=Zr;i(122),i(123),i(124),i(116);var Jr="#if DEBUGMODE>0\nif (vClipSpacePosition.x/vClipSpacePosition.w=1)&&e.prototype.needAlphaBlendingForMesh.call(this,t)},t.prototype.needAlphaTesting=function(){return!!this._forceAlphaTest||!this.subSurface.disableAlphaBlending&&(null!=this._albedoTexture&&this._albedoTexture.hasAlpha&&(null==this._transparencyMode||this._transparencyMode===t.PBRMATERIAL_ALPHATEST))},t.prototype._shouldUseAlphaFromAlbedoTexture=function(){return null!=this._albedoTexture&&this._albedoTexture.hasAlpha&&this._useAlphaFromAlbedoTexture&&this._transparencyMode!==t.PBRMATERIAL_OPAQUE},t.prototype.getAlphaTestTexture=function(){return this._albedoTexture},t.prototype.isReadyForSubMesh=function(e,t,i){if(t.effect&&this.isFrozen&&this._wasPreviouslyReady)return!0;t._materialDefines||(t._materialDefines=new io);var n=t._materialDefines;if(!this.checkReadyOnEveryCall&&t.effect&&n._renderId===this.getScene().getRenderId())return!0;var r=this.getScene(),o=r.getEngine();if(n._areTexturesDirty&&r.texturesEnabled){if(this._albedoTexture&&Pr.a.DiffuseTextureEnabled&&!this._albedoTexture.isReadyOrNotBlocking())return!1;if(this._ambientTexture&&Pr.a.AmbientTextureEnabled&&!this._ambientTexture.isReadyOrNotBlocking())return!1;if(this._opacityTexture&&Pr.a.OpacityTextureEnabled&&!this._opacityTexture.isReadyOrNotBlocking())return!1;var s=this._getReflectionTexture();if(s&&Pr.a.ReflectionTextureEnabled){if(!s.isReadyOrNotBlocking())return!1;if(s.irradianceTexture&&!s.irradianceTexture.isReadyOrNotBlocking())return!1}if(this._lightmapTexture&&Pr.a.LightmapTextureEnabled&&!this._lightmapTexture.isReadyOrNotBlocking())return!1;if(this._emissiveTexture&&Pr.a.EmissiveTextureEnabled&&!this._emissiveTexture.isReadyOrNotBlocking())return!1;if(Pr.a.SpecularTextureEnabled){if(this._metallicTexture){if(!this._metallicTexture.isReadyOrNotBlocking())return!1}else if(this._reflectivityTexture&&!this._reflectivityTexture.isReadyOrNotBlocking())return!1;if(this._microSurfaceTexture&&!this._microSurfaceTexture.isReadyOrNotBlocking())return!1}if(o.getCaps().standardDerivatives&&this._bumpTexture&&Pr.a.BumpTextureEnabled&&!this._disableBumpMap&&!this._bumpTexture.isReady())return!1;if(this._environmentBRDFTexture&&Pr.a.ReflectionTextureEnabled&&!this._environmentBRDFTexture.isReady())return!1}if(!(this.subSurface.isReadyForSubMesh(n,r)&&this.clearCoat.isReadyForSubMesh(n,r,o,this._disableBumpMap)&&this.sheen.isReadyForSubMesh(n,r)&&this.anisotropy.isReadyForSubMesh(n,r)))return!1;if(n._areImageProcessingDirty&&this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady())return!1;o.getCaps().standardDerivatives||e.isVerticesDataPresent(Oi.b.NormalKind)||(e.createNormals(!0),p.a.Warn("PBRMaterial: Normals have been created for the mesh: "+e.name));var a=t.effect,c=this._prepareEffect(e,n,this.onCompiled,this.onError,i);return c&&(this.allowShaderHotSwapping&&a&&!c.isReady()?(c=a,n.markAsUnprocessed()):(r.resetCachedMaterial(),t.setEffect(c,n),this.buildUniformLayout())),!(!t.effect||!t.effect.isReady())&&(n._renderId=r.getRenderId(),this._wasPreviouslyReady=!0,!0)},t.prototype.isMetallicWorkflow=function(){return!(null==this._metallic&&null==this._roughness&&!this._metallicTexture)},t.prototype._prepareEffect=function(e,t,i,n,r,o){if(void 0===i&&(i=null),void 0===n&&(n=null),void 0===r&&(r=null),void 0===o&&(o=null),this._prepareDefines(e,t,r,o),!t.isDirty)return null;t.markAsProcessed();var s=this.getScene().getEngine(),a=new zt.c,c=0;t.USESPHERICALINVERTEX&&a.addFallback(c++,"USESPHERICALINVERTEX"),t.FOG&&a.addFallback(c,"FOG"),t.SPECULARAA&&a.addFallback(c,"SPECULARAA"),t.POINTSIZE&&a.addFallback(c,"POINTSIZE"),t.LOGARITHMICDEPTH&&a.addFallback(c,"LOGARITHMICDEPTH"),t.PARALLAX&&a.addFallback(c,"PARALLAX"),t.PARALLAXOCCLUSION&&a.addFallback(c++,"PARALLAXOCCLUSION"),c=Br.AddFallbacks(t,a,c),c=Br.AddFallbacks(t,a,c),c=kr.AddFallbacks(t,a,c),c=Vr.AddFallbacks(t,a,c),t.ENVIRONMENTBRDF&&a.addFallback(c++,"ENVIRONMENTBRDF"),t.TANGENT&&a.addFallback(c++,"TANGENT"),t.BUMP&&a.addFallback(c++,"BUMP"),c=Er.a.HandleFallbacksForShadows(t,a,this._maxSimultaneousLights,c++),t.SPECULARTERM&&a.addFallback(c++,"SPECULARTERM"),t.USESPHERICALFROMREFLECTIONMAP&&a.addFallback(c++,"USESPHERICALFROMREFLECTIONMAP"),t.USEIRRADIANCEMAP&&a.addFallback(c++,"USEIRRADIANCEMAP"),t.LIGHTMAP&&a.addFallback(c++,"LIGHTMAP"),t.NORMAL&&a.addFallback(c++,"NORMAL"),t.AMBIENT&&a.addFallback(c++,"AMBIENT"),t.EMISSIVE&&a.addFallback(c++,"EMISSIVE"),t.VERTEXCOLOR&&a.addFallback(c++,"VERTEXCOLOR"),t.NUM_BONE_INFLUENCERS>0&&a.addCPUSkinningFallback(c++,e),t.MORPHTARGETS&&a.addFallback(c++,"MORPHTARGETS"),t.MULTIVIEW&&a.addFallback(0,"MULTIVIEW");var l=[Oi.b.PositionKind];t.NORMAL&&l.push(Oi.b.NormalKind),t.TANGENT&&l.push(Oi.b.TangentKind),t.UV1&&l.push(Oi.b.UVKind),t.UV2&&l.push(Oi.b.UV2Kind),t.VERTEXCOLOR&&l.push(Oi.b.ColorKind),Er.a.PrepareAttributesForBones(l,e,t,a),Er.a.PrepareAttributesForInstances(l,t),Er.a.PrepareAttributesForMorphTargets(l,e,t);var u="pbr",h=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vAlbedoColor","vReflectivityColor","vEmissiveColor","visibility","vReflectionColor","vFogInfos","vFogColor","pointSize","vAlbedoInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vReflectionPosition","vReflectionSize","vEmissiveInfos","vReflectivityInfos","vMicroSurfaceSamplerInfos","vBumpInfos","vLightmapInfos","mBones","vClipPlane","vClipPlane2","vClipPlane3","vClipPlane4","albedoMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","reflectivityMatrix","normalMatrix","microSurfaceSamplerMatrix","bumpMatrix","lightmapMatrix","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"],d=["albedoSampler","reflectivitySampler","ambientSampler","emissiveSampler","bumpSampler","lightmapSampler","opacitySampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh","irradianceSampler","microSurfaceSampler","environmentBrdfSampler","boneSampler"],f=["Material","Scene"];kr.AddUniforms(h),kr.AddSamplers(d),Nr.AddUniforms(h),Nr.AddSamplers(d),Br.AddUniforms(h),Br.AddSamplers(d),Vr.AddUniforms(h),Vr.AddSamplers(d),Ai.a&&(Ai.a.PrepareUniforms(h,t),Ai.a.PrepareSamplers(d,t)),Er.a.PrepareUniformsAndSamplersList({uniformsNames:h,uniformBuffersNames:f,samplers:d,defines:t,maxSimultaneousLights:this._maxSimultaneousLights}),this.customShaderNameResolve&&(u=this.customShaderNameResolve(u,h,f,d,t));var p=t.toString();return s.createEffect(u,{attributes:l,uniformsNames:h,uniformBuffersNames:f,samplers:d,defines:p,fallbacks:a,onCompiled:i,onError:n,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:t.NUM_MORPH_INFLUENCERS}},s)},t.prototype._prepareDefines=function(e,i,n,r){void 0===n&&(n=null),void 0===r&&(r=null);var o=this.getScene(),s=o.getEngine();if(Er.a.PrepareDefinesForLights(o,e,i,!0,this._maxSimultaneousLights,this._disableLighting),i._needNormals=!0,Er.a.PrepareDefinesForMultiview(o,i),i.METALLICWORKFLOW=this.isMetallicWorkflow(),i._areTexturesDirty){if(i._needUVs=!1,o.texturesEnabled){o.getEngine().getCaps().textureLOD&&(i.LODBASEDMICROSFURACE=!0),this._albedoTexture&&Pr.a.DiffuseTextureEnabled?Er.a.PrepareDefinesForMergedUV(this._albedoTexture,i,"ALBEDO"):i.ALBEDO=!1,this._ambientTexture&&Pr.a.AmbientTextureEnabled?(Er.a.PrepareDefinesForMergedUV(this._ambientTexture,i,"AMBIENT"),i.AMBIENTINGRAYSCALE=this._useAmbientInGrayScale):i.AMBIENT=!1,this._opacityTexture&&Pr.a.OpacityTextureEnabled?(Er.a.PrepareDefinesForMergedUV(this._opacityTexture,i,"OPACITY"),i.OPACITYRGB=this._opacityTexture.getAlphaFromRGB):i.OPACITY=!1;var a=this._getReflectionTexture();if(a&&Pr.a.ReflectionTextureEnabled){switch(i.REFLECTION=!0,i.GAMMAREFLECTION=a.gammaSpace,i.RGBDREFLECTION=a.isRGBD,i.REFLECTIONMAP_OPPOSITEZ=this.getScene().useRightHandedSystem?!a.invertZ:a.invertZ,i.LODINREFLECTIONALPHA=a.lodLevelInAlpha,i.LINEARSPECULARREFLECTION=a.linearSpecularLOD,a.coordinatesMode===Ge.a.INVCUBIC_MODE&&(i.INVERTCUBICMAP=!0),i.REFLECTIONMAP_3D=a.isCube,i.REFLECTIONMAP_CUBIC=!1,i.REFLECTIONMAP_EXPLICIT=!1,i.REFLECTIONMAP_PLANAR=!1,i.REFLECTIONMAP_PROJECTION=!1,i.REFLECTIONMAP_SKYBOX=!1,i.REFLECTIONMAP_SPHERICAL=!1,i.REFLECTIONMAP_EQUIRECTANGULAR=!1,i.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,i.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,i.REFLECTIONMAP_SKYBOX_TRANSFORMED=!1,a.coordinatesMode){case Ge.a.EXPLICIT_MODE:i.REFLECTIONMAP_EXPLICIT=!0;break;case Ge.a.PLANAR_MODE:i.REFLECTIONMAP_PLANAR=!0;break;case Ge.a.PROJECTION_MODE:i.REFLECTIONMAP_PROJECTION=!0;break;case Ge.a.SKYBOX_MODE:i.REFLECTIONMAP_SKYBOX=!0;break;case Ge.a.SPHERICAL_MODE:i.REFLECTIONMAP_SPHERICAL=!0;break;case Ge.a.EQUIRECTANGULAR_MODE:i.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case Ge.a.FIXED_EQUIRECTANGULAR_MODE:i.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case Ge.a.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:i.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case Ge.a.CUBIC_MODE:case Ge.a.INVCUBIC_MODE:default:i.REFLECTIONMAP_CUBIC=!0,i.USE_LOCAL_REFLECTIONMAP_CUBIC=!!a.boundingBoxSize}a.coordinatesMode!==Ge.a.SKYBOX_MODE?a.irradianceTexture?(i.USEIRRADIANCEMAP=!0,i.USESPHERICALFROMREFLECTIONMAP=!1):a.sphericalPolynomial&&(i.USESPHERICALFROMREFLECTIONMAP=!0,i.USEIRRADIANCEMAP=!1,this._forceIrradianceInFragment||o.getEngine().getCaps().maxVaryingVectors<=8?i.USESPHERICALINVERTEX=!1:i.USESPHERICALINVERTEX=!0):i.REFLECTIONMAP_SKYBOX_TRANSFORMED=!a.getReflectionTextureMatrix().isIdentity()}else i.REFLECTION=!1,i.REFLECTIONMAP_3D=!1,i.REFLECTIONMAP_SPHERICAL=!1,i.REFLECTIONMAP_PLANAR=!1,i.REFLECTIONMAP_CUBIC=!1,i.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,i.REFLECTIONMAP_PROJECTION=!1,i.REFLECTIONMAP_SKYBOX=!1,i.REFLECTIONMAP_SKYBOX_TRANSFORMED=!1,i.REFLECTIONMAP_EXPLICIT=!1,i.REFLECTIONMAP_EQUIRECTANGULAR=!1,i.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,i.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,i.INVERTCUBICMAP=!1,i.USESPHERICALFROMREFLECTIONMAP=!1,i.USEIRRADIANCEMAP=!1,i.USESPHERICALINVERTEX=!1,i.REFLECTIONMAP_OPPOSITEZ=!1,i.LODINREFLECTIONALPHA=!1,i.GAMMAREFLECTION=!1,i.RGBDREFLECTION=!1,i.LINEARSPECULARREFLECTION=!1;this._lightmapTexture&&Pr.a.LightmapTextureEnabled?(Er.a.PrepareDefinesForMergedUV(this._lightmapTexture,i,"LIGHTMAP"),i.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,i.GAMMALIGHTMAP=this._lightmapTexture.gammaSpace):i.LIGHTMAP=!1,this._emissiveTexture&&Pr.a.EmissiveTextureEnabled?Er.a.PrepareDefinesForMergedUV(this._emissiveTexture,i,"EMISSIVE"):i.EMISSIVE=!1,Pr.a.SpecularTextureEnabled?(this._metallicTexture?(Er.a.PrepareDefinesForMergedUV(this._metallicTexture,i,"REFLECTIVITY"),i.ROUGHNESSSTOREINMETALMAPALPHA=this._useRoughnessFromMetallicTextureAlpha,i.ROUGHNESSSTOREINMETALMAPGREEN=!this._useRoughnessFromMetallicTextureAlpha&&this._useRoughnessFromMetallicTextureGreen,i.METALLNESSSTOREINMETALMAPBLUE=this._useMetallnessFromMetallicTextureBlue,i.AOSTOREINMETALMAPRED=this._useAmbientOcclusionFromMetallicTextureRed):this._reflectivityTexture?(Er.a.PrepareDefinesForMergedUV(this._reflectivityTexture,i,"REFLECTIVITY"),i.MICROSURFACEFROMREFLECTIVITYMAP=this._useMicroSurfaceFromReflectivityMapAlpha,i.MICROSURFACEAUTOMATIC=this._useAutoMicroSurfaceFromReflectivityMap):i.REFLECTIVITY=!1,this._microSurfaceTexture?Er.a.PrepareDefinesForMergedUV(this._microSurfaceTexture,i,"MICROSURFACEMAP"):i.MICROSURFACEMAP=!1):(i.REFLECTIVITY=!1,i.MICROSURFACEMAP=!1),o.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&Pr.a.BumpTextureEnabled&&!this._disableBumpMap?(Er.a.PrepareDefinesForMergedUV(this._bumpTexture,i,"BUMP"),this._useParallax&&this._albedoTexture&&Pr.a.DiffuseTextureEnabled?(i.PARALLAX=!0,i.PARALLAXOCCLUSION=!!this._useParallaxOcclusion):i.PARALLAX=!1,i.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap):i.BUMP=!1,this._environmentBRDFTexture&&Pr.a.ReflectionTextureEnabled?(i.ENVIRONMENTBRDF=!0,i.ENVIRONMENTBRDF_RGBD=this._environmentBRDFTexture.isRGBD):(i.ENVIRONMENTBRDF=!1,i.ENVIRONMENTBRDF_RGBD=!1),this._shouldUseAlphaFromAlbedoTexture()?i.ALPHAFROMALBEDO=!0:i.ALPHAFROMALBEDO=!1}i.SPECULAROVERALPHA=this._useSpecularOverAlpha,this._lightFalloff===t.LIGHTFALLOFF_STANDARD?(i.USEPHYSICALLIGHTFALLOFF=!1,i.USEGLTFLIGHTFALLOFF=!1):this._lightFalloff===t.LIGHTFALLOFF_GLTF?(i.USEPHYSICALLIGHTFALLOFF=!1,i.USEGLTFLIGHTFALLOFF=!0):(i.USEPHYSICALLIGHTFALLOFF=!0,i.USEGLTFLIGHTFALLOFF=!1),i.RADIANCEOVERALPHA=this._useRadianceOverAlpha,!this.backFaceCulling&&this._twoSidedLighting?i.TWOSIDEDLIGHTING=!0:i.TWOSIDEDLIGHTING=!1,i.ALPHATESTVALUE=this._alphaCutOff+(this._alphaCutOff%1==0?".":""),i.PREMULTIPLYALPHA=this.alphaMode===_.a.ALPHA_PREMULTIPLIED||this.alphaMode===_.a.ALPHA_PREMULTIPLIED_PORTERDUFF,i.ALPHABLEND=this.needAlphaBlendingForMesh(e),i.ALPHAFRESNEL=this._useAlphaFresnel||this._useLinearAlphaFresnel,i.LINEARALPHAFRESNEL=this._useLinearAlphaFresnel,i.SPECULARAA=o.getEngine().getCaps().standardDerivatives&&this._enableSpecularAntiAliasing}i._areImageProcessingDirty&&this._imageProcessingConfiguration&&this._imageProcessingConfiguration.prepareDefines(i),i.FORCENORMALFORWARD=this._forceNormalForward,i.RADIANCEOCCLUSION=this._useRadianceOcclusion,i.HORIZONOCCLUSION=this._useHorizonOcclusion,i._areMiscDirty&&(Er.a.PrepareDefinesForMisc(e,o,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,i),i.UNLIT=this._unlit||(this.pointsCloud||this.wireframe)&&!e.isVerticesDataPresent(Oi.b.NormalKind),i.DEBUGMODE=this._debugMode),this.subSurface.prepareDefines(i,o),this.clearCoat.prepareDefines(i,o),this.anisotropy.prepareDefines(i,e,o),this.brdf.prepareDefines(i),this.sheen.prepareDefines(i,o),Er.a.PrepareDefinesForFrameBoundValues(o,s,i,!!n,r),Er.a.PrepareDefinesForAttributes(e,i,!0,!0,!0,this._transparencyMode!==t.PBRMATERIAL_OPAQUE)},t.prototype.forceCompilation=function(e,t,i){var n=this,r=l.a({clipPlane:!1},i),o=new io,s=this._prepareEffect(e,o,void 0,void 0,void 0,r.clipPlane);s.isReady()?t&&t(this):s.onCompileObservable.add(function(){t&&t(n)})},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("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),Nr.PrepareUniformBuffer(e),Br.PrepareUniformBuffer(e),Vr.PrepareUniformBuffer(e),kr.PrepareUniformBuffer(e),e.create()},t.prototype.unbind=function(){if(this._activeEffect){var t=!1;this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&(this._activeEffect.setTexture("reflection2DSampler",null),t=!0),this.subSurface.unbind(this._activeEffect)&&(t=!0),t&&this._markAllSubMeshesAsTexturesDirty()}e.prototype.unbind.call(this)},t.prototype.bindForSubMesh=function(e,i,n){var r=this.getScene(),s=n._materialDefines;if(s){var a=n.effect;if(a){this._activeEffect=a,s.INSTANCES||this.bindOnlyWorldMatrix(e),s.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));var c=this._mustRebind(r,a,i.visibility);Er.a.BindBonesParameters(i,this._activeEffect);var l=null,u=this._uniformBuffer;if(c){var h=r.getEngine();if(u.bindToEffect(a,"Material"),this.bindViewProjection(a),l=this._getReflectionTexture(),!u.useUbo||!this.isFrozen||!u.isSync){if(r.texturesEnabled){if(this._albedoTexture&&Pr.a.DiffuseTextureEnabled&&(u.updateFloat2("vAlbedoInfos",this._albedoTexture.coordinatesIndex,this._albedoTexture.level),Er.a.BindTextureMatrix(this._albedoTexture,u,"albedo")),this._ambientTexture&&Pr.a.AmbientTextureEnabled&&(u.updateFloat4("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level,this._ambientTextureStrength,this._ambientTextureImpactOnAnalyticalLights),Er.a.BindTextureMatrix(this._ambientTexture,u,"ambient")),this._opacityTexture&&Pr.a.OpacityTextureEnabled&&(u.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),Er.a.BindTextureMatrix(this._opacityTexture,u,"opacity")),l&&Pr.a.ReflectionTextureEnabled){if(u.updateMatrix("reflectionMatrix",l.getReflectionTextureMatrix()),u.updateFloat2("vReflectionInfos",l.level,0),l.boundingBoxSize){var d=l;u.updateVector3("vReflectionPosition",d.boundingBoxPosition),u.updateVector3("vReflectionSize",d.boundingBoxSize)}if(!s.USEIRRADIANCEMAP){var f=l.sphericalPolynomial;if(s.USESPHERICALFROMREFLECTIONMAP&&f)if(s.SPHERICAL_HARMONICS){var p=f.preScaledHarmonics;this._activeEffect.setVector3("vSphericalL00",p.l00),this._activeEffect.setVector3("vSphericalL1_1",p.l1_1),this._activeEffect.setVector3("vSphericalL10",p.l10),this._activeEffect.setVector3("vSphericalL11",p.l11),this._activeEffect.setVector3("vSphericalL2_2",p.l2_2),this._activeEffect.setVector3("vSphericalL2_1",p.l2_1),this._activeEffect.setVector3("vSphericalL20",p.l20),this._activeEffect.setVector3("vSphericalL21",p.l21),this._activeEffect.setVector3("vSphericalL22",p.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)}u.updateFloat3("vReflectionMicrosurfaceInfos",l.getSize().width,l.lodGenerationScale,l.lodGenerationOffset)}this._emissiveTexture&&Pr.a.EmissiveTextureEnabled&&(u.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),Er.a.BindTextureMatrix(this._emissiveTexture,u,"emissive")),this._lightmapTexture&&Pr.a.LightmapTextureEnabled&&(u.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),Er.a.BindTextureMatrix(this._lightmapTexture,u,"lightmap")),Pr.a.SpecularTextureEnabled&&(this._metallicTexture?(u.updateFloat3("vReflectivityInfos",this._metallicTexture.coordinatesIndex,this._metallicTexture.level,this._ambientTextureStrength),Er.a.BindTextureMatrix(this._metallicTexture,u,"reflectivity")):this._reflectivityTexture&&(u.updateFloat3("vReflectivityInfos",this._reflectivityTexture.coordinatesIndex,this._reflectivityTexture.level,1),Er.a.BindTextureMatrix(this._reflectivityTexture,u,"reflectivity")),this._microSurfaceTexture&&(u.updateFloat2("vMicroSurfaceSamplerInfos",this._microSurfaceTexture.coordinatesIndex,this._microSurfaceTexture.level),Er.a.BindTextureMatrix(this._microSurfaceTexture,u,"microSurfaceSampler"))),this._bumpTexture&&h.getCaps().standardDerivatives&&Pr.a.BumpTextureEnabled&&!this._disableBumpMap&&(u.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level,this._parallaxScaleBias),Er.a.BindTextureMatrix(this._bumpTexture,u,"bump"),r._mirroredCameraPosition?u.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):u.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1))}this.pointsCloud&&u.updateFloat("pointSize",this.pointSize),s.METALLICWORKFLOW?(o.t.Color3[0].r=void 0===this._metallic||null===this._metallic?1:this._metallic,o.t.Color3[0].g=void 0===this._roughness||null===this._roughness?1:this._roughness,u.updateColor4("vReflectivityColor",o.t.Color3[0],0)):u.updateColor4("vReflectivityColor",this._reflectivityColor,this._microSurface),u.updateColor3("vEmissiveColor",Pr.a.EmissiveTextureEnabled?this._emissiveColor:o.e.BlackReadOnly),u.updateColor3("vReflectionColor",this._reflectionColor),u.updateColor4("vAlbedoColor",this._albedoColor,this.alpha),u.updateFloat("visibility",i.visibility),this._lightingInfos.x=this._directIntensity,this._lightingInfos.y=this._emissiveIntensity,this._lightingInfos.z=this._environmentIntensity,this._lightingInfos.w=this._specularIntensity,u.updateVector4("vLightingIntensity",this._lightingInfos)}r.texturesEnabled&&(this._albedoTexture&&Pr.a.DiffuseTextureEnabled&&u.setTexture("albedoSampler",this._albedoTexture),this._ambientTexture&&Pr.a.AmbientTextureEnabled&&u.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&Pr.a.OpacityTextureEnabled&&u.setTexture("opacitySampler",this._opacityTexture),l&&Pr.a.ReflectionTextureEnabled&&(s.LODBASEDMICROSFURACE?u.setTexture("reflectionSampler",l):(u.setTexture("reflectionSampler",l._lodTextureMid||l),u.setTexture("reflectionSamplerLow",l._lodTextureLow||l),u.setTexture("reflectionSamplerHigh",l._lodTextureHigh||l)),s.USEIRRADIANCEMAP&&u.setTexture("irradianceSampler",l.irradianceTexture)),s.ENVIRONMENTBRDF&&u.setTexture("environmentBrdfSampler",this._environmentBRDFTexture),this._emissiveTexture&&Pr.a.EmissiveTextureEnabled&&u.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&Pr.a.LightmapTextureEnabled&&u.setTexture("lightmapSampler",this._lightmapTexture),Pr.a.SpecularTextureEnabled&&(this._metallicTexture?u.setTexture("reflectivitySampler",this._metallicTexture):this._reflectivityTexture&&u.setTexture("reflectivitySampler",this._reflectivityTexture),this._microSurfaceTexture&&u.setTexture("microSurfaceSampler",this._microSurfaceTexture)),this._bumpTexture&&h.getCaps().standardDerivatives&&Pr.a.BumpTextureEnabled&&!this._disableBumpMap&&u.setTexture("bumpSampler",this._bumpTexture)),this.subSurface.bindForSubMesh(u,r,h,this.isFrozen,s.LODBASEDMICROSFURACE),this.clearCoat.bindForSubMesh(u,r,h,this._disableBumpMap,this.isFrozen,this._invertNormalMapX,this._invertNormalMapY),this.anisotropy.bindForSubMesh(u,r,this.isFrozen),this.sheen.bindForSubMesh(u,r,this.isFrozen),Er.a.BindClipPlane(this._activeEffect,r),r.ambientColor.multiplyToRef(this._ambientColor,this._globalAmbientColor);var _=r._forcedViewPosition?r._forcedViewPosition:r._mirroredCameraPosition?r._mirroredCameraPosition:r.activeCamera.globalPosition,m=r.useRightHandedSystem===(null!=r._mirroredCameraPosition);a.setFloat4("vEyePosition",_.x,_.y,_.z,m?-1:1),a.setColor3("vAmbientColor",this._globalAmbientColor),a.setFloat2("vDebugMode",this.debugLimit,this.debugFactor)}!c&&this.isFrozen||(r.lightsEnabled&&!this._disableLighting&&Er.a.BindLights(r,i,this._activeEffect,s,this._maxSimultaneousLights,this._lightFalloff!==t.LIGHTFALLOFF_STANDARD),(r.fogEnabled&&i.applyFog&&r.fogMode!==H.a.FOGMODE_NONE||l)&&this.bindView(a),Er.a.BindFogParameters(r,i,this._activeEffect,!0),s.NUM_MORPH_INFLUENCERS&&Er.a.BindMorphTargetParameters(i,this._activeEffect),this._imageProcessingConfiguration.bind(this._activeEffect),Er.a.BindLogDepth(s,this._activeEffect,r)),u.update(),this._afterBind(i,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.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 t=e.prototype.getActiveTextures.call(this);return this._albedoTexture&&t.push(this._albedoTexture),this._ambientTexture&&t.push(this._ambientTexture),this._opacityTexture&&t.push(this._opacityTexture),this._reflectionTexture&&t.push(this._reflectionTexture),this._emissiveTexture&&t.push(this._emissiveTexture),this._reflectivityTexture&&t.push(this._reflectivityTexture),this._metallicTexture&&t.push(this._metallicTexture),this._microSurfaceTexture&&t.push(this._microSurfaceTexture),this._bumpTexture&&t.push(this._bumpTexture),this._lightmapTexture&&t.push(this._lightmapTexture),this.subSurface.getActiveTextures(t),this.clearCoat.getActiveTextures(t),this.sheen.getActiveTextures(t),this.anisotropy.getActiveTextures(t),t},t.prototype.hasTexture=function(t){return!!e.prototype.hasTexture.call(this,t)||(this._albedoTexture===t||(this._ambientTexture===t||(this._opacityTexture===t||(this._reflectionTexture===t||(this._reflectivityTexture===t||(this._metallicTexture===t||(this._microSurfaceTexture===t||(this._bumpTexture===t||(this._lightmapTexture===t||(this.subSurface.hasTexture(t)||this.clearCoat.hasTexture(t)||this.sheen.hasTexture(t)||this.anisotropy.hasTexture(t)))))))))))},t.prototype.dispose=function(t,i){i&&(this._albedoTexture&&this._albedoTexture.dispose(),this._ambientTexture&&this._ambientTexture.dispose(),this._opacityTexture&&this._opacityTexture.dispose(),this._reflectionTexture&&this._reflectionTexture.dispose(),this._environmentBRDFTexture&&this.getScene().environmentBRDFTexture!==this._environmentBRDFTexture&&this._environmentBRDFTexture.dispose(),this._emissiveTexture&&this._emissiveTexture.dispose(),this._metallicTexture&&this._metallicTexture.dispose(),this._reflectivityTexture&&this._reflectivityTexture.dispose(),this._bumpTexture&&this._bumpTexture.dispose(),this._lightmapTexture&&this._lightmapTexture.dispose()),this.subSurface.dispose(i),this.clearCoat.dispose(i),this.sheen.dispose(i),this.anisotropy.dispose(i),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e.prototype.dispose.call(this,t,i)},t.PBRMATERIAL_OPAQUE=0,t.PBRMATERIAL_ALPHATEST=1,t.PBRMATERIAL_ALPHABLEND=2,t.PBRMATERIAL_ALPHATESTANDBLEND=3,t.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=0,t.LIGHTFALLOFF_PHYSICAL=0,t.LIGHTFALLOFF_GLTF=1,t.LIGHTFALLOFF_STANDARD=2,l.c([Object(L.i)()],t.prototype,"_imageProcessingConfiguration",void 0),l.c([Object(L.b)("_markAllSubMeshesAsMiscDirty")],t.prototype,"debugMode",void 0),l.c([Object(L.c)()],t.prototype,"useLogarithmicDepth",null),l.c([Object(L.c)()],t.prototype,"transparencyMode",null),t}(Ar.a),ro=function(e){function t(i,n){var r=e.call(this,i,n)||this;return r.directIntensity=1,r.emissiveIntensity=1,r.environmentIntensity=1,r.specularIntensity=1,r.disableBumpMap=!1,r.ambientTextureStrength=1,r.ambientTextureImpactOnAnalyticalLights=t.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,r.ambientColor=new o.e(0,0,0),r.albedoColor=new o.e(1,1,1),r.reflectivityColor=new o.e(1,1,1),r.reflectionColor=new o.e(1,1,1),r.emissiveColor=new o.e(0,0,0),r.microSurface=1,r.useLightmapAsShadowmap=!1,r.useAlphaFromAlbedoTexture=!1,r.forceAlphaTest=!1,r.alphaCutOff=.4,r.useSpecularOverAlpha=!0,r.useMicroSurfaceFromReflectivityMapAlpha=!1,r.useRoughnessFromMetallicTextureAlpha=!0,r.useRoughnessFromMetallicTextureGreen=!1,r.useMetallnessFromMetallicTextureBlue=!1,r.useAmbientOcclusionFromMetallicTextureRed=!1,r.useAmbientInGrayScale=!1,r.useAutoMicroSurfaceFromReflectivityMap=!1,r.useRadianceOverAlpha=!0,r.useObjectSpaceNormalMap=!1,r.useParallax=!1,r.useParallaxOcclusion=!1,r.parallaxScaleBias=.05,r.disableLighting=!1,r.forceIrradianceInFragment=!1,r.maxSimultaneousLights=4,r.invertNormalMapX=!1,r.invertNormalMapY=!1,r.twoSidedLighting=!1,r.useAlphaFresnel=!1,r.useLinearAlphaFresnel=!1,r.environmentBRDFTexture=null,r.forceNormalForward=!1,r.enableSpecularAntiAliasing=!1,r.useHorizonOcclusion=!0,r.useRadianceOcclusion=!0,r.unlit=!1,r._environmentBRDFTexture=Fr.GetEnvironmentBRDFTexture(n),r}return l.d(t,e),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:!0,configurable:!0}),Object.defineProperty(t.prototype,"indexOfRefraction",{get:function(){return 1/this.subSurface.indexOfRefraction},set:function(e){this.subSurface.indexOfRefraction=1/e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"invertRefractionY",{get:function(){return this.subSurface.invertRefractionY},set:function(e){this.subSurface.invertRefractionY=e},enumerable:!0,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:!0,configurable:!0}),Object.defineProperty(t.prototype,"usePhysicalLightFalloff",{get:function(){return this._lightFalloff===no.LIGHTFALLOFF_PHYSICAL},set:function(e){e!==this.usePhysicalLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),this._lightFalloff=e?no.LIGHTFALLOFF_PHYSICAL:no.LIGHTFALLOFF_STANDARD)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"useGLTFLightFalloff",{get:function(){return this._lightFalloff===no.LIGHTFALLOFF_GLTF},set:function(e){e!==this.useGLTFLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),this._lightFalloff=e?no.LIGHTFALLOFF_GLTF:no.LIGHTFALLOFF_STANDARD)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"imageProcessingConfiguration",{get:function(){return this._imageProcessingConfiguration},set:function(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"cameraColorCurvesEnabled",{get:function(){return this.imageProcessingConfiguration.colorCurvesEnabled},set:function(e){this.imageProcessingConfiguration.colorCurvesEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"cameraColorGradingEnabled",{get:function(){return this.imageProcessingConfiguration.colorGradingEnabled},set:function(e){this.imageProcessingConfiguration.colorGradingEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"cameraToneMappingEnabled",{get:function(){return this._imageProcessingConfiguration.toneMappingEnabled},set:function(e){this._imageProcessingConfiguration.toneMappingEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"cameraExposure",{get:function(){return this._imageProcessingConfiguration.exposure},set:function(e){this._imageProcessingConfiguration.exposure=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"cameraContrast",{get:function(){return this._imageProcessingConfiguration.contrast},set:function(e){this._imageProcessingConfiguration.contrast=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"cameraColorGradingTexture",{get:function(){return this._imageProcessingConfiguration.colorGradingTexture},set:function(e){this._imageProcessingConfiguration.colorGradingTexture=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"cameraColorCurves",{get:function(){return this._imageProcessingConfiguration.colorCurves},set:function(e){this._imageProcessingConfiguration.colorCurves=e},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"PBRMaterial"},t.prototype.clone=function(e){var i=this,n=L.a.Clone(function(){return new t(e,i.getScene())},this);return n.id=e,n.name=e,this.clearCoat.copyTo(n.clearCoat),this.anisotropy.copyTo(n.anisotropy),this.brdf.copyTo(n.brdf),this.sheen.copyTo(n.sheen),n},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,i,n){var r=L.a.Parse(function(){return new t(e.name,i)},e,i,n);return e.clearCoat&&r.clearCoat.parse(e.clearCoat),e.anisotropy&&r.anisotropy.parse(e.anisotropy),e.brdf&&r.brdf.parse(e.brdf),e.sheen&&r.sheen.parse(e.sheen),e.subSurface&&r.subSurface.parse(e.subSurface),r},t.PBRMATERIAL_OPAQUE=no.PBRMATERIAL_OPAQUE,t.PBRMATERIAL_ALPHATEST=no.PBRMATERIAL_ALPHATEST,t.PBRMATERIAL_ALPHABLEND=no.PBRMATERIAL_ALPHABLEND,t.PBRMATERIAL_ALPHATESTANDBLEND=no.PBRMATERIAL_ALPHATESTANDBLEND,t.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=no.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,l.c([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"directIntensity",void 0),l.c([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"emissiveIntensity",void 0),l.c([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"environmentIntensity",void 0),l.c([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"specularIntensity",void 0),l.c([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"disableBumpMap",void 0),l.c([Object(L.m)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"albedoTexture",void 0),l.c([Object(L.m)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"ambientTexture",void 0),l.c([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"ambientTextureStrength",void 0),l.c([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"ambientTextureImpactOnAnalyticalLights",void 0),l.c([Object(L.m)(),Object(L.b)("_markAllSubMeshesAsTexturesAndMiscDirty")],t.prototype,"opacityTexture",void 0),l.c([Object(L.m)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"reflectionTexture",void 0),l.c([Object(L.m)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"emissiveTexture",void 0),l.c([Object(L.m)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"reflectivityTexture",void 0),l.c([Object(L.m)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"metallicTexture",void 0),l.c([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"metallic",void 0),l.c([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"roughness",void 0),l.c([Object(L.m)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"microSurfaceTexture",void 0),l.c([Object(L.m)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"bumpTexture",void 0),l.c([Object(L.m)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty",null)],t.prototype,"lightmapTexture",void 0),l.c([Object(L.e)("ambient"),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"ambientColor",void 0),l.c([Object(L.e)("albedo"),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"albedoColor",void 0),l.c([Object(L.e)("reflectivity"),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"reflectivityColor",void 0),l.c([Object(L.e)("reflection"),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"reflectionColor",void 0),l.c([Object(L.e)("emissive"),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"emissiveColor",void 0),l.c([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"microSurface",void 0),l.c([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useLightmapAsShadowmap",void 0),l.c([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesAndMiscDirty")],t.prototype,"useAlphaFromAlbedoTexture",void 0),l.c([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesAndMiscDirty")],t.prototype,"forceAlphaTest",void 0),l.c([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesAndMiscDirty")],t.prototype,"alphaCutOff",void 0),l.c([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useSpecularOverAlpha",void 0),l.c([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useMicroSurfaceFromReflectivityMapAlpha",void 0),l.c([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useRoughnessFromMetallicTextureAlpha",void 0),l.c([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useRoughnessFromMetallicTextureGreen",void 0),l.c([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useMetallnessFromMetallicTextureBlue",void 0),l.c([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useAmbientOcclusionFromMetallicTextureRed",void 0),l.c([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useAmbientInGrayScale",void 0),l.c([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useAutoMicroSurfaceFromReflectivityMap",void 0),l.c([Object(L.c)()],t.prototype,"usePhysicalLightFalloff",null),l.c([Object(L.c)()],t.prototype,"useGLTFLightFalloff",null),l.c([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useRadianceOverAlpha",void 0),l.c([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useObjectSpaceNormalMap",void 0),l.c([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useParallax",void 0),l.c([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useParallaxOcclusion",void 0),l.c([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"parallaxScaleBias",void 0),l.c([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsLightsDirty")],t.prototype,"disableLighting",void 0),l.c([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"forceIrradianceInFragment",void 0),l.c([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsLightsDirty")],t.prototype,"maxSimultaneousLights",void 0),l.c([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"invertNormalMapX",void 0),l.c([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"invertNormalMapY",void 0),l.c([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"twoSidedLighting",void 0),l.c([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useAlphaFresnel",void 0),l.c([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useLinearAlphaFresnel",void 0),l.c([Object(L.m)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"environmentBRDFTexture",void 0),l.c([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"forceNormalForward",void 0),l.c([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"enableSpecularAntiAliasing",void 0),l.c([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useHorizonOcclusion",void 0),l.c([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsTexturesDirty")],t.prototype,"useRadianceOcclusion",void 0),l.c([Object(L.c)(),Object(L.b)("_markAllSubMeshesAsMiscDirty")],t.prototype,"unlit",void 0),t}(no);s.a.RegisteredTypes["BABYLON.PBRMaterial"]=ro;var oo=i(74);function so(e){return e.charCodeAt(0)+(e.charCodeAt(1)<<8)+(e.charCodeAt(2)<<16)+(e.charCodeAt(3)<<24)}var ao=so("DXT1"),co=so("DXT3"),lo=so("DXT5"),uo=so("DX10"),ho=function(){function e(){}return e.GetDDSInfo=function(e){var t=new Int32Array(e,0,31),i=new Int32Array(e,0,35),n=1;131072&t[2]&&(n=Math.max(1,t[7]));var r=t[21],o=r===uo?i[32]:0,s=_.a.TEXTURETYPE_UNSIGNED_INT;switch(r){case 113:s=_.a.TEXTURETYPE_HALF_FLOAT;break;case 116:s=_.a.TEXTURETYPE_FLOAT;break;case uo:if(10===o){s=_.a.TEXTURETYPE_HALF_FLOAT;break}}return{width:t[4],height:t[3],mipmapCount:n,isFourCC:4==(4&t[20]),isRGB:64==(64&t[20]),isLuminance:131072==(131072&t[20]),isCube:512==(512&t[28]),isCompressed:r===ao||r===co||r===lo,dxgiFormat:o,textureType:s}},e._ToHalfFloat=function(t){e._FloatView||(e._FloatView=new Float32Array(1),e._Int32View=new Int32Array(e._FloatView.buffer)),e._FloatView[0]=t;var i=e._Int32View[0],n=i>>16&32768,r=i>>12&2047,o=i>>23&255;return o<103?n:o>142?(n|=31744,n|=(255==o?0:1)&&8388607&i):o<113?n|=((r|=2048)>>114-o)+(r>>113-o&1):(n|=o-112<<10|r>>1,n+=1&r)},e._FromHalfFloat=function(e){var t=(32768&e)>>15,i=(31744&e)>>10,n=1023&e;return 0===i?(t?-1:1)*Math.pow(2,-14)*(n/Math.pow(2,10)):31==i?n?NaN:1/0*(t?-1:1):(t?-1:1)*Math.pow(2,i-15)*(1+n/Math.pow(2,10))},e._GetHalfFloatAsFloatRGBAArrayBuffer=function(t,i,n,r,o,s){for(var a=new Float32Array(r),c=new Uint16Array(o,n),l=0,u=0;u>8)},e._GetRGBArrayBuffer=function(e,t,i,n,r,o,s,a){for(var c=new Uint8Array(n),l=new Uint8Array(r,i),u=0,h=0;h>8&255,P>>16&255,P>>24&255)))}var C=e._ExtractLongWordOrder(b[23]),M=e._ExtractLongWordOrder(b[24]),O=e._ExtractLongWordOrder(b[25]),I=e._ExtractLongWordOrder(b[26]);R&&(E=t._getRGBABufferInternalSizedFormat(r.textureType)),g=1,131072&b[2]&&!1!==o&&(g=Math.max(1,b[7]));for(var D=c||0;D0?r.sphericalPolynomial=oo.a.ConvertCubeMapToSphericalPolynomial({size:b[4],right:l[0],left:l[1],up:l[2],down:l[3],front:l[4],back:l[5],format:_.a.TEXTUREFORMAT_RGBA,type:_.a.TEXTURETYPE_FLOAT,gammaSpace:!1}):r.sphericalPolynomial=void 0}else p.a.Error("Compressed textures are not supported on this platform.");else p.a.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");else p.a.Error("Invalid magic number in DDS header")},e.StoreLODInAlphaChannel=!1,e}();me.b.prototype.createPrefilteredCubeTexture=function(e,t,i,n,r,o,s,a,c){var l=this;void 0===r&&(r=null),void 0===o&&(o=null),void 0===a&&(a=null),void 0===c&&(c=!0);return this.createCubeTexture(e,t,null,!1,function(e){if(e){var o=e.texture;if(c?e.info.sphericalPolynomial&&(o._sphericalPolynomial=e.info.sphericalPolynomial):o._sphericalPolynomial=new gn.b,o._dataSource=ze.a.DATASOURCE_CUBEPREFILTERED,l.getCaps().textureLOD)r&&r(o);else{var s=l._gl,a=e.width;if(a){for(var u=[],h=0;h<3;h++){var d=1-h/2,f=n,_=D.a.Log2(a)*i+n,m=f+(_-f)*d,g=Math.round(Math.min(Math.max(m,0),_)),v=new ze.a(l,ze.a.DATASOURCE_TEMP);if(v.type=o.type,v.format=o.format,v.width=Math.pow(2,Math.max(D.a.Log2(a)-g,0)),v.height=v.width,v.isCube=!0,l._bindTextureDirectly(s.TEXTURE_CUBE_MAP,v,!0),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MAG_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MIN_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),e.isDDS){var y=e.info,b=e.data;l._unpackFlipY(y.isCompressed),ho.UploadDDSLevels(l,v,b,y,!0,6,g)}else p.a.Warn("DDS is the only prefiltered cube map supported so far.");l._bindTextureDirectly(s.TEXTURE_CUBE_MAP,null);var T=new vn.a(t);T.isCube=!0,T._texture=v,v.isReady=!0,u.push(T)}o._lodTextureHigh=u[2],o._lodTextureMid=u[1],o._lodTextureLow=u[0],r&&r(o)}}}else r&&r(null)},o,s,a,c,i,n)};var fo=function(){function e(){this.supportCascades=!0}return e.prototype.canLoad=function(e,t,i,n,r){return 0===e.indexOf(".dds")},e.prototype.transformUrl=function(e,t){return e},e.prototype.getFallbackTextureUrl=function(e,t){return null},e.prototype.loadCubeData=function(e,t,i,n,r){var o,s=t.getEngine(),a=!1;if(Array.isArray(e))for(var c=0;c1)&&t.generateMipMaps,s._unpackFlipY(o.isCompressed),ho.UploadDDSLevels(s,t,l,o,a,6,-1,c),o.isFourCC||1!==o.mipmapCount||s.generateMipMapsForCubemap(t)}else{var u=e;o=ho.GetDDSInfo(u),t.width=o.width,t.height=o.height,i&&(o.sphericalPolynomial=new gn.b),a=(o.isRGB||o.isLuminance||o.mipmapCount>1)&&t.generateMipMaps,s._unpackFlipY(o.isCompressed),ho.UploadDDSLevels(s,t,u,o,a,6),o.isFourCC||1!==o.mipmapCount||s.generateMipMapsForCubemap(t)}s._setCubeMapTextureParams(a),t.isReady=!0,n&&n({isDDS:!0,width:t.width,info:o,data:e,texture:t})},e.prototype.loadData=function(e,t,i){var n=ho.GetDDSInfo(e),r=(n.isRGB||n.isLuminance||n.mipmapCount>1)&&t.generateMipMaps&&n.width>>n.mipmapCount-1==1;i(n.width,n.height,r,n.isFourCC,function(){ho.UploadDDSLevels(t.getEngine(),t,e,n,r,1)})},e}();me.b._TextureLoaders.push(new fo);var po=function(){function e(){this.supportCascades=!1}return e.prototype.canLoad=function(e,t,i,n,r){return 0===e.indexOf(".env")},e.prototype.transformUrl=function(e,t){return e},e.prototype.getFallbackTextureUrl=function(e,t){return null},e.prototype.loadCubeData=function(e,t,i,n,r){if(!Array.isArray(e)){e=e;var o=Tn.GetEnvInfo(e);o?(t.width=o.width,t.height=o.width,Tn.UploadEnvSpherical(t,o),Tn.UploadEnvLevelsAsync(t,e,o).then(function(){t.isReady=!0,n&&n()})):r&&r("Can not parse the environment file",null)}},e.prototype.loadData=function(e,t,i){throw".env not supported in 2d."},e}();me.b._TextureLoaders.push(new po);var _o=function(){function e(t,i,n,r){this.arrayBuffer=t,this.isInvalid=!1;var o=new Uint8Array(this.arrayBuffer,0,12);if(171!==o[0]||75!==o[1]||84!==o[2]||88!==o[3]||32!==o[4]||49!==o[5]||49!==o[6]||187!==o[7]||13!==o[8]||10!==o[9]||26!==o[10]||10!==o[11])return this.isInvalid=!0,void p.a.Error("texture missing KTX identifier");var s=Uint32Array.BYTES_PER_ELEMENT,a=new DataView(this.arrayBuffer,12,13*s),c=67305985===a.getUint32(0,!0);this.glType=a.getUint32(1*s,c),this.glTypeSize=a.getUint32(2*s,c),this.glFormat=a.getUint32(3*s,c),this.glInternalFormat=a.getUint32(4*s,c),this.glBaseInternalFormat=a.getUint32(5*s,c),this.pixelWidth=a.getUint32(6*s,c),this.pixelHeight=a.getUint32(7*s,c),this.pixelDepth=a.getUint32(8*s,c),this.numberOfArrayElements=a.getUint32(9*s,c),this.numberOfFaces=a.getUint32(10*s,c),this.numberOfMipmapLevels=a.getUint32(11*s,c),this.bytesOfKeyValueData=a.getUint32(12*s,c),0===this.glType?(this.numberOfMipmapLevels=Math.max(1,this.numberOfMipmapLevels),0!==this.pixelHeight&&0===this.pixelDepth?0===this.numberOfArrayElements?this.numberOfFaces===i?this.loadType=e.COMPRESSED_2D:p.a.Error("number of faces expected"+i+", but found "+this.numberOfFaces):p.a.Error("texture arrays not currently supported"):p.a.Error("only 2D textures currently supported")):p.a.Error("only compressed formats currently supported")}return e.prototype.uploadLevels=function(t,i){switch(this.loadType){case e.COMPRESSED_2D:this._upload2DCompressedLevels(t,i);break;case e.TEX_2D:case e.COMPRESSED_3D:case e.TEX_3D:}},e.prototype._upload2DCompressedLevels=function(t,i){for(var n=e.HEADER_LEN+this.bytesOfKeyValueData,r=this.pixelWidth,o=this.pixelHeight,s=i?this.numberOfMipmapLevels:1,a=0;a-1?e.substring(0,i):e)+t},e.prototype.getFallbackTextureUrl=function(e,t){var i=new RegExp(t+"$");return e.replace(i,"")},e.prototype.loadCubeData=function(e,t,i,n,r){if(!Array.isArray(e)){t._invertVScale=!t.invertY;var o=t.getEngine(),s=new _o(e,6),a=s.numberOfMipmapLevels>1&&t.generateMipMaps;o._unpackFlipY(!0),s.uploadLevels(t,t.generateMipMaps),t.width=s.pixelWidth,t.height=s.pixelHeight,o._setCubeMapTextureParams(a),t.isReady=!0}},e.prototype.loadData=function(e,t,i){t._invertVScale=!t.invertY;var n=new _o(e,1);i(n.pixelWidth,n.pixelHeight,!1,!0,function(){n.uploadLevels(t,t.generateMipMaps)},n.isInvalid)},e}();me.b._TextureLoaders.unshift(new mo);H.a.prototype.createDefaultLight=function(e){if(void 0===e&&(e=!1),e&&this.lights)for(var t=0;t=c.video.HAVE_CURRENT_DATA;return!a.poster||a.autoPlay&&l?l&&c._createInternalTexture():(c._texture=c._engine.createTexture(a.poster,!1,!0,n),c._displayingPosterTexture=!0),c}return l.d(t,e),Object.defineProperty(t.prototype,"onUserActionRequestedObservable",{get:function(){return this._onUserActionRequestedObservable||(this._onUserActionRequestedObservable=new r.c),this._onUserActionRequestedObservable},enumerable:!0,configurable:!0}),t.prototype._getName=function(e){return e instanceof HTMLVideoElement?e.currentSrc:"object"==typeof e?e.toString():e},t.prototype._getVideo=function(e){if(e instanceof HTMLVideoElement)return ye.h.SetCorsBehavior(e.currentSrc,e),e;var t=document.createElement("video");return"string"==typeof e?(ye.h.SetCorsBehavior(e,t),t.src=e):(ye.h.SetCorsBehavior(e[0],t),e.forEach(function(e){var i=document.createElement("source");i.src=e,t.appendChild(i)})),t},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},t.prototype.dispose=function(){e.prototype.dispose.call(this),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,i){var n=document.createElement("video");return n.setAttribute("autoplay",""),n.setAttribute("muted","true"),n.setAttribute("playsinline",""),n.muted=!0,void 0!==n.mozSrcObject?n.mozSrcObject=i:"object"==typeof n.srcObject?n.srcObject=i:(window.URL=window.URL||window.webkitURL||window.mozURL||window.msURL,n.src=window.URL&&window.URL.createObjectURL(i)),new Promise(function(i){var r=function(){i(new t("video",n,e,!0,!0)),n.removeEventListener("playing",r)};n.addEventListener("playing",r),n.play()})},t.CreateFromWebCamAsync=function(e,t,i){var n,r=this;return void 0===i&&(i=!1),t&&t.deviceId&&(n={exact:t.deviceId}),navigator.mediaDevices?navigator.mediaDevices.getUserMedia({video:t,audio:i}).then(function(t){return r.CreateFromStreamAsync(e,t)}):(navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia,navigator.getUserMedia&&navigator.getUserMedia({video:{deviceId:n,width:{min:t&&t.minWidth||256,max:t&&t.maxWidth||640},height:{min:t&&t.minHeight||256,max:t&&t.maxHeight||480}},audio:i},function(t){return r.CreateFromStreamAsync(e,t)},function(e){p.a.Error(e.name)}),Promise.reject("No support for userMedia on this device"))},t.CreateFromWebCam=function(e,t,i,n){void 0===n&&(n=!1),this.CreateFromWebCamAsync(e,i,n).then(function(e){t&&t(e)}).catch(function(e){p.a.Error(e.name)})},t}(Ge.a),vo=function(e){function t(i,n,r,s){var a=e.call(this,i,s)||this;a._useDirectMapping=!1,a._videoMode=t.MODE_MONOSCOPIC,a._onBeforeCameraRenderObserver=null,s=a.getScene(),i=i||"videoDome",r.resolution=0|Math.abs(r.resolution)||32,r.clickToPlay=Boolean(r.clickToPlay),r.autoPlay=void 0===r.autoPlay||Boolean(r.autoPlay),r.loop=void 0===r.loop||Boolean(r.loop),r.size=Math.abs(r.size)||(s.activeCamera?.48*s.activeCamera.maxZ:1e3),void 0===r.useDirectMapping?a._useDirectMapping=!0:a._useDirectMapping=r.useDirectMapping,void 0===r.faceForward&&(r.faceForward=!0),a._setReady(!1);var c={loop:r.loop,autoPlay:r.autoPlay,autoUpdateTexture:!0,poster:r.poster},l=a._material=new Dr(i+"_material",s),u=a._videoTexture=new go(i+"_texture",n,s,!1,a._useDirectMapping,Ge.a.TRILINEAR_SAMPLINGMODE,c);if(a._mesh=fe.a.CreateSphere(i+"_mesh",r.resolution,r.size,s,!1,fe.a.BACKSIDE),u.onLoadObservable.addOnce(function(){a._setReady(!0)}),l.useEquirectangularFOV=!0,l.fovMultiplier=1,l.opacityFresnel=!1,a._useDirectMapping?(u.wrapU=Ge.a.CLAMP_ADDRESSMODE,u.wrapV=Ge.a.CLAMP_ADDRESSMODE,l.diffuseTexture=u):(u.coordinatesMode=Ge.a.FIXED_EQUIRECTANGULAR_MIRRORED_MODE,u.wrapV=Ge.a.CLAMP_ADDRESSMODE,l.reflectionTexture=u),a._mesh.material=l,a._mesh.parent=a,r.clickToPlay&&(s.onPointerUp=function(){a._videoTexture.video.play()}),r.faceForward&&s.activeCamera){var h=s.activeCamera,d=o.x.Forward(),f=o.x.TransformNormal(d,h.getViewMatrix());f.normalize(),a.rotation.y=Math.acos(o.x.Dot(d,f))}return a}return l.d(t,e),Object.defineProperty(t.prototype,"videoTexture",{get:function(){return this._videoTexture},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fovMultiplier",{get:function(){return this._material.fovMultiplier},set:function(e){this._material.fovMultiplier=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"videoMode",{get:function(){return this._videoMode},set:function(e){this._videoMode!==e&&this._changeVideoMode(e)},enumerable:!0,configurable:!0}),t.prototype._changeVideoMode=function(e){var i=this;switch(this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._videoMode=e,this._videoTexture.uScale=1,this._videoTexture.vScale=1,this._videoTexture.uOffset=0,this._videoTexture.vOffset=0,e){case t.MODE_SIDEBYSIDE:this._videoTexture.uScale=.5,this._onBeforeCameraRenderObserver=this._scene.onBeforeCameraRenderObservable.add(function(e){i._videoTexture.uOffset=e.isRightCamera?.5:0});break;case t.MODE_TOPBOTTOM:this._videoTexture.vScale=.5,this._onBeforeCameraRenderObserver=this._scene.onBeforeCameraRenderObservable.add(function(e){i._videoTexture.vOffset=e.isRightCamera?.5:0})}},t.prototype.dispose=function(t,i){void 0===i&&(i=!1),this._videoTexture.dispose(),this._mesh.dispose(),this._material.dispose(),this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),e.prototype.dispose.call(this,t,i)},t.MODE_MONOSCOPIC=0,t.MODE_TOPBOTTOM=1,t.MODE_SIDEBYSIDE=2,t}(ir.a),yo=function(){function e(e){this.engine=e,this._captureGPUFrameTime=!1,this._gpuFrameTime=new ye.f,this._captureShaderCompilationTime=!1,this._shaderCompilationTime=new ye.f,this._onBeginFrameObserver=null,this._onEndFrameObserver=null,this._onBeforeShaderCompilationObserver=null,this._onAfterShaderCompilationObserver=null}return Object.defineProperty(e.prototype,"gpuFrameTimeCounter",{get:function(){return this._gpuFrameTime},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"captureGPUFrameTime",{get:function(){return this._captureGPUFrameTime},set:function(e){var t=this;e!==this._captureGPUFrameTime&&(this._captureGPUFrameTime=e,e?(this._onBeginFrameObserver=this.engine.onBeginFrameObservable.add(function(){t._gpuFrameTimeToken||(t._gpuFrameTimeToken=t.engine.startTimeQuery())}),this._onEndFrameObserver=this.engine.onEndFrameObservable.add(function(){if(t._gpuFrameTimeToken){var e=t.engine.endTimeQuery(t._gpuFrameTimeToken);e>-1&&(t._gpuFrameTimeToken=null,t._gpuFrameTime.fetchNewFrame(),t._gpuFrameTime.addCount(e,!0))}})):(this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver),this._onBeginFrameObserver=null,this.engine.onEndFrameObservable.remove(this._onEndFrameObserver),this._onEndFrameObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"shaderCompilationTimeCounter",{get:function(){return this._shaderCompilationTime},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"captureShaderCompilationTime",{get:function(){return this._captureShaderCompilationTime},set:function(e){var t=this;e!==this._captureShaderCompilationTime&&(this._captureShaderCompilationTime=e,e?(this._onBeforeShaderCompilationObserver=this.engine.onBeforeShaderCompilationObservable.add(function(){t._shaderCompilationTime.fetchNewFrame(),t._shaderCompilationTime.beginMonitoring()}),this._onAfterShaderCompilationObserver=this.engine.onAfterShaderCompilationObservable.add(function(){t._shaderCompilationTime.endMonitoring()})):(this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver),this._onBeforeShaderCompilationObserver=null,this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver),this._onAfterShaderCompilationObserver=null))},enumerable:!0,configurable:!0}),e.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},e}(),bo=function(){function e(e){var t=this;this.scene=e,this._captureActiveMeshesEvaluationTime=!1,this._activeMeshesEvaluationTime=new ye.f,this._captureRenderTargetsRenderTime=!1,this._renderTargetsRenderTime=new ye.f,this._captureFrameTime=!1,this._frameTime=new ye.f,this._captureRenderTime=!1,this._renderTime=new ye.f,this._captureInterFrameTime=!1,this._interFrameTime=new ye.f,this._captureParticlesRenderTime=!1,this._particlesRenderTime=new ye.f,this._captureSpritesRenderTime=!1,this._spritesRenderTime=new ye.f,this._capturePhysicsTime=!1,this._physicsTime=new ye.f,this._captureAnimationsTime=!1,this._animationsTime=new ye.f,this._captureCameraRenderTime=!1,this._cameraRenderTime=new ye.f,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=e.onBeforeAnimationsObservable.add(function(){t._captureActiveMeshesEvaluationTime&&t._activeMeshesEvaluationTime.fetchNewFrame(),t._captureRenderTargetsRenderTime&&t._renderTargetsRenderTime.fetchNewFrame(),t._captureFrameTime&&(ye.h.StartPerformanceCounter("Scene rendering"),t._frameTime.beginMonitoring()),t._captureInterFrameTime&&t._interFrameTime.endMonitoring(),t._captureParticlesRenderTime&&t._particlesRenderTime.fetchNewFrame(),t._captureSpritesRenderTime&&t._spritesRenderTime.fetchNewFrame(),t._captureAnimationsTime&&t._animationsTime.beginMonitoring(),t.scene.getEngine()._drawCalls.fetchNewFrame()}),this._onAfterRenderObserver=e.onAfterRenderObservable.add(function(){t._captureFrameTime&&(ye.h.EndPerformanceCounter("Scene rendering"),t._frameTime.endMonitoring()),t._captureRenderTime&&t._renderTime.endMonitoring(!1),t._captureInterFrameTime&&t._interFrameTime.beginMonitoring()})}return Object.defineProperty(e.prototype,"activeMeshesEvaluationTimeCounter",{get:function(){return this._activeMeshesEvaluationTime},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"captureActiveMeshesEvaluationTime",{get:function(){return this._captureActiveMeshesEvaluationTime},set:function(e){var t=this;e!==this._captureActiveMeshesEvaluationTime&&(this._captureActiveMeshesEvaluationTime=e,e?(this._onBeforeActiveMeshesEvaluationObserver=this.scene.onBeforeActiveMeshesEvaluationObservable.add(function(){ye.h.StartPerformanceCounter("Active meshes evaluation"),t._activeMeshesEvaluationTime.beginMonitoring()}),this._onAfterActiveMeshesEvaluationObserver=this.scene.onAfterActiveMeshesEvaluationObservable.add(function(){ye.h.EndPerformanceCounter("Active meshes evaluation"),t._activeMeshesEvaluationTime.endMonitoring()})):(this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver),this._onBeforeActiveMeshesEvaluationObserver=null,this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver),this._onAfterActiveMeshesEvaluationObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"renderTargetsRenderTimeCounter",{get:function(){return this._renderTargetsRenderTime},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"captureRenderTargetsRenderTime",{get:function(){return this._captureRenderTargetsRenderTime},set:function(e){var t=this;e!==this._captureRenderTargetsRenderTime&&(this._captureRenderTargetsRenderTime=e,e?(this._onBeforeRenderTargetsRenderObserver=this.scene.onBeforeRenderTargetsRenderObservable.add(function(){ye.h.StartPerformanceCounter("Render targets rendering"),t._renderTargetsRenderTime.beginMonitoring()}),this._onAfterRenderTargetsRenderObserver=this.scene.onAfterRenderTargetsRenderObservable.add(function(){ye.h.EndPerformanceCounter("Render targets rendering"),t._renderTargetsRenderTime.endMonitoring(!1)})):(this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver),this._onBeforeRenderTargetsRenderObserver=null,this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver),this._onAfterRenderTargetsRenderObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"particlesRenderTimeCounter",{get:function(){return this._particlesRenderTime},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"captureParticlesRenderTime",{get:function(){return this._captureParticlesRenderTime},set:function(e){var t=this;e!==this._captureParticlesRenderTime&&(this._captureParticlesRenderTime=e,e?(this._onBeforeParticlesRenderingObserver=this.scene.onBeforeParticlesRenderingObservable.add(function(){ye.h.StartPerformanceCounter("Particles"),t._particlesRenderTime.beginMonitoring()}),this._onAfterParticlesRenderingObserver=this.scene.onAfterParticlesRenderingObservable.add(function(){ye.h.EndPerformanceCounter("Particles"),t._particlesRenderTime.endMonitoring(!1)})):(this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver),this._onBeforeParticlesRenderingObserver=null,this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver),this._onAfterParticlesRenderingObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"spritesRenderTimeCounter",{get:function(){return this._spritesRenderTime},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"captureSpritesRenderTime",{get:function(){return this._captureSpritesRenderTime},set:function(e){var t=this;e!==this._captureSpritesRenderTime&&(this._captureSpritesRenderTime=e,this.scene.spriteManagers&&(e?(this._onBeforeSpritesRenderingObserver=this.scene.onBeforeSpritesRenderingObservable.add(function(){ye.h.StartPerformanceCounter("Sprites"),t._spritesRenderTime.beginMonitoring()}),this._onAfterSpritesRenderingObserver=this.scene.onAfterSpritesRenderingObservable.add(function(){ye.h.EndPerformanceCounter("Sprites"),t._spritesRenderTime.endMonitoring(!1)})):(this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver),this._onBeforeSpritesRenderingObserver=null,this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver),this._onAfterSpritesRenderingObserver=null)))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"physicsTimeCounter",{get:function(){return this._physicsTime},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"capturePhysicsTime",{get:function(){return this._capturePhysicsTime},set:function(e){var t=this;e!==this._capturePhysicsTime&&this.scene.onBeforePhysicsObservable&&(this._capturePhysicsTime=e,e?(this._onBeforePhysicsObserver=this.scene.onBeforePhysicsObservable.add(function(){ye.h.StartPerformanceCounter("Physics"),t._physicsTime.beginMonitoring()}),this._onAfterPhysicsObserver=this.scene.onAfterPhysicsObservable.add(function(){ye.h.EndPerformanceCounter("Physics"),t._physicsTime.endMonitoring()})):(this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver),this._onBeforePhysicsObserver=null,this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver),this._onAfterPhysicsObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"animationsTimeCounter",{get:function(){return this._animationsTime},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"captureAnimationsTime",{get:function(){return this._captureAnimationsTime},set:function(e){var t=this;e!==this._captureAnimationsTime&&(this._captureAnimationsTime=e,e?this._onAfterAnimationsObserver=this.scene.onAfterAnimationsObservable.add(function(){t._animationsTime.endMonitoring()}):(this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver),this._onAfterAnimationsObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"frameTimeCounter",{get:function(){return this._frameTime},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"captureFrameTime",{get:function(){return this._captureFrameTime},set:function(e){this._captureFrameTime=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"interFrameTimeCounter",{get:function(){return this._interFrameTime},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"captureInterFrameTime",{get:function(){return this._captureInterFrameTime},set:function(e){this._captureInterFrameTime=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"renderTimeCounter",{get:function(){return this._renderTime},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"captureRenderTime",{get:function(){return this._captureRenderTime},set:function(e){var t=this;e!==this._captureRenderTime&&(this._captureRenderTime=e,e?(this._onBeforeDrawPhaseObserver=this.scene.onBeforeDrawPhaseObservable.add(function(){t._renderTime.beginMonitoring(),ye.h.StartPerformanceCounter("Main render")}),this._onAfterDrawPhaseObserver=this.scene.onAfterDrawPhaseObservable.add(function(){t._renderTime.endMonitoring(!1),ye.h.EndPerformanceCounter("Main render")})):(this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver),this._onBeforeDrawPhaseObserver=null,this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver),this._onAfterDrawPhaseObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"cameraRenderTimeCounter",{get:function(){return this._cameraRenderTime},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"captureCameraRenderTime",{get:function(){return this._captureCameraRenderTime},set:function(e){var t=this;e!==this._captureCameraRenderTime&&(this._captureCameraRenderTime=e,e?(this._onBeforeCameraRenderObserver=this.scene.onBeforeCameraRenderObservable.add(function(e){t._cameraRenderTime.beginMonitoring(),ye.h.StartPerformanceCounter("Rendering camera "+e.name)}),this._onAfterCameraRenderObserver=this.scene.onAfterCameraRenderObservable.add(function(e){t._cameraRenderTime.endMonitoring(!1),ye.h.EndPerformanceCounter("Rendering camera "+e.name)})):(this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=null,this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=null))},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"drawCallsCounter",{get:function(){return this.scene.getEngine()._drawCalls},enumerable:!0,configurable:!0}),e.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},e}(),To=i(23),Eo="#ifdef DIFFUSE\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef OPACITY\nvarying vec2 vUVOpacity;\nuniform sampler2D opacitySampler;\nuniform float opacityIntensity;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef VERTEXALPHA\nvarying vec4 vColor;\n#endif\nuniform vec4 glowColor;\nvoid main(void)\n{\nvec4 finalColor=glowColor;\n\n#ifdef DIFFUSE\nvec4 albedoTexture=texture2D(diffuseSampler,vUVDiffuse);\nfinalColor.a*=albedoTexture.a;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vUVOpacity);\n#ifdef OPACITYRGB\nfinalColor.a*=getLuminance(opacityMap.rgb);\n#else\nfinalColor.a*=opacityMap.a;\n#endif\nfinalColor.a*=opacityIntensity;\n#endif\n#ifdef VERTEXALPHA\nfinalColor.a*=vColor.a;\n#endif\n#ifdef ALPHATEST\nif (finalColor.a4&&(o.push(Oi.b.MatricesIndicesExtraKind),o.push(Oi.b.MatricesWeightsExtraKind)),r.push("#define NUM_BONE_INFLUENCERS "+s.numBoneInfluencers),r.push("#define BonesPerMesh "+(s.skeleton?s.skeleton.bones.length+1:0))):r.push("#define NUM_BONE_INFLUENCERS 0");var f=s.morphTargetManager,p=0;f&&f.numInfluencers>0&&(r.push("#define MORPHTARGETS"),p=f.numInfluencers,r.push("#define NUM_MORPH_INFLUENCERS "+p),Er.a.PrepareAttributesForMorphTargets(o,s,{NUM_MORPH_INFLUENCERS:p})),t&&(r.push("#define INSTANCES"),Er.a.PushAttributesForInstances(o)),this._addCustomEffectDefines(r);var _=r.join("\n");return this._cachedDefines!==_&&(this._cachedDefines=_,this._effectLayerMapGenerationEffect=this._scene.getEngine().createEffect("glowMapGeneration",o,["world","mBones","viewProjection","glowColor","morphTargetInfluences","diffuseMatrix","emissiveMatrix","opacityMatrix","opacityIntensity"],["diffuseSampler","emissiveSampler","opacitySampler"],_,void 0,void 0,void 0,{maxSimultaneousMorphTargets:p})),this._effectLayerMapGenerationEffect.isReady()},e.prototype.render=function(){var e=this._mergeEffect;if(e.isReady()){for(var t=0;t-1&&this._scene.effectLayers.splice(t,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onBeforeRenderMainTextureObservable.clear(),this.onBeforeComposeObservable.clear(),this.onAfterComposeObservable.clear(),this.onSizeChangedObservable.clear()},e.prototype.getClassName=function(){return"EffectLayer"},e.Parse=function(e,t,i){return ye.h.Instantiate(e.customType).Parse(e,t,i)},e._SceneComponentInitialization=function(e){throw be.a.WarnImport("EffectLayerSceneComponent")},l.c([Object(L.c)()],e.prototype,"name",void 0),l.c([Object(L.f)()],e.prototype,"neutralColor",void 0),l.c([Object(L.c)()],e.prototype,"isEnabled",void 0),l.c([Object(L.d)()],e.prototype,"camera",null),l.c([Object(L.c)()],e.prototype,"renderingGroupId",null),e}();n.a.AddParser(xe.a.NAME_EFFECTLAYER,function(e,t,i,n){if(e.effectLayers){i.effectLayers||(i.effectLayers=new Array);for(var r=0;r0){this._previousStencilState=this._engine.getStencilBuffer();for(var n=0,r=i;n-1)){this._renderEffects=!0,this._needStencil=this._needStencil||o.needStencil();var s=o._mainTexture;s._shouldRender()&&(this.scene.incrementRenderId(),s.render(!1,!1),t=!0)}}this.scene.incrementRenderId()}return t},e.prototype._setStencil=function(){this._needStencil&&this._engine.setStencilBuffer(!0)},e.prototype._setStencilBack=function(){this._needStencil&&this._engine.setStencilBuffer(this._previousStencilState)},e.prototype._draw=function(e){if(this._renderEffects){this._engine.setDepthBuffer(!1);for(var t=this.scene.effectLayers,i=0;i0&&e.isBackground===t&&e.renderTargetTextures.indexOf(n)>-1&&0!=(e.layerMask&i)},e.prototype._drawRenderTargetBackground=function(e){var t=this;this._draw(function(i){return t._drawRenderTargetPredicate(i,!0,t.scene.activeCamera.layerMask,e)})},e.prototype._drawRenderTargetForeground=function(e){var t=this;this._draw(function(i){return t._drawRenderTargetPredicate(i,!1,t.scene.activeCamera.layerMask,e)})},e.prototype.addFromContainer=function(e){var t=this;e.layers&&e.layers.forEach(function(e){t.scene.layers.push(e)})},e.prototype.removeFromContainer=function(e,t){var i=this;void 0===t&&(t=!1),e.layers&&e.layers.forEach(function(e){var n=i.scene.layers.indexOf(e);-1!==n&&i.scene.layers.splice(n,1),t&&e.dispose()})},e}(),Lo="\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}";zt.a.ShadersStore.layerPixelShader=Lo;var wo="\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}";zt.a.ShadersStore.layerVertexShader=wo;var Fo=function(){function e(e,t,i,n,s){this.name=e,this.scale=new o.w(1,1),this.offset=new o.w(0,0),this.alphaBlendingMode=_.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=t?new Ge.a(t,i,!0):null,this.isBackground=void 0===n||n,this.color=void 0===s?new o.f(1,1,1,1):s,this._scene=i||R.a.LastCreatedScene;var a=this._scene._getComponent(xe.a.NAME_LAYER);a||(a=new Do(this._scene),this._scene._addComponent(a)),this._scene.layers.push(this);var c=this._scene.getEngine(),l=[];l.push(1,1),l.push(-1,1),l.push(-1,-1),l.push(1,-1);var u=new Oi.b(c,l,Oi.b.PositionKind,!1,!1,2);this._vertexBuffers[Oi.b.PositionKind]=u,this._createIndexBuffer(),this._effect=c.createEffect("layer",[Oi.b.PositionKind],["textureMatrix","color","scale","offset"],["textureSampler"],""),this._alphaTestEffect=c.createEffect("layer",[Oi.b.PositionKind],["textureMatrix","color","scale","offset"],["textureSampler"],"#define ALPHATEST")}return Object.defineProperty(e.prototype,"onDispose",{set:function(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onBeforeRender",{set:function(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"onAfterRender",{set:function(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)},enumerable:!0,configurable:!0}),e.prototype._createIndexBuffer=function(){var e=this._scene.getEngine(),t=[];t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),this._indexBuffer=e.createIndexBuffer(t)},e.prototype._rebuild=function(){var e=this._vertexBuffers[Oi.b.PositionKind];e&&e._rebuild(),this._createIndexBuffer()},e.prototype.render=function(){var e=this.alphaTest?this._alphaTestEffect:this._effect;if(e.isReady()&&this.texture&&this.texture.isReady()){var t=this._scene.getEngine();this.onBeforeRenderObservable.notifyObservers(this),t.enableEffect(e),t.setState(!1),e.setTexture("textureSampler",this.texture),e.setMatrix("textureMatrix",this.texture.getTextureMatrix()),e.setFloat4("color",this.color.r,this.color.g,this.color.b,this.color.a),e.setVector2("offset",this.offset),e.setVector2("scale",this.scale),t.bindBuffers(this._vertexBuffers,this._indexBuffer,e),this.alphaTest?t.drawElementsType(To.a.TriangleFillMode,0,6):(t.setAlphaMode(this.alphaBlendingMode),t.drawElementsType(To.a.TriangleFillMode,0,6),t.setAlphaMode(_.a.ALPHA_DISABLE)),this.onAfterRenderObservable.notifyObservers(this)}},e.prototype.dispose=function(){var e=this._vertexBuffers[Oi.b.PositionKind];e&&(e.dispose(),this._vertexBuffers[Oi.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 t=this._scene.layers.indexOf(this);this._scene.layers.splice(t,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onAfterRenderObservable.clear(),this.onBeforeRenderObservable.clear()},e}(),No=function(){function e(e,t,i,n,r){this.size=e,this.position=t,this.alphaMode=_.a.ALPHA_ONEONE,this.color=i||new o.e(1,1,1),this.texture=n?new Ge.a(n,r.getScene(),!0):null,this._system=r,r.lensFlares.push(this)}return e.AddFlare=function(t,i,n,r,o){return new e(t,i,n,r,o)},e.prototype.dispose=function(){this.texture&&this.texture.dispose();var e=this._system.lensFlares.indexOf(this);this._system.lensFlares.splice(e,1)},e}(),Bo="\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}";zt.a.ShadersStore.lensFlarePixelShader=Bo;var Uo="\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}";zt.a.ShadersStore.lensFlareVertexShader=Uo;var Vo=function(){function e(t,i,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||R.a.LastCreatedScene,e._SceneComponentInitialization(this._scene),this._emitter=i,this.id=t,n.lensFlareSystems.push(this),this.meshesSelectionPredicate=function(e){return n.activeCamera&&e.material&&e.isVisible&&e.isEnabled()&&e.isBlocker&&0!=(e.layerMask&n.activeCamera.layerMask)};var r=n.getEngine(),o=[];o.push(1,1),o.push(-1,1),o.push(-1,-1),o.push(1,-1),this._vertexBuffers[Oi.b.PositionKind]=new Oi.b(r,o,Oi.b.PositionKind,!1,!1,2);var s=[];s.push(0),s.push(1),s.push(2),s.push(0),s.push(2),s.push(3),this._indexBuffer=r.createIndexBuffer(s),this._effect=r.createEffect("lensFlare",[Oi.b.PositionKind],["color","viewportMatrix"],["textureSampler"],"")}return Object.defineProperty(e.prototype,"isEnabled",{get:function(){return this._isEnabled},set:function(e){this._isEnabled=e},enumerable:!0,configurable:!0}),e.prototype.getScene=function(){return this._scene},e.prototype.getEmitter=function(){return this._emitter},e.prototype.setEmitter=function(e){this._emitter=e},e.prototype.getEmitterPosition=function(){return this._emitter.getAbsolutePosition?this._emitter.getAbsolutePosition():this._emitter.position},e.prototype.computeEffectivePosition=function(e){var t=this.getEmitterPosition();return t=o.x.Project(t,o.j.Identity(),this._scene.getTransformMatrix(),e),this._positionX=t.x,this._positionY=t.y,t=o.x.TransformCoordinates(this.getEmitterPosition(),this._scene.getViewMatrix()),this.viewportBorder>0&&(e.x-=this.viewportBorder,e.y-=this.viewportBorder,e.width+=2*this.viewportBorder,e.height+=2*this.viewportBorder,t.x+=this.viewportBorder,t.y+=this.viewportBorder,this._positionX+=this.viewportBorder,this._positionY+=this.viewportBorder),t.z>0&&(this._positionX>e.x&&this._positionXe.y&&(this._positionY,e.y,e.height),!0)},e.prototype._isVisible=function(){if(!this._isEnabled||!this._scene.activeCamera)return!1;var e=this.getEmitterPosition().subtract(this._scene.activeCamera.globalPosition),t=e.length();e.normalize();var i=new It.a(this._scene.activeCamera.globalPosition,e),n=this._scene.pickWithRay(i,this.meshesSelectionPredicate,!0);return!n||!n.hit||n.distance>t},e.prototype.render=function(){if(!this._effect.isReady()||!this._scene.activeCamera)return!1;var e,t,i=this._scene.getEngine(),n=this._scene.activeCamera.viewport.toGlobal(i.getRenderWidth(!0),i.getRenderHeight(!0));if(!this.computeEffectivePosition(n))return!1;if(!this._isVisible())return!1;var r=(e=this._positionXn.x+n.width-this.borderLimit?this._positionX-n.x-n.width+this.borderLimit:0)>(t=this._positionYn.y+n.height-this.borderLimit?this._positionY-n.y-n.height+this.borderLimit:0)?e:t;(r-=this.viewportBorder)>this.borderLimit&&(r=this.borderLimit);var s=1-D.a.Clamp(r/this.borderLimit,0,1);if(s<0)return!1;s>1&&(s=1),this.viewportBorder>0&&(n.x+=this.viewportBorder,n.y+=this.viewportBorder,n.width-=2*this.viewportBorder,n.height-=2*this.viewportBorder,this._positionX-=this.viewportBorder,this._positionY-=this.viewportBorder);var a=n.x+n.width/2,c=n.y+n.height/2,l=a-this._positionX,u=c-this._positionY;i.enableEffect(this._effect),i.setState(!1),i.setDepthBuffer(!1),i.bindBuffers(this._vertexBuffers,this._indexBuffer,this._effect);for(var h=0;h0);for(var i=0,n=t;i0)}},e}();Vo._SceneComponentInitialization=function(e){var t=e._getComponent(xe.a.NAME_LENSFLARESYSTEM);t||(t=new ko(e),e._addComponent(t))};var Go="#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}";zt.a.ShadersStore.shadowMapPixelShader=Go;var zo="\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n\n#include\n#include\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}";zt.a.ShadersStore.shadowMapVertexShader=zo;var jo="\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}";zt.a.ShadersStore.depthBoxBlurPixelShader=jo;var Wo=function(){function e(t,i,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=e.FILTER_NONE,this._filteringQuality=e.QUALITY_HIGH,this._contactHardeningLightSizeUVRatio=.1,this._darkness=0,this._transparencyShadow=!1,this.frustumEdgeFalloff=0,this.forceBackFacesOnly=!1,this._lightDirection=o.x.Zero(),this._viewMatrix=o.j.Zero(),this._projectionMatrix=o.j.Zero(),this._transformMatrix=o.j.Zero(),this._cachedPosition=new o.x(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cachedDirection=new o.x(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._currentFaceIndex=0,this._currentFaceIndexCache=0,this._defaultTextureMatrix=o.j.Identity(),this._mapSize=t,this._light=i,this._scene=i.getScene(),i._shadowGenerator=this,e._SceneComponentInitialization(this._scene);var s=this._scene.getEngine().getCaps();n?s.textureFloatRender&&s.textureFloatLinearFiltering?this._textureType=_.a.TEXTURETYPE_FLOAT:s.textureHalfFloatRender&&s.textureHalfFloatLinearFiltering?this._textureType=_.a.TEXTURETYPE_HALF_FLOAT:this._textureType=_.a.TEXTURETYPE_UNSIGNED_INT:s.textureHalfFloatRender&&s.textureHalfFloatLinearFiltering?this._textureType=_.a.TEXTURETYPE_HALF_FLOAT:s.textureFloatRender&&s.textureFloatLinearFiltering?this._textureType=_.a.TEXTURETYPE_FLOAT:this._textureType=_.a.TEXTURETYPE_UNSIGNED_INT,this._initializeGenerator(),this._applyFilterValues()}return Object.defineProperty(e.prototype,"bias",{get:function(){return this._bias},set:function(e){this._bias=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"normalBias",{get:function(){return this._normalBias},set:function(e){this._normalBias=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"blurBoxOffset",{get:function(){return this._blurBoxOffset},set:function(e){this._blurBoxOffset!==e&&(this._blurBoxOffset=e,this._disposeBlurPostProcesses())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"blurScale",{get:function(){return this._blurScale},set:function(e){this._blurScale!==e&&(this._blurScale=e,this._disposeBlurPostProcesses())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"blurKernel",{get:function(){return this._blurKernel},set:function(e){this._blurKernel!==e&&(this._blurKernel=e,this._disposeBlurPostProcesses())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"useKernelBlur",{get:function(){return this._useKernelBlur},set:function(e){this._useKernelBlur!==e&&(this._useKernelBlur=e,this._disposeBlurPostProcesses())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"depthScale",{get:function(){return void 0!==this._depthScale?this._depthScale:this._light.getDepthScale()},set:function(e){this._depthScale=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"filter",{get:function(){return this._filter},set:function(t){if(this._light.needCube()){if(t===e.FILTER_BLUREXPONENTIALSHADOWMAP)return void(this.useExponentialShadowMap=!0);if(t===e.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP)return void(this.useCloseExponentialShadowMap=!0);if(t===e.FILTER_PCF||t===e.FILTER_PCSS)return void(this.usePoissonSampling=!0)}t!==e.FILTER_PCF&&t!==e.FILTER_PCSS||1!==this._scene.getEngine().webGLVersion?this._filter!==t&&(this._filter=t,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty()):this.usePoissonSampling=!0},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"usePoissonSampling",{get:function(){return this.filter===e.FILTER_POISSONSAMPLING},set:function(t){(t||this.filter===e.FILTER_POISSONSAMPLING)&&(this.filter=t?e.FILTER_POISSONSAMPLING:e.FILTER_NONE)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"useExponentialShadowMap",{get:function(){return this.filter===e.FILTER_EXPONENTIALSHADOWMAP},set:function(t){(t||this.filter===e.FILTER_EXPONENTIALSHADOWMAP)&&(this.filter=t?e.FILTER_EXPONENTIALSHADOWMAP:e.FILTER_NONE)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"useBlurExponentialShadowMap",{get:function(){return this.filter===e.FILTER_BLUREXPONENTIALSHADOWMAP},set:function(t){(t||this.filter===e.FILTER_BLUREXPONENTIALSHADOWMAP)&&(this.filter=t?e.FILTER_BLUREXPONENTIALSHADOWMAP:e.FILTER_NONE)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"useCloseExponentialShadowMap",{get:function(){return this.filter===e.FILTER_CLOSEEXPONENTIALSHADOWMAP},set:function(t){(t||this.filter===e.FILTER_CLOSEEXPONENTIALSHADOWMAP)&&(this.filter=t?e.FILTER_CLOSEEXPONENTIALSHADOWMAP:e.FILTER_NONE)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"useBlurCloseExponentialShadowMap",{get:function(){return this.filter===e.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP},set:function(t){(t||this.filter===e.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP)&&(this.filter=t?e.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP:e.FILTER_NONE)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"usePercentageCloserFiltering",{get:function(){return this.filter===e.FILTER_PCF},set:function(t){(t||this.filter===e.FILTER_PCF)&&(this.filter=t?e.FILTER_PCF:e.FILTER_NONE)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"filteringQuality",{get:function(){return this._filteringQuality},set:function(e){this._filteringQuality!==e&&(this._filteringQuality=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"useContactHardeningShadow",{get:function(){return this.filter===e.FILTER_PCSS},set:function(t){(t||this.filter===e.FILTER_PCSS)&&(this.filter=t?e.FILTER_PCSS:e.FILTER_NONE)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"contactHardeningLightSizeUVRatio",{get:function(){return this._contactHardeningLightSizeUVRatio},set:function(e){this._contactHardeningLightSizeUVRatio=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"darkness",{get:function(){return this._darkness},set:function(e){this.setDarkness(e)},enumerable:!0,configurable:!0}),e.prototype.getDarkness=function(){return this._darkness},e.prototype.setDarkness=function(e){return this._darkness=e>=1?1:e<=0?0:e,this},Object.defineProperty(e.prototype,"transparencyShadow",{get:function(){return this._transparencyShadow},set:function(e){this.setTransparencyShadow(e)},enumerable:!0,configurable:!0}),e.prototype.setTransparencyShadow=function(e){return this._transparencyShadow=e,this},e.prototype.getShadowMap=function(){return this._shadowMap},e.prototype.getShadowMapForRendering=function(){return this._shadowMap2?this._shadowMap2:this._shadowMap},e.prototype.getClassName=function(){return"ShadowGenerator"},e.prototype.addShadowCaster=function(e,t){var i;return void 0===t&&(t=!0),this._shadowMap?(this._shadowMap.renderList||(this._shadowMap.renderList=[]),this._shadowMap.renderList.push(e),t&&(i=this._shadowMap.renderList).push.apply(i,e.getChildMeshes()),this):this},e.prototype.removeShadowCaster=function(e,t){if(void 0===t&&(t=!0),!this._shadowMap||!this._shadowMap.renderList)return this;var i=this._shadowMap.renderList.indexOf(e);if(-1!==i&&this._shadowMap.renderList.splice(i,1),t)for(var n=0,r=e.getChildren();n1?(this._shadowMap=new _i(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube(),void 0,!1,!1),this._shadowMap.createDepthStencilTexture(_.a.LESS,!0)):this._shadowMap=new _i(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube()),this._shadowMap.wrapU=Ge.a.CLAMP_ADDRESSMODE,this._shadowMap.wrapV=Ge.a.CLAMP_ADDRESSMODE,this._shadowMap.anisotropicFilteringLevel=1,this._shadowMap.updateSamplingMode(Ge.a.BILINEAR_SAMPLINGMODE),this._shadowMap.renderParticles=!1,this._shadowMap.ignoreCameraViewport=!0,this._shadowMap.onBeforeRenderObservable.add(function(n){t._currentFaceIndex=n,t._filter===e.FILTER_PCF&&i.setColorWrite(!1)}),this._shadowMap.customRenderFunction=this._renderForShadowMap.bind(this),this._shadowMap.onAfterUnbindObservable.add(function(){if(t._filter===e.FILTER_PCF&&i.setColorWrite(!0),t.useBlurExponentialShadowMap||t.useBlurCloseExponentialShadowMap){var n=t.getShadowMapForRendering();n&&t._scene.postProcessManager.directRender(t._blurPostProcesses,n.getInternalTexture(),!0)}});var n=new o.f(0,0,0,0),r=new o.f(1,1,1,1);this._shadowMap.onClearObservable.add(function(i){t._filter===e.FILTER_PCF?i.clear(r,!1,!0,!1):t.useExponentialShadowMap||t.useBlurExponentialShadowMap?i.clear(n,!0,!0,!1):i.clear(r,!0,!0,!1)})},e.prototype._initializeBlurRTTAndPostProcesses=function(){var e=this,t=this._scene.getEngine(),i=this._mapSize/this.blurScale;this.useKernelBlur&&1===this.blurScale||(this._shadowMap2=new _i(this._light.name+"_shadowMap2",i,this._scene,!1,!0,this._textureType),this._shadowMap2.wrapU=Ge.a.CLAMP_ADDRESSMODE,this._shadowMap2.wrapV=Ge.a.CLAMP_ADDRESSMODE,this._shadowMap2.updateSamplingMode(Ge.a.BILINEAR_SAMPLINGMODE)),this.useKernelBlur?(this._kernelBlurXPostprocess=new yr(this._light.name+"KernelBlurX",new o.w(1,0),this.blurKernel,1,null,Ge.a.BILINEAR_SAMPLINGMODE,t,!1,this._textureType),this._kernelBlurXPostprocess.width=i,this._kernelBlurXPostprocess.height=i,this._kernelBlurXPostprocess.onApplyObservable.add(function(t){t.setTexture("textureSampler",e._shadowMap)}),this._kernelBlurYPostprocess=new yr(this._light.name+"KernelBlurY",new o.w(0,1),this.blurKernel,1,null,Ge.a.BILINEAR_SAMPLINGMODE,t,!1,this._textureType),this._kernelBlurXPostprocess.autoClear=!1,this._kernelBlurYPostprocess.autoClear=!1,this._textureType===_.a.TEXTURETYPE_UNSIGNED_INT&&(this._kernelBlurXPostprocess.packedFloat=!0,this._kernelBlurYPostprocess.packedFloat=!0),this._blurPostProcesses=[this._kernelBlurXPostprocess,this._kernelBlurYPostprocess]):(this._boxBlurPostprocess=new Wt(this._light.name+"DepthBoxBlur","depthBoxBlur",["screenSize","boxOffset"],[],1,null,Ge.a.BILINEAR_SAMPLINGMODE,t,!1,"#define OFFSET "+this._blurBoxOffset,this._textureType),this._boxBlurPostprocess.onApplyObservable.add(function(t){t.setFloat2("screenSize",i,i),t.setTexture("textureSampler",e._shadowMap)}),this._boxBlurPostprocess.autoClear=!1,this._blurPostProcesses=[this._boxBlurPostprocess])},e.prototype._renderForShadowMap=function(e,t,i,n){var r,o=this._scene.getEngine();if(n.length){for(o.setColorWrite(!1),r=0;r=s.length)return void(e&&e(i));setTimeout(d,16)}};d()}else e&&e(this)}else e&&e(this)}else e&&e(this)},e.prototype.forceCompilationAsync=function(e){var t=this;return new Promise(function(i){t.forceCompilation(function(){i()},e)})},e.prototype.isReady=function(e,t){var i=[];this._textureType!==_.a.TEXTURETYPE_UNSIGNED_INT&&i.push("#define FLOAT"),this.useExponentialShadowMap||this.useBlurExponentialShadowMap?i.push("#define ESM"):(this.usePercentageCloserFiltering||this.useContactHardeningShadow)&&i.push("#define DEPTHTEXTURE");var n=[Oi.b.PositionKind],r=e.getMesh(),o=e.getMaterial();if(this.normalBias&&r.isVerticesDataPresent(Oi.b.NormalKind)&&(n.push(Oi.b.NormalKind),i.push("#define NORMAL"),r.nonUniformScaling&&i.push("#define NONUNIFORMSCALING"),this.getLight().getTypeID()===lr.a.LIGHTTYPEID_DIRECTIONALLIGHT&&i.push("#define DIRECTIONINLIGHTDATA")),o&&o.needAlphaTesting()){var s=o.getAlphaTestTexture();s&&(i.push("#define ALPHATEST"),r.isVerticesDataPresent(Oi.b.UVKind)&&(n.push(Oi.b.UVKind),i.push("#define UV1")),r.isVerticesDataPresent(Oi.b.UV2Kind)&&1===s.coordinatesIndex&&(n.push(Oi.b.UV2Kind),i.push("#define UV2")))}if(r.useBones&&r.computeBonesUsingShaders&&r.skeleton){n.push(Oi.b.MatricesIndicesKind),n.push(Oi.b.MatricesWeightsKind),r.numBoneInfluencers>4&&(n.push(Oi.b.MatricesIndicesExtraKind),n.push(Oi.b.MatricesWeightsExtraKind));var a=r.skeleton;i.push("#define NUM_BONE_INFLUENCERS "+r.numBoneInfluencers),a.isUsingTextureForMatrices?i.push("#define BONETEXTURE"):i.push("#define BonesPerMesh "+(a.bones.length+1))}else i.push("#define NUM_BONE_INFLUENCERS 0");var c=r.morphTargetManager,l=0;if(c&&c.numInfluencers>0&&(i.push("#define MORPHTARGETS"),l=c.numInfluencers,i.push("#define NUM_MORPH_INFLUENCERS "+l),Er.a.PrepareAttributesForMorphTargets(n,r,{NUM_MORPH_INFLUENCERS:l})),t&&(i.push("#define INSTANCES"),Er.a.PushAttributesForInstances(n)),this.customShaderOptions&&this.customShaderOptions.defines)for(var u=0,h=this.customShaderOptions.defines;uMath.PI;)r-=2*Math.PI;var s=r/Math.PI,a=o/Math.PI;s=.5*s+.5;var c=Math.round(s*i);c<0?c=0:c>=i&&(c=i-1);var l=Math.round(a*n);l<0?l=0:l>=n&&(l=n-1);var u=n-l-1;return{r:t[u*i*3+3*c+0],g:t[u*i*3+3*c+1],b:t[u*i*3+3*c+2]}},e.FACE_FRONT=[new o.x(-1,-1,-1),new o.x(1,-1,-1),new o.x(-1,1,-1),new o.x(1,1,-1)],e.FACE_BACK=[new o.x(1,-1,1),new o.x(-1,-1,1),new o.x(1,1,1),new o.x(-1,1,1)],e.FACE_RIGHT=[new o.x(1,-1,-1),new o.x(1,-1,1),new o.x(1,1,-1),new o.x(1,1,1)],e.FACE_LEFT=[new o.x(-1,-1,1),new o.x(-1,-1,-1),new o.x(-1,1,1),new o.x(-1,1,-1)],e.FACE_DOWN=[new o.x(-1,1,-1),new o.x(1,1,-1),new o.x(-1,1,1),new o.x(1,1,1)],e.FACE_UP=[new o.x(-1,-1,1),new o.x(1,-1,1),new o.x(-1,-1,-1),new o.x(1,-1,-1)],e}(),Zo=function(){function e(){}return e.Ldexp=function(e,t){return t>1023?e*Math.pow(2,1023)*Math.pow(2,t-1023):t<-1074?e*Math.pow(2,-1074)*Math.pow(2,t+1074):e*Math.pow(2,t)},e.Rgbe2float=function(e,t,i,n,r,o){r>0?(r=this.Ldexp(1,r-136),e[o+0]=t*r,e[o+1]=i*r,e[o+2]=n*r):(e[o+0]=0,e[o+1]=0,e[o+2]=0)},e.readStringLine=function(e,t){for(var i="",n="",r=t;r32767)throw"HDR Bad header format, unsupported size";return{height:t,width:i,dataPosition:s+=n.length+1}},e.GetCubeMapTextureData=function(e,t){var i=new Uint8Array(e),n=this.RGBE_ReadHeader(i),r=this.RGBE_ReadPixels_RLE(i,n);return qo.ConvertPanoramaToCubemap(r,n.width,n.height,t)},e.RGBE_ReadPixels=function(e,t){return this.RGBE_ReadPixels_RLE(e,t)},e.RGBE_ReadPixels_RLE=function(e,t){for(var i,n,r,o,s,a=t.height,c=t.width,l=t.dataPosition,u=0,h=0,d=0,f=new ArrayBuffer(4*c),p=new Uint8Array(f),_=new ArrayBuffer(t.width*t.height*4*3),m=new Float32Array(_);a>0;){if(i=e[l++],n=e[l++],r=e[l++],o=e[l++],2!=i||2!=n||128&r)throw"HDR Bad header format, not RLE";if((r<<8|o)!=c)throw"HDR Bad header format, wrong scan line width";for(u=0,d=0;d<4;d++)for(h=(d+1)*c;u128){if(0==(s=i-128)||s>h-u)throw"HDR Bad Format, bad scanline data (run)";for(;s-- >0;)p[u++]=n}else{if(0==(s=i)||s>h-u)throw"HDR Bad Format, bad scanline data (non-run)";if(p[u++]=n,--s>0)for(var g=0;g255){var g=255/m;f*=g,p*=g,_*=g}c[3*d+0]=f,c[3*d+1]=p,c[3*d+2]=_}c?a.push(c):a.push(h)}return a},null,this._onLoad,this._onError))},t.prototype.clone=function(){var e=this.getScene();if(!e)return this;var i=new t(this.url,e,this._size,this._noMipmap,this._generateHarmonics,this.gammaSpace);return i.level=this.level,i.wrapU=this.wrapU,i.wrapV=this.wrapV,i.coordinatesIndex=this.coordinatesIndex,i.coordinatesMode=this.coordinatesMode,i},t.prototype.delayLoad=function(){this.delayLoadState===me.b.DELAYLOADSTATE_NOTLOADED&&(this.delayLoadState=me.b.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 t=this;this._textureMatrix=e,e.updateFlag!==this._textureMatrix.updateFlag&&e.isIdentity()!==this._textureMatrix.isIdentity()&&this.getScene().markAllMaterialsAsDirty(_.a.MATERIAL_TextureDirtyFlag,function(e){return-1!==e.getActiveTextures().indexOf(t)})},t.Parse=function(e,i,n){var r=null;return e.name&&!e.isRenderTarget&&((r=new t(n+e.name,i,e.size,e.noMipmap,e.generateHarmonics,e.useInGammaSpace)).name=e.name,r.hasAlpha=e.hasAlpha,r.level=e.level,r.coordinatesMode=e.coordinatesMode,r.isBlocking=e.isBlocking),r&&(e.boundingBoxPosition&&(r.boundingBoxPosition=o.x.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(r.boundingBoxSize=o.x.FromArray(e.boundingBoxSize)),e.rotationY&&(r.rotationY=e.rotationY)),r},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}(vn.a);s.a.RegisteredTypes["BABYLON.HDRCubeTexture"]=Jo;var $o=function(){function e(e,t,i){void 0===t&&(t=0),void 0===i&&(i=null),this.name=e,this.animations=new Array,this._positions=null,this._normals=null,this._tangents=null,this.onInfluenceChanged=new r.c,this._onDataLayoutChanged=new r.c,this._animationPropertiesOverride=null,this._scene=i||R.a.LastCreatedScene,this.influence=t}return Object.defineProperty(e.prototype,"influence",{get:function(){return this._influence},set:function(e){if(this._influence!==e){var t=this._influence;this._influence=e,this.onInfluenceChanged.hasObservers&&this.onInfluenceChanged.notifyObservers(0===t||0===e)}},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"animationPropertiesOverride",{get:function(){return!this._animationPropertiesOverride&&this._scene?this._scene.animationPropertiesOverride:this._animationPropertiesOverride},set:function(e){this._animationPropertiesOverride=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"hasPositions",{get:function(){return!!this._positions},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"hasNormals",{get:function(){return!!this._normals},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"hasTangents",{get:function(){return!!this._tangents},enumerable:!0,configurable:!0}),e.prototype.setPositions=function(e){var t=this.hasPositions;this._positions=e,t!==this.hasPositions&&this._onDataLayoutChanged.notifyObservers(void 0)},e.prototype.getPositions=function(){return this._positions},e.prototype.setNormals=function(e){var t=this.hasNormals;this._normals=e,t!==this.hasNormals&&this._onDataLayoutChanged.notifyObservers(void 0)},e.prototype.getNormals=function(){return this._normals},e.prototype.setTangents=function(e){var t=this.hasTangents;this._tangents=e,t!==this.hasTangents&&this._onDataLayoutChanged.notifyObservers(void 0)},e.prototype.getTangents=function(){return this._tangents},e.prototype.serialize=function(){var e={};return e.name=this.name,e.influence=this.influence,e.positions=Array.prototype.slice.call(this.getPositions()),null!=this.id&&(e.id=this.id),this.hasNormals&&(e.normals=Array.prototype.slice.call(this.getNormals())),this.hasTangents&&(e.tangents=Array.prototype.slice.call(this.getTangents())),L.a.AppendSerializedAnimations(this,e),e},e.prototype.getClassName=function(){return"MorphTarget"},e.Parse=function(t){var i=new e(t.name,t.influence);if(i.setPositions(t.positions),null!=t.id&&(i.id=t.id),t.normals&&i.setNormals(t.normals),t.tangents&&i.setTangents(t.tangents),t.animations)for(var n=0;n=0&&(this._targets.splice(t,1),e.onInfluenceChanged.remove(this._targetInfluenceChangedObservers.splice(t,1)[0]),e._onDataLayoutChanged.remove(this._targetDataLayoutChangedObservers.splice(t,1)[0]),this._syncActiveTargets(!0))},e.prototype.serialize=function(){var e={};e.id=this.uniqueId,e.targets=[];for(var t=0,i=this._targets;t-1&&(this._impostors.splice(t,1).length&&this.getPhysicsPlugin().removePhysicsBody(e))},e.prototype.addJoint=function(e,t,i){var n={mainImpostor:e,connectedImpostor:t,joint:i};i.physicsPlugin=this._physicsPlugin,this._joints.push(n),this._physicsPlugin.generateJoint(n)},e.prototype.removeJoint=function(e,t,i){var n=this._joints.filter(function(n){return n.connectedImpostor===t&&n.joint===i&&n.mainImpostor===e});n.length&&this._physicsPlugin.removeJoint(n[0])},e.prototype._step=function(e){var t=this;this._impostors.forEach(function(e){e.isBodyInitRequired()&&t._physicsPlugin.generatePhysicsBody(e)}),e>.1?e=.1:e<=0&&(e=1/60),this._physicsPlugin.executeStep(e,this._impostors)},e.prototype.getPhysicsPlugin=function(){return this._physicsPlugin},e.prototype.getImpostors=function(){return this._impostors},e.prototype.getImpostorForPhysicsObject=function(e){for(var t=0;t0&&(this._removeAfterStep.forEach(function(e){t.world.remove(e.physicsBody)}),this._removeAfterStep=[])},e.prototype.applyImpulse=function(e,t,i){var n=new this.BJSCANNON.Vec3(i.x,i.y,i.z),r=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyImpulse(r,n)},e.prototype.applyForce=function(e,t,i){var n=new this.BJSCANNON.Vec3(i.x,i.y,i.z),r=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyForce(r,n)},e.prototype.generatePhysicsBody=function(e){if(e.parent)e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate());else{if(e.isBodyInitRequired()){var t=this._createShape(e),i=e.physicsBody;i&&this.removePhysicsBody(e);var n=this._addMaterial("mat-"+e.uniqueId,e.getParam("friction"),e.getParam("restitution")),r={mass:e.getParam("mass"),material:n},o=e.getParam("nativeOptions");for(var s in o)o.hasOwnProperty(s)&&(r[s]=o[s]);e.physicsBody=new this.BJSCANNON.Body(r),e.physicsBody.addEventListener("collide",e.onCollide),this.world.addEventListener("preStep",e.beforeStep),this.world.addEventListener("postStep",e.afterStep),e.physicsBody.addShape(t),this.world.add(e.physicsBody),i&&["force","torque","velocity","angularVelocity"].forEach(function(t){e.physicsBody[t].copy(i[t])}),this._processChildMeshes(e)}this._updatePhysicsBodyTransformation(e)}},e.prototype._processChildMeshes=function(e){var t=this,i=e.object.getChildMeshes?e.object.getChildMeshes(!0):[],n=e.object.rotationQuaternion;if(i.length){var r=function(i,s){if(n&&s.rotationQuaternion){var a=s.getPhysicsImpostor();if(a)if(a.parent!==e){var c=s.getAbsolutePosition().subtract(e.object.getAbsolutePosition()),l=s.rotationQuaternion.multiply(o.q.Inverse(n));a.physicsBody&&(t.removePhysicsBody(a),a.physicsBody=null),a.parent=e,a.resetUpdateFlags(),e.physicsBody.addShape(t._createShape(a),new t.BJSCANNON.Vec3(c.x,c.y,c.z),new t.BJSCANNON.Quaternion(l.x,l.y,l.z,l.w)),e.physicsBody.mass+=a.getParam("mass")}n.multiplyInPlace(s.rotationQuaternion),s.getChildMeshes(!0).filter(function(e){return!!e.physicsImpostor}).forEach(r.bind(t,s.getAbsolutePosition()))}};i.filter(function(e){return!!e.physicsImpostor}).forEach(r.bind(this,e.object.getAbsolutePosition()))}},e.prototype.removePhysicsBody=function(e){e.physicsBody.removeEventListener("collide",e.onCollide),this.world.removeEventListener("preStep",e.beforeStep),this.world.removeEventListener("postStep",e.afterStep),this._removeAfterStep.push(e)},e.prototype.generateJoint=function(e){var t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(t&&i){var n,r=e.joint.jointData,o={pivotA:r.mainPivot?(new this.BJSCANNON.Vec3).copy(r.mainPivot):null,pivotB:r.connectedPivot?(new this.BJSCANNON.Vec3).copy(r.connectedPivot):null,axisA:r.mainAxis?(new this.BJSCANNON.Vec3).copy(r.mainAxis):null,axisB:r.connectedAxis?(new this.BJSCANNON.Vec3).copy(r.connectedAxis):null,maxForce:r.nativeParams.maxForce,collideConnected:!!r.collision};switch(e.joint.type){case is.e.HingeJoint:case is.e.Hinge2Joint:n=new this.BJSCANNON.HingeConstraint(t,i,o);break;case is.e.DistanceJoint:n=new this.BJSCANNON.DistanceConstraint(t,i,r.maxDistance||2);break;case is.e.SpringJoint:var s=r;n=new this.BJSCANNON.Spring(t,i,{restLength:s.length,stiffness:s.stiffness,damping:s.damping,localAnchorA:o.pivotA,localAnchorB:o.pivotB});break;case is.e.LockJoint:n=new this.BJSCANNON.LockConstraint(t,i,o);break;case is.e.PointToPointJoint:case is.e.BallAndSocketJoint:default:n=new this.BJSCANNON.PointToPointConstraint(t,o.pivotA,i,o.pivotB,o.maxForce)}n.collideConnected=!!r.collision,e.joint.physicsJoint=n,e.joint.type!==is.e.SpringJoint?this.world.addConstraint(n):(e.joint.jointData.forceApplicationCallback=e.joint.jointData.forceApplicationCallback||function(){n.applyForce()},e.mainImpostor.registerAfterPhysicsStep(e.joint.jointData.forceApplicationCallback))}},e.prototype.removeJoint=function(e){e.joint.type!==is.e.SpringJoint?this.world.removeConstraint(e.joint.physicsJoint):e.mainImpostor.unregisterAfterPhysicsStep(e.joint.jointData.forceApplicationCallback)},e.prototype._addMaterial=function(e,t,i){var n,r;for(n=0;n1e3*i));a++);this.time+=n;for(var c=this.time%i/i,l=e,u=this.bodies,h=0;h!==u.length;h++){var d=u[h];d.type!==t.Body.STATIC&&d.sleepState!==t.Body.SLEEPING?(d.position.vsub(d.previousPosition,l),l.scale(c,l),d.position.vadd(l,d.interpolatedPosition)):(d.interpolatedPosition.copy(d.position),d.interpolatedQuaternion.copy(d.quaternion))}}}},e.prototype.raycast=function(e,t){return this._cannonRaycastResult.reset(),this.world.raycastClosest(e,t,{},this._cannonRaycastResult),this._raycastResult.reset(e,t),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},e}();ns.DefaultPluginFactory=function(){return new os};var ss=function(){function e(e,t){void 0===t&&(t=OIMO),this.name="OimoJSPlugin",this._tmpImpostorsArray=[],this._tmpPositionVector=o.x.Zero(),this.BJSOIMO=t,this.world=new this.BJSOIMO.World({iterations:e}),this.world.clear(),this._raycastResult=new rs}return e.prototype.setGravity=function(e){this.world.gravity.copy(e)},e.prototype.setTimeStep=function(e){this.world.timeStep=e},e.prototype.getTimeStep=function(){return this.world.timeStep},e.prototype.executeStep=function(e,t){var i=this;t.forEach(function(e){e.beforeStep()}),this.world.step(),t.forEach(function(e){e.afterStep(),i._tmpImpostorsArray[e.uniqueId]=e});for(var n=this.world.contacts;null!==n;)if(!n.touching||n.body1.sleeping||n.body2.sleeping){var r=this._tmpImpostorsArray[+n.body1.name],o=this._tmpImpostorsArray[+n.body2.name];r&&o?(r.onCollide({body:o.physicsBody}),o.onCollide({body:r.physicsBody}),n=n.next):n=n.next}else n=n.next},e.prototype.applyImpulse=function(e,t,i){var n=e.physicsBody.mass;e.physicsBody.applyImpulse(i.scale(this.world.invScale),t.scale(this.world.invScale*n))},e.prototype.applyForce=function(e,t,i){p.a.Warn("Oimo doesn't support applying force. Using impule instead."),this.applyImpulse(e,t,i)},e.prototype.generatePhysicsBody=function(e){var t=this;if(e.parent)e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate());else{if(e.isBodyInitRequired()){var i={name:e.uniqueId,config:[e.getParam("mass")||1,e.getParam("friction"),e.getParam("restitution")],size:[],type:[],pos:[],posShape:[],rot:[],rotShape:[],move:0!==e.getParam("mass"),density:e.getParam("mass"),friction:e.getParam("friction"),restitution:e.getParam("restitution"),world:this.world},n=[e];(a=e.object).getChildMeshes&&a.getChildMeshes().forEach(function(e){e.physicsImpostor&&n.push(e.physicsImpostor)});var r=function(e){return Math.max(e,ns.Epsilon)},s=new o.q;n.forEach(function(n){if(n.object.rotationQuaternion){var o=n.object.rotationQuaternion;s=o.clone();var a=o.toEulerAngles(),c=n.getObjectExtendSize();if(n===e){var l=e.getObjectCenter();e.object.getAbsolutePivotPoint().subtractToRef(l,t._tmpPositionVector),t._tmpPositionVector.divideInPlace(e.object.scaling),i.pos.push(l.x),i.pos.push(l.y),i.pos.push(l.z),i.posShape.push(0,0,0),i.rotShape.push(0,0,0)}else{var u=n.object.getAbsolutePosition().subtract(e.object.getAbsolutePosition());i.posShape.push(u.x),i.posShape.push(u.y),i.posShape.push(u.z),i.pos.push(0,0,0),i.rotShape.push(57.29577951308232*a.x),i.rotShape.push(57.29577951308232*a.y),i.rotShape.push(57.29577951308232*a.z)}switch(n.type){case ts.a.ParticleImpostor:p.a.Warn("No Particle support in OIMO.js. using SphereImpostor instead");case ts.a.SphereImpostor:var h=c.x,d=c.y,f=c.z,_=Math.max(r(h),r(d),r(f))/2;i.type.push("sphere"),i.size.push(_),i.size.push(_),i.size.push(_);break;case ts.a.CylinderImpostor:var m=r(c.x)/2,g=r(c.y);i.type.push("cylinder"),i.size.push(m),i.size.push(g),i.size.push(g);break;case ts.a.PlaneImpostor:case ts.a.BoxImpostor:default:m=r(c.x),g=r(c.y);var v=r(c.z);i.type.push("box"),i.size.push(m),i.size.push(g),i.size.push(v)}n.object.rotationQuaternion=o}}),e.physicsBody=this.world.add(i),e.physicsBody.resetQuaternion(s),e.physicsBody.updatePosition(0)}else this._tmpPositionVector.copyFromFloats(0,0,0);var a;e.setDeltaPosition(this._tmpPositionVector)}},e.prototype.removePhysicsBody=function(e){this.world.removeRigidBody(e.physicsBody)},e.prototype.generateJoint=function(e){var t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(t&&i){var n,r=e.joint.jointData,o=r.nativeParams||{},s={body1:t,body2:i,axe1:o.axe1||(r.mainAxis?r.mainAxis.asArray():null),axe2:o.axe2||(r.connectedAxis?r.connectedAxis.asArray():null),pos1:o.pos1||(r.mainPivot?r.mainPivot.asArray():null),pos2:o.pos2||(r.connectedPivot?r.connectedPivot.asArray():null),min:o.min,max:o.max,collision:o.collision||r.collision,spring:o.spring,world:this.world};switch(e.joint.type){case is.e.BallAndSocketJoint:n="jointBall";break;case is.e.SpringJoint:p.a.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");var a=r;s.min=a.length||s.min,s.max=Math.max(s.min,s.max);case is.e.DistanceJoint:n="jointDistance",s.max=r.maxDistance;break;case is.e.PrismaticJoint:n="jointPrisme";break;case is.e.SliderJoint:n="jointSlide";break;case is.e.WheelJoint:n="jointWheel";break;case is.e.HingeJoint:default:n="jointHinge"}s.type=n,e.joint.physicsJoint=this.world.add(s)}},e.prototype.removeJoint=function(e){try{this.world.removeJoint(e.joint.physicsJoint)}catch(e){p.a.Warn(e)}},e.prototype.isSupported=function(){return void 0!==this.BJSOIMO},e.prototype.setTransformationFromPhysicsBody=function(e){e.physicsBody.sleeping||(e.object.position.copyFrom(e.physicsBody.getPosition()),e.object.rotationQuaternion&&e.object.rotationQuaternion.copyFrom(e.physicsBody.getQuaternion()))},e.prototype.setPhysicsBodyTransformation=function(e,t,i){var n=e.physicsBody;n.position.copy(t),n.orientation.copy(i),n.syncShapes(),n.awake()},e.prototype.setLinearVelocity=function(e,t){e.physicsBody.linearVelocity.copy(t)},e.prototype.setAngularVelocity=function(e,t){e.physicsBody.angularVelocity.copy(t)},e.prototype.getLinearVelocity=function(e){var t=e.physicsBody.linearVelocity;return t?new o.x(t.x,t.y,t.z):null},e.prototype.getAngularVelocity=function(e){var t=e.physicsBody.angularVelocity;return t?new o.x(t.x,t.y,t.z):null},e.prototype.setBodyMass=function(e,t){var i=0===t;e.physicsBody.shapes.density=i?1:t,e.physicsBody.setupMass(i?2:1)},e.prototype.getBodyMass=function(e){return e.physicsBody.shapes.density},e.prototype.getBodyFriction=function(e){return e.physicsBody.shapes.friction},e.prototype.setBodyFriction=function(e,t){e.physicsBody.shapes.friction=t},e.prototype.getBodyRestitution=function(e){return e.physicsBody.shapes.restitution},e.prototype.setBodyRestitution=function(e,t){e.physicsBody.shapes.restitution=t},e.prototype.sleepBody=function(e){e.physicsBody.sleep()},e.prototype.wakeUpBody=function(e){e.physicsBody.awake()},e.prototype.updateDistanceJoint=function(e,t,i){e.physicsJoint.limitMotor.upperLimit=t,void 0!==i&&(e.physicsJoint.limitMotor.lowerLimit=i)},e.prototype.setMotor=function(e,t,i,n){void 0!==i?p.a.Warn("OimoJS plugin currently has unexpected behavior when using setMotor with force parameter"):i=1e6,t*=-1;var r=n?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;r&&r.setMotor(t,i)},e.prototype.setLimit=function(e,t,i,n){var r=n?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;r&&r.setLimit(t,void 0===i?-t:i)},e.prototype.syncMeshWithImpostor=function(e,t){var i=t.physicsBody;e.position.x=i.position.x,e.position.y=i.position.y,e.position.z=i.position.z,e.rotationQuaternion&&(e.rotationQuaternion.x=i.orientation.x,e.rotationQuaternion.y=i.orientation.y,e.rotationQuaternion.z=i.orientation.z,e.rotationQuaternion.w=i.orientation.s)},e.prototype.getRadius=function(e){return e.physicsBody.shapes.radius},e.prototype.getBoxSizeToRef=function(e,t){var i=e.physicsBody.shapes;t.x=2*i.halfWidth,t.y=2*i.halfHeight,t.z=2*i.halfDepth},e.prototype.dispose=function(){this.world.clear()},e.prototype.raycast=function(e,t){return p.a.Warn("raycast is not currently supported by the Oimo physics plugin"),this._raycastResult.reset(e,t),this._raycastResult},e}();Mi.a.CreateRibbon=function(e){var t=e.pathArray,i=e.closeArray||!1,n=e.closePath||!1,r=e.invertUV||!1,o=Math.floor(t[0].length/2),s=e.offset||o;s=s>o?o:Math.floor(s);var a,c,l,u,h=0===e.sideOrientation?0:e.sideOrientation||Mi.a.DEFAULTSIDE,d=e.uvs,f=e.colors,p=[],_=[],m=[],g=[],v=[],y=[],b=[],T=[],E=[],x=[];if(t.length<2){var A=[],P=[];for(l=0;l0&&(C=R[u].subtract(R[u-1]).length()+b[c],v[c].push(C),b[c]=C),u++;n&&(u--,p.push(R[0].x,R[0].y,R[0].z),C=R[u].subtract(R[0]).length()+b[c],v[c].push(C),b[c]=C),E[c]=S+D,x[c]=I,I+=S+D}var L,w,F=null,N=null;for(l=0;l3?0:u,h);var x=as.CreateRibbon(e,{pathArray:b,closeArray:c,closePath:l,updatable:f,sideOrientation:p,invertUV:m,frontUVs:g||void 0,backUVs:v||void 0},d);return x._creationDataStorage.pathArray=b,x._creationDataStorage.path3D=y,x._creationDataStorage.cap=u,x},e}(),ls=function(){function e(e,t,i){var n=this;void 0===e&&(e=!0),void 0===t&&(t=Ammo),void 0===i&&(i=null),this._useDeltaForWorldStep=e,this.bjsAMMO={},this.name="AmmoJSPlugin",this._timeStep=1/60,this._fixedTimeStep=1/60,this._maxSteps=5,this._tmpQuaternion=new o.q,this._tmpContactCallbackResult=!1,this._tmpVector=new o.x,this._tmpMatrix=new o.j,"function"==typeof t?t(this.bjsAMMO):this.bjsAMMO=t,this.isSupported()?(this._collisionConfiguration=new this.bjsAMMO.btSoftBodyRigidBodyCollisionConfiguration,this._dispatcher=new this.bjsAMMO.btCollisionDispatcher(this._collisionConfiguration),this._overlappingPairCache=i||new this.bjsAMMO.btDbvtBroadphase,this._solver=new this.bjsAMMO.btSequentialImpulseConstraintSolver,this._softBodySolver=new this.bjsAMMO.btDefaultSoftBodySolver,this.world=new this.bjsAMMO.btSoftRigidDynamicsWorld(this._dispatcher,this._overlappingPairCache,this._solver,this._collisionConfiguration,this._softBodySolver),this._tmpAmmoConcreteContactResultCallback=new this.bjsAMMO.ConcreteContactResultCallback,this._tmpAmmoConcreteContactResultCallback.addSingleResult=function(){n._tmpContactCallbackResult=!0},this._raycastResult=new rs,this._tmpAmmoTransform=new this.bjsAMMO.btTransform,this._tmpAmmoTransform.setIdentity(),this._tmpAmmoQuaternion=new this.bjsAMMO.btQuaternion(0,0,0,1),this._tmpAmmoVectorA=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorB=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorC=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorD=new this.bjsAMMO.btVector3(0,0,0)):p.a.Error("AmmoJS is not available. Please make sure you included the js file.")}return e.prototype.setGravity=function(e){this._tmpAmmoVectorA.setValue(e.x,e.y,e.z),this.world.setGravity(this._tmpAmmoVectorA),this.world.getWorldInfo().set_m_gravity(this._tmpAmmoVectorA)},e.prototype.setTimeStep=function(e){this._timeStep=e},e.prototype.setFixedTimeStep=function(e){this._fixedTimeStep=e},e.prototype.setMaxSteps=function(e){this._maxSteps=e},e.prototype.getTimeStep=function(){return this._timeStep},e.prototype._isImpostorInContact=function(e){return this._tmpContactCallbackResult=!1,this.world.contactTest(e.physicsBody,this._tmpAmmoConcreteContactResultCallback),this._tmpContactCallbackResult},e.prototype._isImpostorPairInContact=function(e,t){return this._tmpContactCallbackResult=!1,this.world.contactPairTest(e.physicsBody,t.physicsBody,this._tmpAmmoConcreteContactResultCallback),this._tmpContactCallbackResult},e.prototype._stepSimulation=function(e,t,i){if(void 0===e&&(e=1/60),void 0===t&&(t=10),void 0===i&&(i=1/60),0==t)this.world.stepSimulation(e,0);else for(;t>0&&e>0;)e-i0&&this._isImpostorInContact(a))for(var c=0,l=a._onPhysicsCollideCallbacks;c3?3:a;var c=(new Ammo.btSoftBodyHelpers).CreateRope(this.world.getWorldInfo(),this._tmpAmmoVectorA,this._tmpAmmoVectorB,i-1,a);return c.get_m_cfg().set_collisions(17),c},e.prototype._addHullVerts=function(e,t,i){var n=this,r=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){var s=i.getIndices();s||(s=[]);var a=i.getVerticesData(Oi.b.PositionKind);a||(a=[]),i.computeWorldMatrix(!1);for(var c=s.length/3,l=0;l0){if(e.type!=ts.a.NoImpostor){var l=this._createShape(e,!0);l&&(this._tmpAmmoTransform.getOrigin().setValue(0,0,0),this._tmpAmmoQuaternion.setValue(0,0,0,1),this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion),n.addChildShape(this._tmpAmmoTransform,l))}return n}Ammo.destroy(n),n=null}switch(e.type){case ts.a.SphereImpostor:n=new Ammo.btSphereShape(s.x/2);break;case ts.a.CylinderImpostor:this._tmpAmmoVectorA.setValue(s.x/2,s.y/2,s.z/2),n=new Ammo.btCylinderShape(this._tmpAmmoVectorA);break;case ts.a.PlaneImpostor:case ts.a.BoxImpostor:this._tmpAmmoVectorA.setValue(s.x/2,s.y/2,s.z/2),n=new Ammo.btBoxShape(this._tmpAmmoVectorA);break;case ts.a.MeshImpostor:if(0==e.getParam("mass")){var u=new Ammo.btTriangleMesh;e._pluginData.toDispose.push(u);var h=this._addMeshVerts(u,r,r);n=0==h?new Ammo.btCompoundShape:new Ammo.btBvhTriangleMeshShape(u);break}case ts.a.ConvexHullImpostor:var d=new Ammo.btConvexHullShape;0==(h=this._addHullVerts(d,r,r))?(e._pluginData.toDispose.push(d),n=new Ammo.btCompoundShape):n=d;break;case ts.a.NoImpostor:n=new Ammo.btSphereShape(s.x/2);break;case ts.a.SoftbodyImpostor:n=this._createSoftbody(e);break;case ts.a.ClothImpostor:n=this._createCloth(e);break;case ts.a.RopeImpostor:n=this._createRope(e);break;default:p.a.Warn("The impostor type is not currently supported by the ammo plugin.")}return n},e.prototype.setTransformationFromPhysicsBody=function(e){e.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform),e.object.position.set(this._tmpAmmoTransform.getOrigin().x(),this._tmpAmmoTransform.getOrigin().y(),this._tmpAmmoTransform.getOrigin().z()),e.object.rotationQuaternion?e.object.rotationQuaternion.set(this._tmpAmmoTransform.getRotation().x(),this._tmpAmmoTransform.getRotation().y(),this._tmpAmmoTransform.getRotation().z(),this._tmpAmmoTransform.getRotation().w()):e.object.rotation&&(this._tmpQuaternion.set(this._tmpAmmoTransform.getRotation().x(),this._tmpAmmoTransform.getRotation().y(),this._tmpAmmoTransform.getRotation().z(),this._tmpAmmoTransform.getRotation().w()),this._tmpQuaternion.toEulerAnglesToRef(e.object.rotation))},e.prototype.setPhysicsBodyTransformation=function(e,t,i){var n=e.physicsBody.getWorldTransform();if(n.getOrigin().x()!=t.x||n.getOrigin().y()!=t.y||n.getOrigin().z()!=t.z||n.getRotation().x()!=i.x||n.getRotation().y()!=i.y||n.getRotation().z()!=i.z||n.getRotation().w()!=i.w)if(this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),n.setOrigin(this._tmpAmmoVectorA),this._tmpAmmoQuaternion.setValue(i.x,i.y,i.z,i.w),n.setRotation(this._tmpAmmoQuaternion),e.physicsBody.setWorldTransform(n),0==e.mass){var r=e.physicsBody.getMotionState();r&&r.setWorldTransform(n)}else e.physicsBody.activate()},e.prototype.isSupported=function(){return void 0!==this.bjsAMMO},e.prototype.setLinearVelocity=function(e,t){this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),e.soft?e.physicsBody.linearVelocity(this._tmpAmmoVectorA):e.physicsBody.setLinearVelocity(this._tmpAmmoVectorA)},e.prototype.setAngularVelocity=function(e,t){this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),e.soft?e.physicsBody.angularVelocity(this._tmpAmmoVectorA):e.physicsBody.setAngularVelocity(this._tmpAmmoVectorA)},e.prototype.getLinearVelocity=function(e){if(e.soft)var t=e.physicsBody.linearVelocity();else t=e.physicsBody.getLinearVelocity();if(!t)return null;var i=new o.x(t.x(),t.y(),t.z());return Ammo.destroy(t),i},e.prototype.getAngularVelocity=function(e){if(e.soft)var t=e.physicsBody.angularVelocity();else t=e.physicsBody.getAngularVelocity();if(!t)return null;var i=new o.x(t.x(),t.y(),t.z());return Ammo.destroy(t),i},e.prototype.setBodyMass=function(e,t){e.soft?e.physicsBody.setTotalMass(t,!1):e.physicsBody.setMassProps(t),e._pluginData.mass=t},e.prototype.getBodyMass=function(e){return e._pluginData.mass||0},e.prototype.getBodyFriction=function(e){return e._pluginData.friction||0},e.prototype.setBodyFriction=function(e,t){e.soft?e.physicsBody.get_m_cfg().set_kDF(t):e.physicsBody.setFriction(t),e._pluginData.friction=t},e.prototype.getBodyRestitution=function(e){return e._pluginData.restitution||0},e.prototype.setBodyRestitution=function(e,t){e.physicsBody.setRestitution(t),e._pluginData.restitution=t},e.prototype.getBodyPressure=function(e){return e.soft?e._pluginData.pressure||0:(p.a.Warn("Pressure is not a property of a rigid body"),0)},e.prototype.setBodyPressure=function(e,t){e.soft?e.type===ts.a.SoftbodyImpostor?(e.physicsBody.get_m_cfg().set_kPR(t),e._pluginData.pressure=t):(e.physicsBody.get_m_cfg().set_kPR(0),e._pluginData.pressure=0):p.a.Warn("Pressure can only be applied to a softbody")},e.prototype.getBodyStiffness=function(e){return e.soft?e._pluginData.stiffness||0:(p.a.Warn("Stiffness is not a property of a rigid body"),0)},e.prototype.setBodyStiffness=function(e,t){e.soft?(t=(t=t<0?0:t)>1?1:t,e.physicsBody.get_m_materials().at(0).set_m_kLST(t),e._pluginData.stiffness=t):p.a.Warn("Stiffness cannot be applied to a rigid body")},e.prototype.getBodyVelocityIterations=function(e){return e.soft?e._pluginData.velocityIterations||0:(p.a.Warn("Velocity iterations is not a property of a rigid body"),0)},e.prototype.setBodyVelocityIterations=function(e,t){e.soft?(t=t<0?0:t,e.physicsBody.get_m_cfg().set_viterations(t),e._pluginData.velocityIterations=t):p.a.Warn("Velocity iterations cannot be applied to a rigid body")},e.prototype.getBodyPositionIterations=function(e){return e.soft?e._pluginData.positionIterations||0:(p.a.Warn("Position iterations is not a property of a rigid body"),0)},e.prototype.setBodyPositionIterations=function(e,t){e.soft?(t=t<0?0:t,e.physicsBody.get_m_cfg().set_piterations(t),e._pluginData.positionIterations=t):p.a.Warn("Position iterations cannot be applied to a rigid body")},e.prototype.appendAnchor=function(e,t,i,n,r,o){void 0===r&&(r=1),void 0===o&&(o=!1);var s=e.segments,a=Math.round((s-1)*i)+s*(s-1-Math.round((s-1)*n));e.physicsBody.appendAnchor(a,t.physicsBody,o,r)},e.prototype.appendHook=function(e,t,i,n,r){void 0===n&&(n=1),void 0===r&&(r=!1);var o=Math.round(e.segments*i);e.physicsBody.appendAnchor(o,t.physicsBody,r,n)},e.prototype.sleepBody=function(e){p.a.Warn("sleepBody is not currently supported by the Ammo physics plugin")},e.prototype.wakeUpBody=function(e){e.physicsBody.activate()},e.prototype.updateDistanceJoint=function(e,t,i){p.a.Warn("updateDistanceJoint is not currently supported by the Ammo physics plugin")},e.prototype.setMotor=function(e,t,i,n){e.physicsJoint.enableAngularMotor(!0,t,i)},e.prototype.setLimit=function(e,t,i){p.a.Warn("setLimit is not currently supported by the Ammo physics plugin")},e.prototype.syncMeshWithImpostor=function(e,t){t.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform),e.position.x=this._tmpAmmoTransform.getOrigin().x(),e.position.y=this._tmpAmmoTransform.getOrigin().y(),e.position.z=this._tmpAmmoTransform.getOrigin().z(),e.rotationQuaternion&&(e.rotationQuaternion.x=this._tmpAmmoTransform.getRotation().x(),e.rotationQuaternion.y=this._tmpAmmoTransform.getRotation().y(),e.rotationQuaternion.z=this._tmpAmmoTransform.getRotation().z(),e.rotationQuaternion.w=this._tmpAmmoTransform.getRotation().w())},e.prototype.getRadius=function(e){return e.getObjectExtendSize().x/2},e.prototype.getBoxSizeToRef=function(e,t){var i=e.getObjectExtendSize();t.x=i.x,t.y=i.y,t.z=i.z},e.prototype.dispose=function(){Ammo.destroy(this.world),Ammo.destroy(this._solver),Ammo.destroy(this._overlappingPairCache),Ammo.destroy(this._dispatcher),Ammo.destroy(this._collisionConfiguration),Ammo.destroy(this._tmpAmmoVectorA),Ammo.destroy(this._tmpAmmoVectorB),Ammo.destroy(this._tmpAmmoVectorC),Ammo.destroy(this._tmpAmmoTransform),Ammo.destroy(this._tmpAmmoQuaternion),Ammo.destroy(this._tmpAmmoConcreteContactResultCallback),this.world=null},e.prototype.raycast=function(e,t){this._tmpAmmoVectorRCA=new this.bjsAMMO.btVector3(e.x,e.y,e.z),this._tmpAmmoVectorRCB=new this.bjsAMMO.btVector3(t.x,t.y,t.z);var i=new this.bjsAMMO.ClosestRayResultCallback(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB);return this.world.rayTest(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB,i),this._raycastResult.reset(e,t),i.hasHit()&&(this._raycastResult.setHitData({x:i.get_m_hitNormalWorld().x(),y:i.get_m_hitNormalWorld().y(),z:i.get_m_hitNormalWorld().z()},{x:i.get_m_hitPointWorld().x(),y:i.get_m_hitPointWorld().y(),z:i.get_m_hitPointWorld().z()}),this._raycastResult.calculateHitDistance()),Ammo.destroy(i),Ammo.destroy(this._tmpAmmoVectorRCA),Ammo.destroy(this._tmpAmmoVectorRCB),this._raycastResult},e.DISABLE_COLLISION_FLAG=4,e.KINEMATIC_FLAG=2,e.DISABLE_DEACTIVATION_FLAG=4,e}();n.a.prototype.removeReflectionProbe=function(e){if(!this.reflectionProbes)return-1;var t=this.reflectionProbes.indexOf(e);return-1!==t&&this.reflectionProbes.splice(t,1),t},n.a.prototype.addReflectionProbe=function(e){this.reflectionProbes||(this.reflectionProbes=[]),this.reflectionProbes.push(e)};var us=function(){function e(e,t,i,n,r){var s=this;void 0===n&&(n=!0),void 0===r&&(r=!1),this.name=e,this._viewMatrix=o.j.Identity(),this._target=o.x.Zero(),this._add=o.x.Zero(),this._invertYAxis=!1,this.position=o.x.Zero(),this._scene=i,this._scene.reflectionProbes||(this._scene.reflectionProbes=new Array),this._scene.reflectionProbes.push(this),this._renderTargetTexture=new _i(e,t,i,n,!0,r?_.a.TEXTURETYPE_FLOAT:_.a.TEXTURETYPE_UNSIGNED_INT,!0),this._renderTargetTexture.onBeforeRenderObservable.add(function(e){switch(e){case 0:s._add.copyFromFloats(1,0,0);break;case 1:s._add.copyFromFloats(-1,0,0);break;case 2:s._add.copyFromFloats(0,s._invertYAxis?1:-1,0);break;case 3:s._add.copyFromFloats(0,s._invertYAxis?-1:1,0);break;case 4:s._add.copyFromFloats(0,0,1);break;case 5:s._add.copyFromFloats(0,0,-1)}s._attachedMesh&&s.position.copyFrom(s._attachedMesh.getAbsolutePosition()),s.position.addToRef(s._add,s._target),o.j.LookAtLHToRef(s.position,s._target,o.x.Up(),s._viewMatrix),i.activeCamera&&(s._projectionMatrix=o.j.PerspectiveFovLH(Math.PI/2,1,i.activeCamera.minZ,i.activeCamera.maxZ),i.setTransformMatrix(s._viewMatrix,s._projectionMatrix)),i._forcedViewPosition=s.position}),this._renderTargetTexture.onAfterUnbindObservable.add(function(){i._forcedViewPosition=null,i.updateTransformMatrix(!0)})}return Object.defineProperty(e.prototype,"samples",{get:function(){return this._renderTargetTexture.samples},set:function(e){this._renderTargetTexture.samples=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"refreshRate",{get:function(){return this._renderTargetTexture.refreshRate},set:function(e){this._renderTargetTexture.refreshRate=e},enumerable:!0,configurable:!0}),e.prototype.getScene=function(){return this._scene},Object.defineProperty(e.prototype,"cubeTexture",{get:function(){return this._renderTargetTexture},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"renderList",{get:function(){return this._renderTargetTexture.renderList},enumerable:!0,configurable:!0}),e.prototype.attachToMesh=function(e){this._attachedMesh=e},e.prototype.setRenderingAutoClearDepthStencil=function(e,t){this._renderTargetTexture.setRenderingAutoClearDepthStencil(e,t)},e.prototype.dispose=function(){var e=this._scene.reflectionProbes.indexOf(this);-1!==e&&this._scene.reflectionProbes.splice(e,1),this._renderTargetTexture&&(this._renderTargetTexture.dispose(),this._renderTargetTexture=null)},e.prototype.toString=function(e){var t="Name: "+this.name;return e&&(t+=", position: "+this.position.toString(),this._attachedMesh&&(t+=", attached mesh: "+this._attachedMesh.name)),t},e.prototype.getClassName=function(){return"ReflectionProbe"},e.prototype.serialize=function(){var e=L.a.Serialize(this,this._renderTargetTexture.serialize());return e.isReflectionProbe=!0,e},e.Parse=function(t,i,n){var r=null;if(i.reflectionProbes)for(var o=0;o0){var n=t._waitingData.lods.ids,r=i.isEnabled(!1);if(t._waitingData.lods.distances){var o=t._waitingData.lods.distances;if(o.length>=n.length){var s=o.length>n.length?o[o.length-1]:0;i.setEnabled(!1);for(var a=0;a0&&i.addLODLevel(s,null),!0===r&&i.setEnabled(!0)}else ye.h.Warn("Invalid level of detail distances for "+t.name)}}t._waitingData.lods=null}},_s=function(e,t,i,r,o){void 0===o&&(o=!1);var a=new _e(e),c="importScene has failed JSON parse";try{var l=JSON.parse(t);c="";var u,h,d=Un.loggingLevel===Un.DETAILED_LOGGING;if(void 0!==l.environmentTexture&&null!==l.environmentTexture){var f=void 0===l.isPBR||l.isPBR;if(l.environmentTextureType&&"BABYLON.HDRCubeTexture"===l.environmentTextureType){var _=l.environmentTextureSize?l.environmentTextureSize:128,m=new Jo((l.environmentTexture.match(/https?:\/\//g)?"":i)+l.environmentTexture,e,_,!0,!f);l.environmentTextureRotationY&&(m.rotationY=l.environmentTextureRotationY),e.environmentTexture=m}else if(ye.h.EndsWith(l.environmentTexture,".env")){var g=new Tr((l.environmentTexture.match(/https?:\/\//g)?"":i)+l.environmentTexture,e);l.environmentTextureRotationY&&(g.rotationY=l.environmentTextureRotationY),e.environmentTexture=g}else{var v=Tr.CreateFromPrefilteredData((l.environmentTexture.match(/https?:\/\//g)?"":i)+l.environmentTexture,e);l.environmentTextureRotationY&&(v.rotationY=l.environmentTextureRotationY),e.environmentTexture=v}if(!0===l.createDefaultSkybox){var y=void 0!==e.activeCamera&&null!==e.activeCamera?(e.activeCamera.maxZ-e.activeCamera.minZ)/2:1e3,b=l.skyboxBlurLevel||0;e.createDefaultSkybox(e.environmentTexture,f,y,b)}a.environmentTexture=e.environmentTexture}if(void 0!==l.lights&&null!==l.lights)for(u=0,h=l.lights.length;u0){for(var te=0;te0){for(var ne=0;ne-1&&void 0!==u.skeletons&&null!==u.skeletons)if(!1===g.indexOf(y.skeletonId)>-1)for(var O=0,I=u.skeletons.length;O1,n.wrapU=_.a.TEXTURE_CLAMP_ADDRESSMODE,n.wrapV=_.a.TEXTURE_CLAMP_ADDRESSMODE,n.wrapR=_.a.TEXTURE_CLAMP_ADDRESSMODE,n.anisotropicFilteringLevel=1,n._texture=n._getFromCache(t,!0),n._texture||(i.useDelayedTextureLoading?n.delayLoadState=_.a.DELAYLOADSTATE_NOTLOADED:n.loadTexture()),n):n}return l.d(t,e),t.prototype.getTextureMatrix=function(){return this._textureMatrix},t.prototype.load3dlTexture=function(){var e,i=this._engine;e=1===i.webGLVersion?i.createRawTexture(null,1,1,_.a.TEXTUREFORMAT_RGBA,!1,!1,_.a.TEXTURE_BILINEAR_SAMPLINGMODE):i.createRawTexture3D(null,1,1,1,_.a.TEXTUREFORMAT_RGBA,!1,!1,_.a.TEXTURE_BILINEAR_SAMPLINGMODE),this._texture=e;var n=function(n){if("string"==typeof n){for(var r,o=null,s=null,a=n.split("\n"),c=0,l=0,u=0,h=0,d=0,f=0;f0&&(f+1)%4==0)o[f]=255;else{var b=s[f];o[f]=b/d*255}e.is3D?(e.updateSize(c,c,c),i.updateRawTexture3D(e,o,_.a.TEXTUREFORMAT_RGBA,!1)):(e.updateSize(c*c,c),i.updateRawTexture(e,o,_.a.TEXTUREFORMAT_RGBA,!1))}},r=this.getScene();return r?r._loadFile(this.url,n):this._engine._loadFile(this.url,n),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());return e.level=this.level,e},t.prototype.delayLoad=function(){this.delayLoadState===_.a.DELAYLOADSTATE_NOTLOADED&&(this.delayLoadState=_.a.DELAYLOADSTATE_LOADED,this._texture=this._getFromCache(this.url,!0),this._texture||this.loadTexture())},t.Parse=function(e,i){var n=null;return e.name&&!e.isRenderTarget&&((n=new t(e.name,i)).name=e.name,n.level=e.level),n},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}(vn.a);s.a.RegisteredTypes["BABYLON.ColorGradingTexture"]=Es;var xs=function(e){function t(t,i,n,r,o,s,a){void 0===r&&(r=!1),void 0===o&&(o=!0),void 0===s&&(s=null),void 0===a&&(a=null);var c=e.call(this,i)||this;if(c._onLoad=null,c._onError=null,c.coordinatesMode=Ge.a.CUBIC_MODE,!t)throw new Error("Image url is not set");return c.name=t,c.url=t,c._size=n,c._noMipmap=r,c.gammaSpace=o,c._onLoad=s,c._onError=a,c.hasAlpha=!1,c.isCube=!0,c._texture=c._getFromCache(t,c._noMipmap),c._texture?s&&(c._texture.isReady?ye.h.SetImmediate(function(){return s()}):c._texture.onLoadedObservable.add(s)):i.useDelayedTextureLoading?c.delayLoadState=me.b.DELAYLOADSTATE_NOTLOADED:c.loadImage(c.loadTexture.bind(c),c._onError),c}return l.d(t,e),t.prototype.loadImage=function(e,t){var i=this,n=document.createElement("canvas"),r=new Image;r.addEventListener("load",function(){i._width=r.width,i._height=r.height,n.width=i._width,n.height=i._height;var t=n.getContext("2d");t.drawImage(r,0,0);var o=t.getImageData(0,0,r.width,r.height);i._buffer=o.data.buffer,n.remove(),e()}),r.addEventListener("error",function(e){t&&t(i.getClassName()+" could not be loaded",e)}),r.src=this.url},t.prototype.loadTexture=function(){var e=this,i=this.getScene();i&&(this._texture=i.getEngine().createRawCubeTextureFromUrl(this.url,i,this._size,me.b.TEXTUREFORMAT_RGB,i.getEngine().getCaps().textureFloat?me.b.TEXTURETYPE_FLOAT:me.b.TEXTURETYPE_UNSIGNED_INTEGER,this._noMipmap,function(){for(var i=e.getFloat32ArrayFromArrayBuffer(e._buffer),n=qo.ConvertPanoramaToCubemap(i,e._width,e._height,e._size),r=[],o=0;o<6;o++){var s=n[t._FacesMapping[o]];r.push(s)}return r},null,this._onLoad,this._onError))},t.prototype.getFloat32ArrayFromArrayBuffer=function(e){for(var t=new DataView(e),i=new Float32Array(3*e.byteLength/4),n=0,r=0;ri.length)p.a.Error("Unable to load TGA file - Not enough data");else{n+=r.id_length;var o,s=!1,a=!1,c=!1;switch(r.image_type){case e._TYPE_RLE_INDEXED:s=!0;case e._TYPE_INDEXED:a=!0;break;case e._TYPE_RLE_RGB:s=!0;case e._TYPE_RGB:break;case e._TYPE_RLE_GREY:s=!0;case e._TYPE_GREY:c=!0}var l,u,h,d,f,_,m,g=r.pixel_size>>3,v=r.width*r.height*g;if(a&&(l=i.subarray(n,n+=r.colormap_length*(r.colormap_size>>3))),s){var y,b,T;o=new Uint8Array(v);for(var E=0,x=new Uint8Array(g);n>e._ORIGIN_SHIFT){default:case e._ORIGIN_UL:u=0,d=1,m=r.width,h=0,f=1,_=r.height;break;case e._ORIGIN_BL:u=0,d=1,m=r.width,h=r.height-1,f=-1,_=-1;break;case e._ORIGIN_UR:u=r.width-1,d=-1,m=-1,h=0,f=1,_=r.height;break;case e._ORIGIN_BR:u=r.width-1,d=-1,m=-1,h=r.height-1,f=-1,_=-1}var A=e["_getImageData"+(c?"Grey":"")+r.pixel_size+"bits"](r,l,o,h,f,_,u,d,m);t.getEngine()._uploadDataToTextureDirectly(t,A)}}},e._getImageData8bits=function(e,t,i,n,r,o,s,a,c){var l,u,h,d=i,f=t,p=e.width,_=e.height,m=0,g=new Uint8Array(p*_*4);for(h=n;h!==o;h+=r)for(u=s;u!==c;u+=a,m++)l=d[m],g[4*(u+p*h)+3]=255,g[4*(u+p*h)+2]=f[3*l+0],g[4*(u+p*h)+1]=f[3*l+1],g[4*(u+p*h)+0]=f[3*l+2];return g},e._getImageData16bits=function(e,t,i,n,r,o,s,a,c){var l,u,h,d=i,f=e.width,p=e.height,_=0,m=new Uint8Array(f*p*4);for(h=n;h!==o;h+=r)for(u=s;u!==c;u+=a,_+=2){var g=255*((31744&(l=d[_+0]+(d[_+1]<<8)))>>10)/31|0,v=255*((992&l)>>5)/31|0,y=255*(31&l)/31|0;m[4*(u+f*h)+0]=g,m[4*(u+f*h)+1]=v,m[4*(u+f*h)+2]=y,m[4*(u+f*h)+3]=32768&l?0:255}return m},e._getImageData24bits=function(e,t,i,n,r,o,s,a,c){var l,u,h=i,d=e.width,f=e.height,p=0,_=new Uint8Array(d*f*4);for(u=n;u!==o;u+=r)for(l=s;l!==c;l+=a,p+=3)_[4*(l+d*u)+3]=255,_[4*(l+d*u)+2]=h[p+0],_[4*(l+d*u)+1]=h[p+1],_[4*(l+d*u)+0]=h[p+2];return _},e._getImageData32bits=function(e,t,i,n,r,o,s,a,c){var l,u,h=i,d=e.width,f=e.height,p=0,_=new Uint8Array(d*f*4);for(u=n;u!==o;u+=r)for(l=s;l!==c;l+=a,p+=4)_[4*(l+d*u)+2]=h[p+0],_[4*(l+d*u)+1]=h[p+1],_[4*(l+d*u)+0]=h[p+2],_[4*(l+d*u)+3]=h[p+3];return _},e._getImageDataGrey8bits=function(e,t,i,n,r,o,s,a,c){var l,u,h,d=i,f=e.width,p=e.height,_=0,m=new Uint8Array(f*p*4);for(h=n;h!==o;h+=r)for(u=s;u!==c;u+=a,_++)l=d[_],m[4*(u+f*h)+0]=l,m[4*(u+f*h)+1]=l,m[4*(u+f*h)+2]=l,m[4*(u+f*h)+3]=255;return m},e._getImageDataGrey16bits=function(e,t,i,n,r,o,s,a,c){var l,u,h=i,d=e.width,f=e.height,p=0,_=new Uint8Array(d*f*4);for(u=n;u!==o;u+=r)for(l=s;l!==c;l+=a,p+=2)_[4*(l+d*u)+0]=h[p+0],_[4*(l+d*u)+1]=h[p+0],_[4*(l+d*u)+2]=h[p+0],_[4*(l+d*u)+3]=h[p+1];return _},e._TYPE_INDEXED=1,e._TYPE_RGB=2,e._TYPE_GREY=3,e._TYPE_RLE_INDEXED=9,e._TYPE_RLE_RGB=10,e._TYPE_RLE_GREY=11,e._ORIGIN_MASK=48,e._ORIGIN_SHIFT=4,e._ORIGIN_BL=0,e._ORIGIN_BR=1,e._ORIGIN_UL=2,e._ORIGIN_UR=3,e}(),Ps=function(){function e(){this.supportCascades=!1}return e.prototype.canLoad=function(e,t,i,n,r){return 0===e.indexOf(".tga")},e.prototype.transformUrl=function(e,t){return e},e.prototype.getFallbackTextureUrl=function(e,t){return null},e.prototype.loadCubeData=function(e,t,i,n,r){throw".env not supported in Cube."},e.prototype.loadData=function(e,t,i){var n=new Uint8Array(e),r=As.GetTGAHeader(n);i(r.width,r.height,t.generateMipMaps,!1,function(){As.UploadContent(t,n)})},e}();me.b._TextureLoaders.push(new Ps),me.b.prototype.unBindMultiColorAttachmentFramebuffer=function(e,t,i){void 0===t&&(t=!1),this._currentRenderTarget=null;var n=this._gl;if(e[0]._MSAAFramebuffer){n.bindFramebuffer(n.READ_FRAMEBUFFER,e[0]._MSAAFramebuffer),n.bindFramebuffer(n.DRAW_FRAMEBUFFER,e[0]._framebuffer);var r=e[0]._attachments;r||(r=new Array(e.length),e[0]._attachments=r);for(var o=0;o1?"COLOR_ATTACHMENT"+o:"COLOR_ATTACHMENT"+o+"_WEBGL"],n.readBuffer(r[o]),n.drawBuffers(r),n.blitFramebuffer(0,0,s.width,s.height,0,0,s.width,s.height,n.COLOR_BUFFER_BIT,n.NEAREST)}for(o=0;o1?"COLOR_ATTACHMENT"+o:"COLOR_ATTACHMENT"+o+"_WEBGL"];n.drawBuffers(r)}for(o=0;o1?"COLOR_ATTACHMENT"+y:"COLOR_ATTACHMENT"+y+"_WEBGL"];m.push(x),g.push(A),h.activeTexture(h["TEXTURE"+y]),h.bindTexture(h.TEXTURE_2D,x._webGLTexture),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_MAG_FILTER,E.mag),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_MIN_FILTER,E.min),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_WRAP_S,h.CLAMP_TO_EDGE),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_WRAP_T,h.CLAMP_TO_EDGE),h.texImage2D(h.TEXTURE_2D,0,this._getRGBABufferInternalSizedFormat(T),f,_,0,h.RGBA,this._getWebGLTextureType(T),null),h.framebufferTexture2D(h.DRAW_FRAMEBUFFER,A,h.TEXTURE_2D,x._webGLTexture,0),i&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(h.TEXTURE_2D,null),x._framebuffer=d,x._depthStencilBuffer=v,x.baseWidth=f,x.baseHeight=_,x.width=f,x.height=_,x.isReady=!0,x.samples=1,x.generateMipMaps=i,x.samplingMode=b,x.type=T,x._generateDepthBuffer=n,x._generateStencilBuffer=r,x._attachments=g,this._internalTexturesCache.push(x)}if(o&&this._caps.depthTextureExtension){var P=new ze.a(this,ze.a.DATASOURCE_MULTIRENDERTARGET);h.activeTexture(h.TEXTURE0),h.bindTexture(h.TEXTURE_2D,P._webGLTexture),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_MAG_FILTER,h.NEAREST),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_MIN_FILTER,h.NEAREST),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_WRAP_S,h.CLAMP_TO_EDGE),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_WRAP_T,h.CLAMP_TO_EDGE),h.texImage2D(h.TEXTURE_2D,0,this.webGLVersion<2?h.DEPTH_COMPONENT:h.DEPTH_COMPONENT16,f,_,0,h.DEPTH_COMPONENT,h.UNSIGNED_SHORT,null),h.framebufferTexture2D(h.FRAMEBUFFER,h.DEPTH_ATTACHMENT,h.TEXTURE_2D,P._webGLTexture,0),P._framebuffer=d,P.baseWidth=f,P.baseHeight=_,P.width=f,P.height=_,P.isReady=!0,P.samples=1,P.generateMipMaps=i,P.samplingMode=h.NEAREST,P._generateDepthBuffer=n,P._generateStencilBuffer=r,m.push(P),this._internalTexturesCache.push(P)}return h.drawBuffers(g),h.bindRenderbuffer(h.RENDERBUFFER,null),this._bindUnboundFramebuffer(null),this.resetTextureCache(),m},me.b.prototype.updateMultipleRenderTargetTextureSampleCount=function(e,t){if(this.webGLVersion<2||!e||0==e.length)return 1;if(e[0].samples===t)return t;var i=this._gl;t=Math.min(t,i.getParameter(i.MAX_SAMPLES)),e[0]._depthStencilBuffer&&(i.deleteRenderbuffer(e[0]._depthStencilBuffer),e[0]._depthStencilBuffer=null),e[0]._MSAAFramebuffer&&(i.deleteFramebuffer(e[0]._MSAAFramebuffer),e[0]._MSAAFramebuffer=null);for(var n=0;n1){var r=i.createFramebuffer();if(!r)throw new Error("Unable to create multi sampled framebuffer");this._bindUnboundFramebuffer(r);var o=this._setupFramebufferDepthAttachments(e[0]._generateStencilBuffer,e[0]._generateDepthBuffer,e[0].width,e[0].height,t),s=[];for(n=0;n1?"COLOR_ATTACHMENT"+n:"COLOR_ATTACHMENT"+n+"_WEBGL"],l=i.createRenderbuffer();if(!l)throw new Error("Unable to create multi sampled framebuffer");i.bindRenderbuffer(i.RENDERBUFFER,l),i.renderbufferStorageMultisample(i.RENDERBUFFER,t,this._getRGBAMultiSampleBufferFormat(a.type),a.width,a.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,c,i.RENDERBUFFER,l),a._MSAAFramebuffer=r,a._MSAARenderBuffer=l,a.samples=t,a._depthStencilBuffer=o,i.bindRenderbuffer(i.RENDERBUFFER,null),s.push(c)}i.drawBuffers(s)}else this._bindUnboundFramebuffer(e[0]._framebuffer);return this._bindUnboundFramebuffer(null),t};var Rs=function(e){function t(t,i,n,r,o){var s=this,a=!(!o||!o.generateMipMaps)&&o.generateMipMaps,c=!(!o||!o.generateDepthTexture)&&o.generateDepthTexture,l=!o||void 0===o.doNotChangeAspectRatio||o.doNotChangeAspectRatio;if((s=e.call(this,t,i,r,a,l)||this)._engine=r.getEngine(),s.isSupported){for(var u=[],h=[],d=0;d1||this._engine.getCaps().drawBuffersExtension},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"textures",{get:function(){return this._textures},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"depthTexture",{get:function(){return this._textures[this._textures.length-1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"wrapU",{set:function(e){if(this._textures)for(var t=0;t=0;e--)void 0!==this._internalTextures[e]&&(this._internalTextures[e].dispose(),this._internalTextures.splice(e,1))},t}(_i),Ss=function(){function e(e){this.name=xe.a.NAME_PROCEDURALTEXTURE,this.scene=e,this.scene.proceduralTextures=new Array}return e.prototype.register=function(){this.scene._beforeClearStage.registerStep(xe.a.STEP_BEFORECLEAR_PROCEDURALTEXTURE,this,this._beforeClear)},e.prototype.rebuild=function(){},e.prototype.dispose=function(){},e.prototype._beforeClear=function(){if(this.scene.proceduralTexturesEnabled){ye.h.StartPerformanceCounter("Procedural textures",this.scene.proceduralTextures.length>0);for(var e=0;e0)}},e}(),Cs="\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}";zt.a.ShadersStore.proceduralVertexShader=Cs;var Ms=function(e){function t(t,i,n,o,s,a,c){void 0===s&&(s=null),void 0===a&&(a=!0),void 0===c&&(c=!1);var l=e.call(this,null,o,!a)||this;l.isCube=c,l.isEnabled=!0,l.autoClear=!0,l.onGeneratedObservable=new r.c,l._textures={},l._currentRefreshId=-1,l._refreshRate=1,l._vertexBuffers={},l._uniforms=new Array,l._samplers=new Array,l._floats={},l._ints={},l._floatsArrays={},l._colors3={},l._colors4={},l._vectors2={},l._vectors3={},l._matrices={},l._fallbackTextureUsed=!1,l._cachedDefines="",l._contentUpdateId=-1;var u=(o=l.getScene())._getComponent(xe.a.NAME_PROCEDURALTEXTURE);u||(u=new Ss(o),o._addComponent(u)),o.proceduralTextures.push(l),l._engine=o.getEngine(),l.name=t,l.isRenderTarget=!0,l._size=i,l._generateMipMaps=a,l.setFragment(n),l._fallbackTexture=s,c?(l._texture=l._engine.createRenderTargetCubeTexture(i,{generateMipMaps:a,generateDepthBuffer:!1,generateStencilBuffer:!1}),l.setFloat("face",0)):l._texture=l._engine.createRenderTargetTexture(i,{generateMipMaps:a,generateDepthBuffer:!1,generateStencilBuffer:!1});var h=[];return h.push(1,1),h.push(-1,1),h.push(-1,-1),h.push(1,-1),l._vertexBuffers[Oi.b.PositionKind]=new Oi.b(l._engine,h,Oi.b.PositionKind,!1,!1,2),l._createIndexBuffer(),l}return l.d(t,e),t.prototype.getEffect=function(){return this._effect},t.prototype.getContent=function(){return this._contentData&&this._currentRefreshId==this._contentUpdateId?this._contentData:(this._contentData=this.readPixels(0,0,this._contentData),this._contentUpdateId=this._currentRefreshId,this._contentData)},t.prototype._createIndexBuffer=function(){var e=this._engine,t=[];t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),this._indexBuffer=e.createIndexBuffer(t)},t.prototype._rebuild=function(){var e=this._vertexBuffers[Oi.b.PositionKind];e&&e._rebuild(),this._createIndexBuffer(),this.refreshRate===_i.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=_i.REFRESHRATE_RENDER_ONCE)},t.prototype.reset=function(){void 0!==this._effect&&this._effect.dispose()},t.prototype._getDefines=function(){return""},t.prototype.isReady=function(){var e,t=this,i=this._engine;if(!this._fragment)return!1;if(this._fallbackTextureUsed)return!0;var n=this._getDefines();return!(!this._effect||n!==this._cachedDefines||!this._effect.isReady())||(e=void 0!==this._fragment.fragmentElement?{vertex:"procedural",fragmentElement:this._fragment.fragmentElement}:{vertex:"procedural",fragment:this._fragment},this._cachedDefines=n,this._effect=i.createEffect(e,[Oi.b.PositionKind],this._uniforms,this._samplers,n,void 0,void 0,function(){t.releaseInternalTexture(),t._fallbackTexture&&(t._texture=t._fallbackTexture._texture,t._texture&&t._texture.incrementReferences()),t._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:!0,configurable:!0}),t.prototype._shouldRender=function(){return this.isEnabled&&this.isReady()&&this._texture?!this._fallbackTextureUsed&&(-1===this._currentRefreshId?(this._currentRefreshId=1,!0):this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,!0):(this._currentRefreshId++,!1)):(this._texture&&(this._texture.isReady=!1),!1)},t.prototype.getRenderSize=function(){return this._size},t.prototype.resize=function(e,t){this._fallbackTextureUsed||(this.releaseInternalTexture(),this._texture=this._engine.createRenderTargetTexture(e,t),this._size=e,this._generateMipMaps=t)},t.prototype._checkUniform=function(e){-1===this._uniforms.indexOf(e)&&this._uniforms.push(e)},t.prototype.setTexture=function(e,t){return-1===this._samplers.indexOf(e)&&this._samplers.push(e),this._textures[e]=t,this},t.prototype.setFloat=function(e,t){return this._checkUniform(e),this._floats[e]=t,this},t.prototype.setInt=function(e,t){return this._checkUniform(e),this._ints[e]=t,this},t.prototype.setFloats=function(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this},t.prototype.setColor3=function(e,t){return this._checkUniform(e),this._colors3[e]=t,this},t.prototype.setColor4=function(e,t){return this._checkUniform(e),this._colors4[e]=t,this},t.prototype.setVector2=function(e,t){return this._checkUniform(e),this._vectors2[e]=t,this},t.prototype.setVector3=function(e,t){return this._checkUniform(e),this._vectors3[e]=t,this},t.prototype.setMatrix=function(e,t){return this._checkUniform(e),this._matrices[e]=t,this},t.prototype.render=function(e){var t=this.getScene();if(t){var i=this._engine;for(var n in i.enableEffect(this._effect),i.setState(!1),this._textures)this._effect.setTexture(n,this._textures[n]);for(n in this._ints)this._effect.setInt(n,this._ints[n]);for(n in this._floats)this._effect.setFloat(n,this._floats[n]);for(n in this._floatsArrays)this._effect.setArray(n,this._floatsArrays[n]);for(n in this._colors3)this._effect.setColor3(n,this._colors3[n]);for(n in this._colors4){var r=this._colors4[n];this._effect.setFloat4(n,r.r,r.g,r.b,r.a)}for(n in this._vectors2)this._effect.setVector2(n,this._vectors2[n]);for(n in this._vectors3)this._effect.setVector3(n,this._vectors3[n]);for(n in this._matrices)this._effect.setMatrix(n,this._matrices[n]);if(this._texture){if(this.isCube)for(var o=0;o<6;o++)i.bindFramebuffer(this._texture,o,void 0,void 0,!0),i.bindBuffers(this._vertexBuffers,this._indexBuffer,this._effect),this._effect.setFloat("face",o),this.autoClear&&i.clear(t.clearColor,!0,!1,!1),i.drawElementsType(To.a.TriangleFillMode,0,6),5===o&&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(t.clearColor,!0,!1,!1),i.drawElementsType(To.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(),i=new t(this.name,e.width,this._fragment,this.getScene(),this._fallbackTexture,this._generateMipMaps);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.coordinatesMode=this.coordinatesMode,i},t.prototype.dispose=function(){var t=this.getScene();if(t){var i=t.proceduralTextures.indexOf(this);i>=0&&t.proceduralTextures.splice(i,1);var n=this._vertexBuffers[Oi.b.PositionKind];n&&(n.dispose(),this._vertexBuffers[Oi.b.PositionKind]=null),this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer)&&(this._indexBuffer=null),e.prototype.dispose.call(this)}},l.c([Object(L.c)()],t.prototype,"isEnabled",void 0),l.c([Object(L.c)()],t.prototype,"autoClear",void 0),l.c([Object(L.c)()],t.prototype,"_generateMipMaps",void 0),l.c([Object(L.c)()],t.prototype,"_size",void 0),l.c([Object(L.c)()],t.prototype,"refreshRate",null),t}(Ge.a),Os=i(61),Is=function(e){function t(t,i,n,r,o,s){var a=e.call(this,t,n,null,r,o,s)||this;return a._animate=!0,a._time=0,a._texturePath=i,a._loadJson(i),a.refreshRate=1,a}return l.d(t,e),t.prototype._loadJson=function(e){var t=this,i=function(){p.a.Log("No config file found in "+e+" trying to use ShadersStore or DOM element");try{t.setFragment(t._texturePath)}catch(e){p.a.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture")}},n=e+"/config.json",r=new Os.a;r.open("GET",n),r.addEventListener("load",function(){if(200===r.status||r.responseText&&r.responseText.length>0)try{t._config=JSON.parse(r.response),t.updateShaderUniforms(),t.updateTextures(),t.setFragment(t._texturePath+"/custom"),t._animate=t._config.animate,t.refreshRate=t._config.refreshrate}catch(e){i()}else i()},!1),r.addEventListener("error",function(){i()},!1);try{r.send()}catch(e){p.a.Error("CustomProceduralTexture: Error on XHR send request.")}},t.prototype.isReady=function(){if(!e.prototype.isReady.call(this))return!1;for(var t in this._textures){if(!this._textures[t].isReady())return!1}return!0},t.prototype.render=function(t){var i=this.getScene();this._animate&&i&&(this._time+=.03*i.getAnimationRatio(),this.updateShaderUniforms()),e.prototype.render.call(this,t)},t.prototype.updateTextures=function(){for(var e=0;e[0.."+i.repeatKey+"]\r\n":this.functions[e]="#include<"+e+">\r\n",void(this.sharedData.emitComments&&(this.functions[e]=t+"\r\n"+this.functions[e]));if(this.functions[e]=zt.a.IncludesShadersStore[e],this.sharedData.emitComments&&(this.functions[e]=t+"\r\n"+this.functions[e]),i.removeIfDef&&(this.functions[e]=this.functions[e].replace(/^\s*?#ifdef.+$/gm,""),this.functions[e]=this.functions[e].replace(/^\s*?#endif.*$/gm,""),this.functions[e]=this.functions[e].replace(/^\s*?#else.*$/gm,""),this.functions[e]=this.functions[e].replace(/^\s*?#elif.*$/gm,"")),i.removeAttributes&&(this.functions[e]=this.functions[e].replace(/^\s*?attribute.+$/gm,"")),i.removeUniforms&&(this.functions[e]=this.functions[e].replace(/^\s*?uniform.+$/gm,"")),i.removeVaryings&&(this.functions[e]=this.functions[e].replace(/^\s*?varying.+$/gm,"")),i.replaceStrings)for(var n=0;n-1))return this._optimizers.push(e),this},t.prototype.unregisterOptimizer=function(e){var t=this._optimizers.indexOf(e);if(-1!==t)return this._optimizers.splice(t,1),this},t.prototype.addOutputNode=function(e){if(null===e.target)throw"This node is not meant to be an output node. You may want to explicitly set its target value.";return 0!=(e.target&ws.Vertex)&&this._addVertexOutputNode(e),0!=(e.target&ws.Fragment)&&this._addFragmentOutputNode(e),this},t.prototype.removeOutputNode=function(e){return null===e.target?this:(0!=(e.target&ws.Vertex)&&this._removeVertexOutputNode(e),0!=(e.target&ws.Fragment)&&this._removeFragmentOutputNode(e),this)},t.prototype._addVertexOutputNode=function(e){if(-1===this._vertexOutputNodes.indexOf(e))return e.target=ws.Vertex,this._vertexOutputNodes.push(e),this},t.prototype._removeVertexOutputNode=function(e){var t=this._vertexOutputNodes.indexOf(e);if(-1!==t)return this._vertexOutputNodes.splice(t,1),this},t.prototype._addFragmentOutputNode=function(e){if(-1===this._fragmentOutputNodes.indexOf(e))return e.target=ws.Fragment,this._fragmentOutputNodes.push(e),this},t.prototype._removeFragmentOutputNode=function(e){var t=this._fragmentOutputNodes.indexOf(e);if(-1!==t)return this._fragmentOutputNodes.splice(t,1),this},t.prototype.needAlphaBlending=function(){return this.alpha<1||this._sharedData.hints.needAlphaBlending},t.prototype.needAlphaTesting=function(){return this._sharedData.hints.needAlphaTesting},t.prototype._initializeBlock=function(e,t){e.initialize(t),e.autoConfigure();for(var i=0,n=e.inputs;i0)for(m=0;m0&&(t.compilationString+=this._declareOutput(n,t)+" = "+i.associatedVariableName+".r;\r\n"),r.connectedBlocks.length>0&&(t.compilationString+=this._declareOutput(r,t)+" = "+i.associatedVariableName+".g;\r\n"),o.connectedBlocks.length>0&&(t.compilationString+=this._declareOutput(o,t)+" = "+i.associatedVariableName+".b;\r\n"),s.connectedBlocks.length>0&&(t.compilationString+=this._declareOutput(s,t)+" = "+i.associatedVariableName+".a;\r\n"),this},t}(js),ra=function(e){function t(t){var i=e.call(this,t,ws.Fragment)||this;return i.registerInput("input",Fs.Vector3OrColor3),i.registerOutput("r",Fs.Float),i.registerOutput("g",Fs.Float),i.registerOutput("b",Fs.Float),i}return l.d(t,e),t.prototype.getClassName=function(){return"RGBSplitterBlock"},Object.defineProperty(t.prototype,"input",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this.input,n=this._outputs[0],r=this._outputs[1],o=this._outputs[2];return n.connectedBlocks.length>0&&(t.compilationString+=this._declareOutput(n,t)+" = "+i.associatedVariableName+".r;\r\n"),r.connectedBlocks.length>0&&(t.compilationString+=this._declareOutput(r,t)+" = "+i.associatedVariableName+".g;\r\n"),o.connectedBlocks.length>0&&(t.compilationString+=this._declareOutput(o,t)+" = "+i.associatedVariableName+".b;\r\n"),this},t}(js),oa=function(e){function t(t){var i=e.call(this,t,ws.Fragment)||this;return i.autoConnectTextureMatrix=!0,i.autoSelectUV=!0,i.registerInput("uv",Fs.Vector2),i.registerInput("textureInfo",Fs.Vector2,!0),i.registerInput("transformedUV",Fs.Vector2,!1,ws.Vertex),i.registerInput("texture",Fs.Texture,!1,ws.Fragment),i.registerInput("textureTransform",Fs.Matrix,!0,ws.Vertex),i.registerOutput("color",Fs.Color4),i._inputs[0]._needToEmitVarying=!1,i}return l.d(t,e),t.prototype.getClassName=function(){return"TextureBlock"},Object.defineProperty(t.prototype,"uv",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"textureInfo",{get:function(){return this._inputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"transformedUV",{get:function(){return this._inputs[2]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"texture",{get:function(){return this._inputs[3]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"textureTransform",{get:function(){return this._inputs[4]},enumerable:!0,configurable:!0}),t.prototype.autoConfigure=function(){this.uv.connectedPoint||(this.uv.setAsAttribute(),this.uv.connectTo(this.transformedUV))},t.prototype.initialize=function(e){if(this.texture.value&&this.texture.value.getTextureMatrix){var t=this.texture.value;this.autoConnectTextureMatrix&&(this.textureTransform.valueCallback=function(){return t.getTextureMatrix()}),this.autoSelectUV&&this.uv.setAsAttribute("uv"+(t.coordinatesIndex?t.coordinatesIndex+1:""))}},t.prototype.prepareDefines=function(e,t,i){if(this.texture.value&&this.texture.value.getTextureMatrix){var n=this.uv,r=this.textureTransform,o=null!=r.connectedPoint||r.isUniform,s=this.texture.value,a=("vMain"+n.associatedVariableName).toUpperCase();o&&!s.getTextureMatrix().isIdentityAs3x2()?(i.setValue(this._defineName,!0),i.setValue(a,!1)):(i.setValue(this._defineName,!1),i.setValue(a,!0))}},t.prototype.isReady=function(){var e=this.texture.value;return!(e&&!e.isReadyOrNotBlocking())},t.prototype._injectVertexCode=function(e){var t=this.uv,i=this.transformedUV,n=this.textureTransform,r=null!=n.connectedPoint||n.isUniform;this._defineName=e._getFreeDefineName("UVTRANSFORM");var o="vMain"+t.associatedVariableName;i.associatedVariableName=e._getFreeVariableName(i.name),e._emitVaryings(i,this._defineName,!0),e._emitVaryings(i,o.toUpperCase(),!0,!1,o),n.associatedVariableName=e._getFreeVariableName(n.name),e._emitUniformOrAttributes(n,this._defineName),r?(e.sharedData.emitComments&&(e.compilationString+="\r\n//"+this.name+"\r\n"),e.compilationString+="#ifdef "+this._defineName+"\r\n",e.compilationString+=i.associatedVariableName+" = vec2("+n.associatedVariableName+" * vec4("+t.associatedVariableName+", 1.0, 0.0));\r\n",e.compilationString+="#else\r\n",e.compilationString+=o+" = "+t.associatedVariableName+";\r\n",e.compilationString+="#endif\r\n"):e.compilationString+=o+" = "+t.associatedVariableName+";\r\n"},t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t),t.sharedData.blockingBlocks.push(this),this._injectVertexCode(t._vertexState),t.sharedData.blocksWithDefines.push(this);var i=this.uv,n=this.transformedUV,r=this.textureInfo,o=this.texture,s=this._outputs[0],a=null!=r.connectedPoint||r.isUniform?" * "+r.associatedVariableName+".y":"";return t.compilationString+="#ifdef "+this._defineName+"\r\n",t.compilationString+="vec4 "+s.associatedVariableName+" = texture2D("+o.associatedVariableName+", "+n.associatedVariableName+")"+a+";\r\n",t.compilationString+="#else\r\n",t.compilationString+="vec4 "+s.associatedVariableName+" = texture2D("+o.associatedVariableName+", vMain"+i.associatedVariableName+")"+a+";\r\n",t.compilationString+="#endif\r\n",this},t}(js),sa=function(e){function t(t){var i=e.call(this,t,ws.Fragment)||this;return i.registerInput("color",Fs.Color3OrColor4),i.registerOutput("output",Fs.Color4),i}return l.d(t,e),t.prototype.getClassName=function(){return"ImageProcessingBlock"},Object.defineProperty(t.prototype,"color",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),t.prototype.initialize=function(e){e._excludeVariableName("exposureLinear"),e._excludeVariableName("contrast"),e._excludeVariableName("vInverseScreenSize"),e._excludeVariableName("vignetteSettings1"),e._excludeVariableName("vignetteSettings2"),e._excludeVariableName("vCameraColorCurveNegative"),e._excludeVariableName("vCameraColorCurveNeutral"),e._excludeVariableName("vCameraColorCurvePositive"),e._excludeVariableName("txColorTransform"),e._excludeVariableName("colorTransformSettings")},t.prototype.isReady=function(e,t,i){return!(i._areImageProcessingDirty&&t.imageProcessingConfiguration&&!t.imageProcessingConfiguration.isReady())},t.prototype.prepareDefines=function(e,t,i){i._areImageProcessingDirty&&t.imageProcessingConfiguration&&t.imageProcessingConfiguration.prepareDefines(i)},t.prototype.bind=function(e,t,i){i&&t.imageProcessingConfiguration&&t.imageProcessingConfiguration.bind(e)},t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t),t.sharedData.blocksWithDefines.push(this),t.sharedData.blockingBlocks.push(this),t.sharedData.bindableBlocks.push(this),t.uniforms.push("exposureLinear"),t.uniforms.push("contrast"),t.uniforms.push("vInverseScreenSize"),t.uniforms.push("vignetteSettings1"),t.uniforms.push("vignetteSettings2"),t.uniforms.push("vCameraColorCurveNegative"),t.uniforms.push("vCameraColorCurveNeutral"),t.uniforms.push("vCameraColorCurvePositive"),t.uniforms.push("txColorTransform"),t.uniforms.push("colorTransformSettings");var i=this.color,n=this._outputs[0],r="//"+this.name;return t._emitFunctionFromInclude("helperFunctions",r),t._emitFunctionFromInclude("imageProcessingDeclaration",r),t._emitFunctionFromInclude("imageProcessingFunctions",r),i.connectedPoint.type===Fs.Color4?t.compilationString+=this._declareOutput(n,t)+" = "+i.associatedVariableName+";\r\n":t.compilationString+=this._declareOutput(n,t)+" = vec4("+i.associatedVariableName+", 1.0);\r\n",t.compilationString+="#ifdef IMAGEPROCESSINGPOSTPROCESS\r\n",t.compilationString+=n.associatedVariableName+".rgb = toLinearSpace("+i.associatedVariableName+".rgb);\r\n",t.compilationString+="#else\r\n",t.compilationString+="#ifdef IMAGEPROCESSING\r\n",t.compilationString+=n.associatedVariableName+".rgb = toLinearSpace("+i.associatedVariableName+".rgb);\r\n",t.compilationString+=n.associatedVariableName+" = applyImageProcessing("+n.associatedVariableName+");\r\n",t.compilationString+="#endif\r\n",t.compilationString+="#endif\r\n",this},t}(js),aa=function(e){function t(t){var i=e.call(this,t,ws.VertexAndFragment,!0)||this;return i.registerInput("worldPosition",Fs.Vector4,!1,ws.Vertex),i.registerInput("view",Fs.Matrix,!1,ws.Vertex),i.registerOutput("vFogDistance",Fs.Vector3,ws.Vertex),i.registerInput("color",Fs.Color3OrColor4,!1,ws.Fragment),i.registerInput("fogColor",Fs.Color3,!1,ws.Fragment),i.registerInput("fogParameters",Fs.Vector4,!1,ws.Fragment),i.registerOutput("output",Fs.Color3,ws.Fragment),i}return l.d(t,e),t.prototype.getClassName=function(){return"FogBlock"},Object.defineProperty(t.prototype,"worldPosition",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"view",{get:function(){return this._inputs[1]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"color",{get:function(){return this._inputs[2]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fogColor",{get:function(){return this._inputs[3]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"fogParameters",{get:function(){return this._inputs[4]},enumerable:!0,configurable:!0}),t.prototype.autoConfigure=function(){this.view.connectedPoint||this.view.setAsWellKnownValue(Ns.View),this.fogColor.connectedPoint||this.fogColor.setAsWellKnownValue(Ns.Automatic),this.fogParameters.connectedPoint||this.fogParameters.setAsWellKnownValue(Ns.Automatic),this._outputs[0].isVarying=!0},t.prototype.prepareDefines=function(e,t,i){var n=e.getScene();i.setValue("FOG",t.fogEnabled&&Er.a.GetFogState(e,n))},t.prototype.bind=function(e,t,i){if(i){var n=i.getScene();e.setColor3("fogColor",n.fogColor),e.setFloat4("fogParameters",n.fogMode,n.fogStart,n.fogEnd,n.fogDensity)}},t.prototype._buildBlock=function(t){if(e.prototype._buildBlock.call(this,t),t.sharedData.blocksWithDefines.push(this),t.target===ws.Fragment){t._emitFunctionFromInclude("fogFragmentDeclaration","//"+this.name,{removeUniforms:!0,removeVaryings:!0,removeIfDef:!1,replaceStrings:[{search:/float CalcFogFactor\(\)/,replace:"float CalcFogFactor(vec3 vFogDistance, vec4 vFogInfos)"}]});var i=t._getFreeVariableName("fog"),n=this.color,r=this.fogColor,o=this.fogParameters,s=this._outputs[1],a=this._outputs[0];t.compilationString+="#ifdef FOG\r\n",t.compilationString+="float "+i+" = CalcFogFactor("+a.associatedVariableName+", "+o.associatedVariableName+");\r\n",t.compilationString+=this._declareOutput(s,t)+" = "+i+" * "+n.associatedVariableName+".rgb + (1.0 - "+i+") * "+r.associatedVariableName+";\r\n",t.compilationString+="#else\r\n"+this._declareOutput(s,t)+" = "+n.associatedVariableName+".rgb;\r\n",t.compilationString+="#endif\r\n"}else{var c=this.worldPosition,l=this.view;a=this._outputs[0];t.compilationString+=this._declareOutput(a,t)+" = ("+l.associatedVariableName+" * "+c.associatedVariableName+").xyz;\r\n"}return this},t}(js),ca=function(e){function t(t){var i=e.call(this,t)||this;return i.registerInput("left",Fs.Vector4OrColor4),i.registerInput("right",Fs.Vector4OrColor4),i.registerOutput("output",Fs.Vector4OrColor4),i}return l.d(t,e),t.prototype.getClassName=function(){return"MultiplyBlock"},Object.defineProperty(t.prototype,"left",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"right",{get:function(){return this._inputs[1]},enumerable:!0,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=this._declareOutput(i,t)+" = "+this.left.associatedVariableName+" * "+this.right.associatedVariableName+";\r\n",this},t}(js),la=function(e){function t(t){var i=e.call(this,t)||this;return i.registerInput("left",Fs.Vector4OrColor4),i.registerInput("right",Fs.Vector4OrColor4),i.registerOutput("output",Fs.Vector4OrColor4),i}return l.d(t,e),t.prototype.getClassName=function(){return"AddBlock"},Object.defineProperty(t.prototype,"left",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"right",{get:function(){return this._inputs[1]},enumerable:!0,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=this._declareOutput(i,t)+" = "+this.left.associatedVariableName+" + "+this.right.associatedVariableName+";\r\n",this},t}(js),ua=function(e){function t(t){var i=e.call(this,t)||this;return i.minimum=0,i.maximum=1,i.registerInput("value",Fs.Float),i.registerOutput("output",Fs.Float),i}return l.d(t,e),t.prototype.getClassName=function(){return"ClampBlock"},Object.defineProperty(t.prototype,"value",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=this._declareOutput(i,t)+" = clamp("+this.value.associatedVariableName+", "+this._writeFloat(this.minimum)+", "+this._writeFloat(this.maximum)+");\r\n",this},t}(js),ha=function(e){function t(t){var i=e.call(this,t,ws.Vertex)||this;return i.complementZ=1,i.complementW=0,i.registerInput("vector",Fs.Vector2),i.registerInput("transform",Fs.Matrix),i.registerOutput("output",Fs.Vector2),i}return l.d(t,e),Object.defineProperty(t.prototype,"vector",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"transform",{get:function(){return this._inputs[1]},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"Vector2TransformBlock"},t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0],n=this.vector,r=this.transform;return t.compilationString+=this._declareOutput(i,t)+" = vec2("+r.associatedVariableName+" * vec4("+n.associatedVariableName+", "+this.complementZ+", "+this.complementW+"));\r\n",this},t}(js),da=function(e){function t(t){var i=e.call(this,t,ws.Vertex)||this;return i.complement=1,i.registerInput("vector",Fs.Vector3),i.registerInput("transform",Fs.Matrix),i.registerOutput("output",Fs.Vector4),i}return l.d(t,e),Object.defineProperty(t.prototype,"vector",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"transform",{get:function(){return this._inputs[1]},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"Vector3TransformBlock"},t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0],n=this.vector,r=this.transform;return t.compilationString+=this._declareOutput(i,t)+" = "+r.associatedVariableName+" * vec4("+n.associatedVariableName+", "+this.complement+");\r\n",this},t}(js),fa=function(e){function t(t){var i=e.call(this,t,ws.Vertex)||this;return i.registerInput("left",Fs.Matrix),i.registerInput("right",Fs.Matrix),i.registerOutput("output",Fs.Matrix),i}return l.d(t,e),Object.defineProperty(t.prototype,"left",{get:function(){return this._inputs[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"right",{get:function(){return this._inputs[1]},enumerable:!0,configurable:!0}),t.prototype.getClassName=function(){return"MatrixMultiplicationBlock"},t.prototype._buildBlock=function(t){e.prototype._buildBlock.call(this,t);var i=this._outputs[0];return t.compilationString+=this._declareOutput(i,t)+" = "+this.left.associatedVariableName+" * "+this.right.associatedVariableName+";\r\n",this},t}(js),pa=function(){function e(){}return e.prototype.optimize=function(e,t){},e}(),_a=function(){function e(e){this._pendingActions=new Array,this._workerInfos=e.map(function(e){return{worker:e,active:!1}})}return e.prototype.dispose=function(){for(var e=0,t=this._workerInfos;ee.EPSILON?1:0;l|=h,u.push(h)}switch(l){case 0:(o.x.Dot(this.normal,t.plane.normal)>0?i:n).push(t);break;case 1:r.push(t);break;case 2:s.push(t);break;case 3:var d,f=[],p=[];for(a=0;a=3&&(d=new Pa(f,t.shared)).plane&&r.push(d),p.length>=3&&(d=new Pa(p,t.shared)).plane&&s.push(d)}},e.EPSILON=1e-5,e}(),Pa=function(){function e(e,t){this.vertices=e,this.shared=t,this.plane=Aa.FromPoints(e[0].pos,e[1].pos,e[2].pos)}return e.prototype.clone=function(){return new e(this.vertices.map(function(e){return e.clone()}),this.shared)},e.prototype.flip=function(){this.vertices.reverse().map(function(e){e.flip()}),this.plane.flip()},e}(),Ra=function(){function e(e){this.plane=null,this.front=null,this.back=null,this.polygons=new Array,e&&this.build(e)}return e.prototype.clone=function(){var t=new e;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},e.prototype.invert=function(){for(var e=0;e1)?1:e.arc||1,c=0===e.sideOrientation?0:e.sideOrientation||Mi.a.DEFAULTSIDE;t.push(0,0,0),r.push(.5,.5);for(var l=2*Math.PI*a,u=l/s,h=0;ht.x&&(t.x=i.x),i.yt.y&&(t.y=i.y)}),{min:e,max:t,width:t.x-e.x,height:t.y-e.y}},e}(),Na=function(){function e(){}return e.Rectangle=function(e,t,i,n){return[new o.w(e,t),new o.w(i,t),new o.w(i,n),new o.w(e,n)]},e.Circle=function(e,t,i,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=32);for(var r=new Array,s=0,a=2*Math.PI/n,c=0;c0){var u=r.length/3;this._points.elements.forEach(function(t){n.push(0,-1,0),r.push(t.x,-e,t.y),o.push(1-(t.x-s.min.x)/s.width,1-(t.y-s.min.y)/s.height)});var h=a.length;for(l=0;ls.elements.length-1?s.elements[0]:s.elements[h+1],e.push(f.x,0,f.y),e.push(f.x,-a,f.y),e.push(d.x,0,d.y),e.push(d.x,-a,d.y);var p=new o.x(f.x,0,f.y),_=new o.x(d.x,0,d.y).subtract(p),m=new o.x(0,1,0),g=o.x.Cross(_,m);g=g.normalize(),i.push(u/r.width,0),i.push(u/r.width,1),u+=_.length(),i.push(u/r.width,0),i.push(u/r.width,1),c?(t.push(g.x,g.y,g.z),t.push(g.x,g.y,g.z),t.push(g.x,g.y,g.z),t.push(g.x,g.y,g.z),n.push(l),n.push(l+2),n.push(l+1),n.push(l+1),n.push(l+2),n.push(l+3)):(t.push(-g.x,-g.y,-g.z),t.push(-g.x,-g.y,-g.z),t.push(-g.x,-g.y,-g.z),t.push(-g.x,-g.y,-g.z),n.push(l),n.push(l+1),n.push(l+2),n.push(l+1),n.push(l+3),n.push(l+2)),l+=4}},e}();Mi.a.CreatePolygon=function(e,t,i,n,r,s){for(var a=i||new Array(3),c=n,l=[],u=0;u<3;u++)void 0===a[u]&&(a[u]=new o.y(0,0,1,1)),c&&void 0===c[u]&&(c[u]=new o.f(1,1,1,1));for(var h=e.getVerticesData(Oi.b.PositionKind),d=e.getVerticesData(Oi.b.NormalKind),f=e.getVerticesData(Oi.b.UVKind),p=e.getIndices(),_=0,m=0,g=0;g1?1:t.arc:1,s=void 0===t.closed||t.closed,a=t.shape,c=t.radius||1,l=t.tessellation||64,u=t.clip||0,h=t.updatable,d=fe.a._GetDefaultSideOrientation(t.sideOrientation),f=t.cap||fe.a.NO_CAP,p=2*Math.PI,_=new Array,m=t.invertUV||!1,g=0,v=0,y=p/l*r,b=new Array;for(g=0;g<=l-u;g++){b=[];for(f!=fe.a.CAP_START&&f!=fe.a.CAP_ALL||(b.push(new o.x(0,a[0].y,0)),b.push(new o.x(Math.cos(g*y)*a[0].x*c,a[0].y,Math.sin(g*y)*a[0].x*c))),v=0;v0||h>0){m=-d,g=-f;v=d,y=f;switch(r){case fe.a.CENTER:m-=c/=2,v+=c;break;case fe.a.LEFT:v+=c,p=-c/2;break;case fe.a.RIGHT:m-=c,p=c/2}switch(o){case fe.a.CENTER:g-=h/=2,y+=h;break;case fe.a.BOTTOM:y+=h,_=-h/2;break;case fe.a.TOP:g-=h,_=h/2}}var b=[],T=[],E=[];E[0]=[0,0,1,0,1,1,0,1],E[1]=[0,0,1,0,1,1,0,1],t!==fe.a.ROTATE_TILE&&t!==fe.a.ROTATE_ROW||(E[1]=[1,1,0,1,0,0,1,0]),t!==fe.a.FLIP_TILE&&t!==fe.a.FLIP_ROW||(E[1]=[1,0,0,0,0,1,1,1]),t!==fe.a.FLIP_N_ROTATE_TILE&&t!==fe.a.FLIP_N_ROTATE_ROW||(E[1]=[0,1,1,1,1,0,0,0]);for(var x=[],A=[],P=[],R=0,S=0;S0||h>0){var M,O,I,D,L=h>0&&(o===fe.a.CENTER||o===fe.a.TOP),w=h>0&&(o===fe.a.CENTER||o===fe.a.BOTTOM),F=c>0&&(r===fe.a.CENTER||r===fe.a.RIGHT),N=c>0&&(r===fe.a.CENTER||r===fe.a.LEFT),B=[];if(L&&F&&(b.push(m+p,g+_,0),b.push(-d+p,g+_,0),b.push(-d+p,g+h+_,0),b.push(m+p,g+h+_,0),P.push(R,R+1,R+3,R+1,R+2,R+3),R+=4,B=[M=1-c/i,O=1-h/n,I=1,O,I,D=1,M,D],t===fe.a.ROTATE_ROW&&(B=[1-M,1-O,1-I,1-O,1-I,1-D,1-M,1-D]),t===fe.a.FLIP_ROW&&(B=[1-M,O,1-I,O,1-I,D,1-M,D]),t===fe.a.FLIP_N_ROTATE_ROW&&(B=[M,1-O,I,1-O,I,1-D,M,1-D]),x=x.concat(B),A.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),L&&N&&(b.push(d+p,g+_,0),b.push(v+p,g+_,0),b.push(v+p,g+h+_,0),b.push(d+p,g+h+_,0),P.push(R,R+1,R+3,R+1,R+2,R+3),R+=4,B=[M=0,O=1-h/n,I=c/i,O,I,D=1,M,D],(t===fe.a.ROTATE_ROW||t===fe.a.ROTATE_TILE&&a%2==0)&&(B=[1-M,1-O,1-I,1-O,1-I,1-D,1-M,1-D]),(t===fe.a.FLIP_ROW||t===fe.a.FLIP_TILE&&a%2==0)&&(B=[1-M,O,1-I,O,1-I,D,1-M,D]),(t===fe.a.FLIP_N_ROTATE_ROW||t===fe.a.FLIP_N_ROTATE_TILE&&a%2==0)&&(B=[M,1-O,I,1-O,I,1-D,M,1-D]),x=x.concat(B),A.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),w&&F&&(b.push(m+p,f+_,0),b.push(-d+p,f+_,0),b.push(-d+p,y+_,0),b.push(m+p,y+_,0),P.push(R,R+1,R+3,R+1,R+2,R+3),R+=4,B=[M=1-c/i,O=0,I=1,O,I,D=h/n,M,D],(t===fe.a.ROTATE_ROW&&u%2==1||t===fe.a.ROTATE_TILE&&u%1==0)&&(B=[1-M,1-O,1-I,1-O,1-I,1-D,1-M,1-D]),(t===fe.a.FLIP_ROW&&u%2==1||t===fe.a.FLIP_TILE&&u%2==0)&&(B=[1-M,O,1-I,O,1-I,D,1-M,D]),(t===fe.a.FLIP_N_ROTATE_ROW&&u%2==1||t===fe.a.FLIP_N_ROTATE_TILE&&u%2==0)&&(B=[M,1-O,I,1-O,I,1-D,M,1-D]),x=x.concat(B),A.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),w&&N&&(b.push(d+p,f+_,0),b.push(v+p,f+_,0),b.push(v+p,y+_,0),b.push(d+p,y+_,0),P.push(R,R+1,R+3,R+1,R+2,R+3),R+=4,B=[M=0,O=0,I=c/i,O,I,D=h/n,M,D],(t===fe.a.ROTATE_ROW&&u%2==1||t===fe.a.ROTATE_TILE&&(u+a)%2==1)&&(B=[1-M,1-O,1-I,1-O,1-I,1-D,1-M,1-D]),(t===fe.a.FLIP_ROW&&u%2==1||t===fe.a.FLIP_TILE&&(u+a)%2==1)&&(B=[1-M,O,1-I,O,1-I,D,1-M,D]),(t===fe.a.FLIP_N_ROTATE_ROW&&u%2==1||t===fe.a.FLIP_N_ROTATE_TILE&&(u+a)%2==1)&&(B=[M,1-O,I,1-O,I,1-D,M,1-D]),x=x.concat(B),A.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),L){var U=[];M=0,O=1-h/n,I=1,D=1,U[0]=[M,O,I,O,I,D,M,D],U[1]=[M,O,I,O,I,D,M,D],t!==fe.a.ROTATE_TILE&&t!==fe.a.ROTATE_ROW||(U[1]=[1-M,1-O,1-I,1-O,1-I,1-D,1-M,1-D]),t!==fe.a.FLIP_TILE&&t!==fe.a.FLIP_ROW||(U[1]=[1-M,O,1-I,O,1-I,D,1-M,D]),t!==fe.a.FLIP_N_ROTATE_TILE&&t!==fe.a.FLIP_N_ROTATE_ROW||(U[1]=[M,1-O,I,1-O,I,1-D,M,1-D]);for(C=0;C1)?1:t.arc||1;var f,p,_=function(e,t,i,n,r,s,a,c){for(var l,u,h,d,f=t.getTangents(),p=t.getNormals(),_=t.getDistances(),m=2*Math.PI/r*c,g=s||function(){return n},v=o.t.Matrix[0],y=a===fe.a.NO_CAP||a===fe.a.CAP_END?0:2,b=0;b3?0:l,t.arc);var v=as.CreateRibbon(e,{pathArray:p,closePath:!0,closeArray:!1,updatable:h,sideOrientation:d,invertUV:u,frontUVs:t.frontUVs,backUVs:t.backUVs},i);return v._creationDataStorage.pathArray=p,v._creationDataStorage.path3D=f,v._creationDataStorage.tessellation=a,v._creationDataStorage.cap=l,v._creationDataStorage.arc=t.arc,v._creationDataStorage.radius=s,v},e}();Mi.a.CreateIcoSphere=function(e){var t,i=e.sideOrientation||Mi.a.DEFAULTSIDE,n=e.radius||1,r=void 0===e.flat||e.flat,s=e.subdivisions||4,a=e.radiusX||n,c=e.radiusY||n,l=e.radiusZ||n,u=(1+Math.sqrt(5))/2,h=[-1,u,-0,1,u,0,-1,-u,0,1,-u,0,0,-1,-u,0,1,-u,0,-1,u,0,1,u,u,0,1,u,0,-1,-u,0,1,-u,0,-1],d=[0,11,5,0,5,1,0,1,7,0,7,10,12,22,23,1,5,20,5,11,4,23,22,13,22,18,6,7,1,8,14,21,4,14,4,2,16,13,6,15,6,19,3,8,9,4,21,5,13,17,23,6,13,22,19,6,18,9,8,1],f=[0,1,2,3,4,5,6,7,8,9,10,11,0,2,3,3,3,4,7,8,9,9,10,11],p=[5,1,3,1,6,4,0,0,5,3,4,2,2,2,4,0,2,0,1,1,6,0,6,2,0,4,3,3,4,4,3,1,4,2,4,4,0,2,1,1,2,2,3,3,1,3,2,4],_=[0,0,0,0,1,0,0,1,1,0,0,0,1,1,0,0,1,1,1,0],m=new Array,g=new Array,v=new Array,y=new Array,b=0,T=new Array(3),E=new Array(3);for(t=0;t<3;t++)T[t]=o.x.Zero(),E[t]=o.w.Zero();for(var x=0;x<20;x++){for(t=0;t<3;t++){var A=d[3*x+t];T[t].copyFromFloats(h[3*f[A]],h[3*f[A]+1],h[3*f[A]+2]),T[t].normalize().scaleInPlace(n),E[t].copyFromFloats(p[2*A]*(138/1024)+60/1024+_[x]*(-40/1024),p[2*A+1]*(239/1024)+26/1024+_[x]*(20/1024))}for(var P=function(e,t,i,n){var u,h=o.x.Lerp(T[0],T[2],t/s),d=o.x.Lerp(T[1],T[2],t/s),f=s===t?T[2]:o.x.Lerp(h,d,e/(s-t));if(f.normalize(),r){var p=o.x.Lerp(T[0],T[2],n/s),_=o.x.Lerp(T[1],T[2],n/s);u=o.x.Lerp(p,_,i/(s-n))}else u=new o.x(f.x,f.y,f.z);u.x/=a,u.y/=c,u.z/=l,u.normalize();var x=o.w.Lerp(E[0],E[2],t/s),A=o.w.Lerp(E[1],E[2],t/s),P=s===t?E[2]:o.w.Lerp(x,A,e/(s-t));g.push(f.x*a,f.y*c,f.z*l),v.push(u.x,u.y,u.z),y.push(P.x,P.y),m.push(b),b++},R=0;R0)?1:0)+((c=o.x.Dot(e[s+1].position,t)-i>0)?1:0)+((u=o.x.Dot(e[s+2].position,t)-i>0)?1:0)){case 0:r.push(e[s]),r.push(e[s+1]),r.push(e[s+2]);break;case 1:if(a&&(h=e[s+1],d=e[s+2],f=n(e[s],h),p=n(e[s],d)),c){h=e[s],d=e[s+2],f=n(e[s+1],h),p=n(e[s+1],d),r.push(f),r.push(d.clone()),r.push(h.clone()),r.push(d.clone()),r.push(f.clone()),r.push(p);break}u&&(h=e[s],d=e[s+1],f=n(e[s+2],h),p=n(e[s+2],d)),h&&d&&f&&p&&(r.push(h.clone()),r.push(d.clone()),r.push(f),r.push(p),r.push(f.clone()),r.push(d.clone()));break;case 2:a||(d=n(h=e[s].clone(),e[s+1]),f=n(h,e[s+2]),r.push(h),r.push(d),r.push(f)),c||(d=n(h=e[s+1].clone(),e[s+2]),f=n(h,e[s]),r.push(h),r.push(d),r.push(f)),u||(d=n(h=e[s+2].clone(),e[s]),f=n(h,e[s+1]),r.push(h),r.push(d),r.push(f))}}return r},A=0;Ac||i.deleted||i.isDirty))for(var r=0;r<3;++r)if(i.error[r]>0,function(e){if(r){var t=e+a.verticesStart,s=o.x.FromArray(r,3*t),l=function(e){if(i)for(var t=0;t0&&this._reconstructedMesh.setVerticesData(Oi.b.UVKind,a),c.length>0&&this._reconstructedMesh.setVerticesData(Oi.b.ColorKind,c);var y=this._mesh.subMeshes[e];e>0&&(this._reconstructedMesh.subMeshes=[],m.forEach(function(e){Ta.b.AddToMesh(e.materialIndex,e.verticesStart,e.verticesCount,e.indexStart,e.indexCount,e.getMesh())}),Ta.b.AddToMesh(y.materialIndex,_,d,p,3*r.length,this._reconstructedMesh))},e.prototype.initDecimatedMesh=function(){this._reconstructedMesh=new fe.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},e.prototype.isFlipped=function(e,t,i,n,r){for(var s=0;s.999)return!0;var f=o.x.Cross(h,d).normalize();if(n[s]=!1,o.x.Dot(f,a.normal)<.2)return!0}else n[s]=!0,r.push(a)}}return!1},e.prototype.updateTriangles=function(e,t,i,n){for(var r=n,o=0;o=400&&o?o(l):i()},!1),l.addEventListener("error",function(){p.a.Error("error on XHR request."),i()},!1),l.send()}else p.a.Error("Error: IndexedDB not supported by your browser or Babylon.js Database is not open."),i()},e._ValidateXHRData=function(e,t){void 0===t&&(t=7);try{if(1&t){if(e.responseText&&e.responseText.length>0)return!0;if(1===t)return!1}if(2&t){var i=As.GetTGAHeader(e.response);if(i.width&&i.height&&i.width>0&&i.height>0)return!0;if(2===t)return!1}if(4&t){var n=new Uint8Array(e.response,0,3);return 68===n[0]&&68===n[1]&&83===n[2]}}catch(e){}return!1},e.IsUASupportingBlobStorage=!0,e.IDBStorageEnabled=!1,e._ParseURL=function(e){document.createElement("a").href=e;var t=e.substring(0,e.lastIndexOf("#")),i=e.substring(t.lastIndexOf("/")+1,e.length);return e.substring(0,e.indexOf(i,0))},e._ReturnFullUrlLocation=function(t){return-1===t.indexOf("http:/")&&-1===t.indexOf("https:/")?e._ParseURL(window.location.href)+t:t},e}(),rc=function(){function e(){this.direction1=new o.x(0,1,0),this.direction2=new o.x(0,1,0),this.minEmitBox=new o.x(-.5,-.5,-.5),this.maxEmitBox=new o.x(.5,.5,.5)}return e.prototype.startDirectionFunction=function(e,t,i){var n=D.a.RandomRange(this.direction1.x,this.direction2.x),r=D.a.RandomRange(this.direction1.y,this.direction2.y),s=D.a.RandomRange(this.direction1.z,this.direction2.z);o.x.TransformNormalFromFloatsToRef(n,r,s,e,t)},e.prototype.startPositionFunction=function(e,t,i){var n=D.a.RandomRange(this.minEmitBox.x,this.maxEmitBox.x),r=D.a.RandomRange(this.minEmitBox.y,this.maxEmitBox.y),s=D.a.RandomRange(this.minEmitBox.z,this.maxEmitBox.z);o.x.TransformCoordinatesFromFloatsToRef(n,r,s,e,t)},e.prototype.clone=function(){var t=new e;return S.a.DeepCopy(this,t),t},e.prototype.applyToShader=function(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2),e.setVector3("minEmitBox",this.minEmitBox),e.setVector3("maxEmitBox",this.maxEmitBox)},e.prototype.getEffectDefines=function(){return"#define BOXEMITTER"},e.prototype.getClassName=function(){return"BoxParticleEmitter"},e.prototype.serialize=function(){var e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e.minEmitBox=this.minEmitBox.asArray(),e.maxEmitBox=this.maxEmitBox.asArray(),e},e.prototype.parse=function(e){o.x.FromArrayToRef(e.direction1,0,this.direction1),o.x.FromArrayToRef(e.direction2,0,this.direction2),o.x.FromArrayToRef(e.minEmitBox,0,this.minEmitBox),o.x.FromArrayToRef(e.maxEmitBox,0,this.maxEmitBox)},e}(),oc=function(){function e(e,t,i){void 0===e&&(e=1),void 0===t&&(t=Math.PI),void 0===i&&(i=0),this.directionRandomizer=i,this.radiusRange=1,this.heightRange=1,this.emitFromSpawnPointOnly=!1,this.angle=t,this.radius=e}return Object.defineProperty(e.prototype,"radius",{get:function(){return this._radius},set:function(e){this._radius=e,this._buildHeight()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"angle",{get:function(){return this._angle},set:function(e){this._angle=e,this._buildHeight()},enumerable:!0,configurable:!0}),e.prototype._buildHeight=function(){0!==this._angle?this._height=this._radius/Math.tan(this._angle/2):this._height=1},e.prototype.startDirectionFunction=function(e,t,i){if(1===Math.abs(Math.cos(this._angle)))o.x.TransformNormalFromFloatsToRef(0,1,0,e,t);else{var n=i.position.subtract(e.getTranslation()).normalize(),r=D.a.RandomRange(0,this.directionRandomizer),s=D.a.RandomRange(0,this.directionRandomizer),a=D.a.RandomRange(0,this.directionRandomizer);n.x+=r,n.y+=s,n.z+=a,n.normalize(),o.x.TransformNormalFromFloatsToRef(n.x,n.y,n.z,e,t)}},e.prototype.startPositionFunction=function(e,t,i){var n,r=D.a.RandomRange(0,2*Math.PI);n=this.emitFromSpawnPointOnly?1e-4:1-(n=D.a.RandomRange(0,this.heightRange))*n;var s=this._radius-D.a.RandomRange(0,this._radius*this.radiusRange),a=(s*=n)*Math.sin(r),c=s*Math.cos(r),l=n*this._height;o.x.TransformCoordinatesFromFloatsToRef(a,l,c,e,t)},e.prototype.clone=function(){var t=new e(this._radius,this._angle,this.directionRandomizer);return S.a.DeepCopy(this,t),t},e.prototype.applyToShader=function(e){e.setFloat2("radius",this._radius,this.radiusRange),e.setFloat("coneAngle",this._angle),e.setFloat2("height",this._height,this.heightRange),e.setFloat("directionRandomizer",this.directionRandomizer)},e.prototype.getEffectDefines=function(){var e="#define CONEEMITTER";return this.emitFromSpawnPointOnly&&(e+="\n#define CONEEMITTERSPAWNPOINT"),e},e.prototype.getClassName=function(){return"ConeParticleEmitter"},e.prototype.serialize=function(){var e={};return e.type=this.getClassName(),e.radius=this._radius,e.angle=this._angle,e.directionRandomizer=this.directionRandomizer,e},e.prototype.parse=function(e){this.radius=e.radius,this.angle=e.angle,this.directionRandomizer=e.directionRandomizer},e}(),sc=function(){function e(e,t,i,n){void 0===e&&(e=1),void 0===t&&(t=1),void 0===i&&(i=1),void 0===n&&(n=0),this.radius=e,this.height=t,this.radiusRange=i,this.directionRandomizer=n}return e.prototype.startDirectionFunction=function(e,t,i){var n=i.position.subtract(e.getTranslation()).normalize(),r=D.a.RandomRange(-this.directionRandomizer/2,this.directionRandomizer/2),s=Math.atan2(n.x,n.z);s+=D.a.RandomRange(-Math.PI/2,Math.PI/2)*this.directionRandomizer,n.y=r,n.x=Math.sin(s),n.z=Math.cos(s),n.normalize(),o.x.TransformNormalFromFloatsToRef(n.x,n.y,n.z,e,t)},e.prototype.startPositionFunction=function(e,t,i){var n=D.a.RandomRange(-this.height/2,this.height/2),r=D.a.RandomRange(0,2*Math.PI),s=D.a.RandomRange((1-this.radiusRange)*(1-this.radiusRange),1),a=Math.sqrt(s)*this.radius,c=a*Math.cos(r),l=a*Math.sin(r);o.x.TransformCoordinatesFromFloatsToRef(c,n,l,e,t)},e.prototype.clone=function(){var t=new e(this.radius,this.directionRandomizer);return S.a.DeepCopy(this,t),t},e.prototype.applyToShader=function(e){e.setFloat("radius",this.radius),e.setFloat("height",this.height),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)},e.prototype.getEffectDefines=function(){return"#define CYLINDEREMITTER"},e.prototype.getClassName=function(){return"CylinderParticleEmitter"},e.prototype.serialize=function(){var e={};return e.type=this.getClassName(),e.radius=this.radius,e.height=this.height,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e},e.prototype.parse=function(e){this.radius=e.radius,this.height=e.height,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer},e}(),ac=function(e){function t(t,i,n,r,s){void 0===t&&(t=1),void 0===i&&(i=1),void 0===n&&(n=1),void 0===r&&(r=new o.x(0,1,0)),void 0===s&&(s=new o.x(0,1,0));var a=e.call(this,t,i,n)||this;return a.direction1=r,a.direction2=s,a}return l.d(t,e),t.prototype.startDirectionFunction=function(e,t,i){var n=D.a.RandomRange(this.direction1.x,this.direction2.x),r=D.a.RandomRange(this.direction1.y,this.direction2.y),s=D.a.RandomRange(this.direction1.z,this.direction2.z);o.x.TransformNormalFromFloatsToRef(n,r,s,e,t)},t.prototype.clone=function(){var e=new t(this.radius,this.height,this.radiusRange,this.direction1,this.direction2);return S.a.DeepCopy(this,e),e},t.prototype.applyToShader=function(e){e.setFloat("radius",this.radius),e.setFloat("height",this.height),e.setFloat("radiusRange",this.radiusRange),e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)},t.prototype.getEffectDefines=function(){return"#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER"},t.prototype.getClassName=function(){return"CylinderDirectedParticleEmitter"},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.direction1=this.direction1.asArray(),t.direction2=this.direction2.asArray(),t},t.prototype.parse=function(t){e.prototype.parse.call(this,t),this.direction1.copyFrom(t.direction1),this.direction2.copyFrom(t.direction2)},t}(sc),cc=function(){function e(e,t,i){void 0===e&&(e=1),void 0===t&&(t=1),void 0===i&&(i=0),this.radius=e,this.radiusRange=t,this.directionRandomizer=i}return e.prototype.startDirectionFunction=function(e,t,i){var n=i.position.subtract(e.getTranslation()).normalize(),r=D.a.RandomRange(0,this.directionRandomizer),s=D.a.RandomRange(0,this.directionRandomizer),a=D.a.RandomRange(0,this.directionRandomizer);n.x+=r,n.y+=s,n.z+=a,n.normalize(),o.x.TransformNormalFromFloatsToRef(n.x,n.y,n.z,e,t)},e.prototype.startPositionFunction=function(e,t,i){var n=this.radius-D.a.RandomRange(0,this.radius*this.radiusRange),r=D.a.RandomRange(0,1),s=D.a.RandomRange(0,2*Math.PI),a=Math.acos(2*r-1),c=n*Math.cos(s)*Math.sin(a),l=n*Math.cos(a),u=n*Math.sin(s)*Math.sin(a);o.x.TransformCoordinatesFromFloatsToRef(c,Math.abs(l),u,e,t)},e.prototype.clone=function(){var t=new e(this.radius,this.directionRandomizer);return S.a.DeepCopy(this,t),t},e.prototype.applyToShader=function(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)},e.prototype.getEffectDefines=function(){return"#define HEMISPHERICEMITTER"},e.prototype.getClassName=function(){return"HemisphericParticleEmitter"},e.prototype.serialize=function(){var e={};return e.type=this.getClassName(),e.radius=this.radius,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e},e.prototype.parse=function(e){this.radius=e.radius,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer},e}(),lc=function(){function e(){this.direction1=new o.x(0,1,0),this.direction2=new o.x(0,1,0)}return e.prototype.startDirectionFunction=function(e,t,i){var n=D.a.RandomRange(this.direction1.x,this.direction2.x),r=D.a.RandomRange(this.direction1.y,this.direction2.y),s=D.a.RandomRange(this.direction1.z,this.direction2.z);o.x.TransformNormalFromFloatsToRef(n,r,s,e,t)},e.prototype.startPositionFunction=function(e,t,i){o.x.TransformCoordinatesFromFloatsToRef(0,0,0,e,t)},e.prototype.clone=function(){var t=new e;return S.a.DeepCopy(this,t),t},e.prototype.applyToShader=function(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)},e.prototype.getEffectDefines=function(){return"#define POINTEMITTER"},e.prototype.getClassName=function(){return"PointParticleEmitter"},e.prototype.serialize=function(){var e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e},e.prototype.parse=function(e){o.x.FromArrayToRef(e.direction1,0,this.direction1),o.x.FromArrayToRef(e.direction2,0,this.direction2)},e}(),uc=function(){function e(e,t,i){void 0===e&&(e=1),void 0===t&&(t=1),void 0===i&&(i=0),this.radius=e,this.radiusRange=t,this.directionRandomizer=i}return e.prototype.startDirectionFunction=function(e,t,i){var n=i.position.subtract(e.getTranslation()).normalize(),r=D.a.RandomRange(0,this.directionRandomizer),s=D.a.RandomRange(0,this.directionRandomizer),a=D.a.RandomRange(0,this.directionRandomizer);n.x+=r,n.y+=s,n.z+=a,n.normalize(),o.x.TransformNormalFromFloatsToRef(n.x,n.y,n.z,e,t)},e.prototype.startPositionFunction=function(e,t,i){var n=this.radius-D.a.RandomRange(0,this.radius*this.radiusRange),r=D.a.RandomRange(0,1),s=D.a.RandomRange(0,2*Math.PI),a=Math.acos(2*r-1),c=n*Math.cos(s)*Math.sin(a),l=n*Math.cos(a),u=n*Math.sin(s)*Math.sin(a);o.x.TransformCoordinatesFromFloatsToRef(c,l,u,e,t)},e.prototype.clone=function(){var t=new e(this.radius,this.directionRandomizer);return S.a.DeepCopy(this,t),t},e.prototype.applyToShader=function(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)},e.prototype.getEffectDefines=function(){return"#define SPHEREEMITTER"},e.prototype.getClassName=function(){return"SphereParticleEmitter"},e.prototype.serialize=function(){var e={};return e.type=this.getClassName(),e.radius=this.radius,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e},e.prototype.parse=function(e){this.radius=e.radius,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer},e}(),hc=function(e){function t(t,i,n){void 0===t&&(t=1),void 0===i&&(i=new o.x(0,1,0)),void 0===n&&(n=new o.x(0,1,0));var r=e.call(this,t)||this;return r.direction1=i,r.direction2=n,r}return l.d(t,e),t.prototype.startDirectionFunction=function(e,t,i){var n=D.a.RandomRange(this.direction1.x,this.direction2.x),r=D.a.RandomRange(this.direction1.y,this.direction2.y),s=D.a.RandomRange(this.direction1.z,this.direction2.z);o.x.TransformNormalFromFloatsToRef(n,r,s,e,t)},t.prototype.clone=function(){var e=new t(this.radius,this.direction1,this.direction2);return S.a.DeepCopy(this,e),e},t.prototype.applyToShader=function(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)},t.prototype.getEffectDefines=function(){return"#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER"},t.prototype.getClassName=function(){return"SphereDirectedParticleEmitter"},t.prototype.serialize=function(){var t=e.prototype.serialize.call(this);return t.direction1=this.direction1.asArray(),t.direction2=this.direction2.asArray(),t},t.prototype.parse=function(t){e.prototype.parse.call(this,t),this.direction1.copyFrom(t.direction1),this.direction2.copyFrom(t.direction2)},t}(uc),dc=function(){function e(t){this.animations=[],this.renderingGroupId=0,this.emitter=null,this.emitRate=10,this.manualEmitCount=-1,this.updateSpeed=.01,this.targetStopDuration=0,this.disposeOnStop=!1,this.minEmitPower=1,this.maxEmitPower=1,this.minLifeTime=1,this.maxLifeTime=1,this.minSize=1,this.maxSize=1,this.minScaleX=1,this.maxScaleX=1,this.minScaleY=1,this.maxScaleY=1,this.minInitialRotation=0,this.maxInitialRotation=0,this.minAngularSpeed=0,this.maxAngularSpeed=0,this.layerMask=268435455,this.customShader=null,this.preventAutoStart=!1,this.noiseStrength=new o.x(10,10,10),this.onAnimationEnd=null,this.blendMode=e.BLENDMODE_ONEONE,this.forceDepthWrite=!1,this.preWarmCycles=0,this.preWarmStepOffset=1,this.spriteCellChangeSpeed=1,this.startSpriteCellID=0,this.endSpriteCellID=0,this.spriteCellWidth=0,this.spriteCellHeight=0,this.spriteRandomStartCell=!1,this.translationPivot=new o.w(0,0),this.beginAnimationOnStart=!1,this.beginAnimationFrom=0,this.beginAnimationTo=60,this.beginAnimationLoop=!1,this.worldOffset=new o.x(0,0,0),this.gravity=o.x.Zero(),this._colorGradients=null,this._sizeGradients=null,this._lifeTimeGradients=null,this._angularSpeedGradients=null,this._velocityGradients=null,this._limitVelocityGradients=null,this._dragGradients=null,this._emitRateGradients=null,this._startSizeGradients=null,this._rampGradients=null,this._colorRemapGradients=null,this._alphaRemapGradients=null,this.startDelay=0,this.limitVelocityDamping=.4,this.color1=new o.f(1,1,1,1),this.color2=new o.f(1,1,1,1),this.colorDead=new o.f(0,0,0,1),this.textureMask=new o.f(1,1,1,1),this._isSubEmitter=!1,this.billboardMode=_.a.PARTICLES_BILLBOARDMODE_ALL,this._isBillboardBased=!0,this._imageProcessingConfigurationDefines=new Ai.b,this.id=t,this.name=t}return Object.defineProperty(e.prototype,"noiseTexture",{get:function(){return this._noiseTexture},set:function(e){this._noiseTexture!==e&&(this._noiseTexture=e,this._reset())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isAnimationSheetEnabled",{get:function(){return this._isAnimationSheetEnabled},set:function(e){this._isAnimationSheetEnabled!=e&&(this._isAnimationSheetEnabled=e,this._reset())},enumerable:!0,configurable:!0}),e.prototype.getScene=function(){return this._scene},e.prototype._hasTargetStopDurationDependantGradient=function(){return this._startSizeGradients&&this._startSizeGradients.length>0||this._emitRateGradients&&this._emitRateGradients.length>0||this._lifeTimeGradients&&this._lifeTimeGradients.length>0},e.prototype.getDragGradients=function(){return this._dragGradients},e.prototype.getLimitVelocityGradients=function(){return this._limitVelocityGradients},e.prototype.getColorGradients=function(){return this._colorGradients},e.prototype.getSizeGradients=function(){return this._sizeGradients},e.prototype.getColorRemapGradients=function(){return this._colorRemapGradients},e.prototype.getAlphaRemapGradients=function(){return this._alphaRemapGradients},e.prototype.getLifeTimeGradients=function(){return this._lifeTimeGradients},e.prototype.getAngularSpeedGradients=function(){return this._angularSpeedGradients},e.prototype.getVelocityGradients=function(){return this._velocityGradients},e.prototype.getStartSizeGradients=function(){return this._startSizeGradients},e.prototype.getEmitRateGradients=function(){return this._emitRateGradients},Object.defineProperty(e.prototype,"direction1",{get:function(){return this.particleEmitterType.direction1?this.particleEmitterType.direction1:o.x.Zero()},set:function(e){this.particleEmitterType.direction1&&(this.particleEmitterType.direction1=e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"direction2",{get:function(){return this.particleEmitterType.direction2?this.particleEmitterType.direction2:o.x.Zero()},set:function(e){this.particleEmitterType.direction2&&(this.particleEmitterType.direction2=e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"minEmitBox",{get:function(){return this.particleEmitterType.minEmitBox?this.particleEmitterType.minEmitBox:o.x.Zero()},set:function(e){this.particleEmitterType.minEmitBox&&(this.particleEmitterType.minEmitBox=e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"maxEmitBox",{get:function(){return this.particleEmitterType.maxEmitBox?this.particleEmitterType.maxEmitBox:o.x.Zero()},set:function(e){this.particleEmitterType.maxEmitBox&&(this.particleEmitterType.maxEmitBox=e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isBillboardBased",{get:function(){return this._isBillboardBased},set:function(e){this._isBillboardBased!==e&&(this._isBillboardBased=e,this._reset())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"imageProcessingConfiguration",{get:function(){return this._imageProcessingConfiguration},set:function(e){this._attachImageProcessingConfiguration(e)},enumerable:!0,configurable:!0}),e.prototype._attachImageProcessingConfiguration=function(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration=e||this._scene.imageProcessingConfiguration)},e.prototype._reset=function(){},e.prototype._removeGradientAndTexture=function(e,t,i){if(!t)return this;for(var n=0,r=0,o=t;r0&&this._attachedSubEmitters.forEach(function(t){e._inheritParticleInfoToSubEmitter(t)})},e.prototype._reset=function(){this.age=0,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},e.prototype.copyTo=function(e){e.position.copyFrom(this.position),this._initialDirection?e._initialDirection?e._initialDirection.copyFrom(this._initialDirection):e._initialDirection=this._initialDirection.clone():e._initialDirection=null,e.direction.copyFrom(this.direction),e.color.copyFrom(this.color),e.colorStep.copyFrom(this.colorStep),e.lifeTime=this.lifeTime,e.age=this.age,e._randomCellOffset=this._randomCellOffset,e.size=this.size,e.scale.copyFrom(this.scale),e.angle=this.angle,e.angularSpeed=this.angularSpeed,e.particleSystem=this.particleSystem,e.cellIndex=this.cellIndex,e.id=this.id,e._attachedSubEmitters=this._attachedSubEmitters,this._currentColorGradient&&(e._currentColorGradient=this._currentColorGradient,e._currentColor1.copyFrom(this._currentColor1),e._currentColor2.copyFrom(this._currentColor2)),this._currentSizeGradient&&(e._currentSizeGradient=this._currentSizeGradient,e._currentSize1=this._currentSize1,e._currentSize2=this._currentSize2),this._currentAngularSpeedGradient&&(e._currentAngularSpeedGradient=this._currentAngularSpeedGradient,e._currentAngularSpeed1=this._currentAngularSpeed1,e._currentAngularSpeed2=this._currentAngularSpeed2),this._currentVelocityGradient&&(e._currentVelocityGradient=this._currentVelocityGradient,e._currentVelocity1=this._currentVelocity1,e._currentVelocity2=this._currentVelocity2),this._currentLimitVelocityGradient&&(e._currentLimitVelocityGradient=this._currentLimitVelocityGradient,e._currentLimitVelocity1=this._currentLimitVelocity1,e._currentLimitVelocity2=this._currentLimitVelocity2),this._currentDragGradient&&(e._currentDragGradient=this._currentDragGradient,e._currentDrag1=this._currentDrag1,e._currentDrag2=this._currentDrag2),this.particleSystem.isAnimationSheetEnabled&&(e._initialStartSpriteCellID=this._initialStartSpriteCellID,e._initialEndSpriteCellID=this._initialEndSpriteCellID),this.particleSystem.useRampGradients&&e.remapData.copyFrom(this.remapData),this._randomNoiseCoordinates1&&(e._randomNoiseCoordinates1?(e._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1),e._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2)):(e._randomNoiseCoordinates1=this._randomNoiseCoordinates1.clone(),e._randomNoiseCoordinates2=this._randomNoiseCoordinates2.clone()))},e._Count=0,e}();!function(e){e[e.ATTACHED=0]="ATTACHED",e[e.END=1]="END"}(ic||(ic={}));var pc=function(){function e(e){this.particleSystem=e,this.type=ic.END,this.inheritDirection=!1,this.inheritedVelocityAmount=0,e.emitter&&e.emitter.dispose||(e.emitter=new Fe.a("SubemitterSystemEmitter",e.getScene())),e.onDisposeObservable.add(function(){e.emitter&&e.emitter.dispose&&e.emitter.dispose()})}return e.prototype.clone=function(){var t=this.particleSystem.emitter;t?t instanceof o.x?t=t.clone():t instanceof Fe.a&&((t=new fe.a("",t.getScene())).isVisible=!1):t=new o.x;var i=new e(this.particleSystem.clone("",t));return i.particleSystem.name+="Clone",i.type=this.type,i.inheritDirection=this.inheritDirection,i.inheritedVelocityAmount=this.inheritedVelocityAmount,i.particleSystem._disposeEmitterOnDispose=!0,i.particleSystem.disposeOnStop=!0,i},e.prototype.serialize=function(){var e={};return e.type=this.type,e.inheritDirection=this.inheritDirection,e.inheritedVelocityAmount=this.inheritedVelocityAmount,e.particleSystem=this.particleSystem.serialize(),e},e._ParseParticleSystem=function(e,t,i){throw be.a.WarnImport("ParseParticle")},e.Parse=function(t,i,n){var r=t.particleSystem,o=new e(e._ParseParticleSystem(r,i,n));return o.type=t.type,o.inheritDirection=t.inheritDirection,o.inheritedVelocityAmount=t.inheritedVelocityAmount,o.particleSystem._isSubEmitter=!0,o},e.prototype.dispose=function(){this.particleSystem.dispose()},e}(),_c="\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#include\n#include\n#include\n#include\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\nuniform sampler2D rampSampler;\n#endif\nvoid main(void) {\n#include\nvec4 textureColor=texture2D(diffuseSampler,vUV);\nvec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n#ifdef RAMPGRADIENT\nfloat alpha=baseColor.a;\nfloat remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);\nvec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));\nbaseColor.rgb*=rampColor.rgb;\n\nfloat finalAlpha=baseColor.a;\nbaseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0);\n#endif\n#ifdef BLENDMULTIPLYMODE\nfloat sourceAlpha=vColor.a*textureColor.a;\nbaseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha);\n#endif\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\nbaseColor=applyImageProcessing(baseColor);\n#endif\n#endif\ngl_FragColor=baseColor;\n}";zt.a.ShadersStore.particlesPixelShader=_c;var mc="\nattribute vec3 position;\nattribute vec4 color;\nattribute float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET\nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD\nattribute vec3 direction;\n#endif\n#ifdef BILLBOARDSTRETCHED\nattribute vec3 direction;\n#endif\n#ifdef RAMPGRADIENT\nattribute vec4 remapData;\n#endif\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET\nuniform vec3 particlesInfos;\n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\n#endif\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include\n#ifdef BILLBOARD\nuniform vec3 eyePosition;\n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {\nvec3 normalizedToCamera=normalize(toCamera);\nvec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));\nvec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);\nvec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\nvec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\n#endif\nvoid main(void) {\nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD\n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz;\n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 toCamera=position-eyePosition;\nvec3 worldPos=rotateAlign(toCamera,rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz;\n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner;\n#endif\n#ifdef RAMPGRADIENT\nremapRanges=remapData;\n#endif\n\ngl_Position=projection*vec4(viewPos,1.0);\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(worldPos,1.0);\n#endif\nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*vec4(viewPos,1.0);\n#endif\n#include\n}";zt.a.ShadersStore.particlesVertexShader=mc;var gc=function(e){function t(t,i,n,s,a,c){void 0===s&&(s=null),void 0===a&&(a=!1),void 0===c&&(c=.01);var l=e.call(this,t)||this;return l._inheritedVelocityOffset=new o.x,l.onDisposeObservable=new r.c,l._particles=new Array,l._stockParticles=new Array,l._newPartsExcess=0,l._vertexBuffers={},l._scaledColorStep=new o.f(0,0,0,0),l._colorDiff=new o.f(0,0,0,0),l._scaledDirection=o.x.Zero(),l._scaledGravity=o.x.Zero(),l._currentRenderId=-1,l._useInstancing=!1,l._started=!1,l._stopped=!1,l._actualFrame=0,l._currentEmitRate1=0,l._currentEmitRate2=0,l._currentStartSize1=0,l._currentStartSize2=0,l._rawTextureWidth=256,l._useRampGradients=!1,l._disposeEmitterOnDispose=!1,l.recycleParticle=function(e){var t=l._particles.pop();t!==e&&t.copyTo(e),l._stockParticles.push(t)},l._createParticle=function(){var e;if(0!==l._stockParticles.length?(e=l._stockParticles.pop())._reset():e=new fc(l),l._subEmitters&&l._subEmitters.length>0){var t=l._subEmitters[Math.floor(Math.random()*l._subEmitters.length)];e._attachedSubEmitters=[],t.forEach(function(t){if(t.type===ic.ATTACHED){var i=t.clone();e._attachedSubEmitters.push(i),i.particleSystem.start()}})}return e},l._emitFromParticle=function(e){if(l._subEmitters&&0!==l._subEmitters.length){var t=Math.floor(Math.random()*l._subEmitters.length);l._subEmitters[t].forEach(function(t){if(t.type===ic.END){var i=t.clone();e._inheritParticleInfoToSubEmitter(i),i.particleSystem._rootParticleSystem=l,l.activeSubSystems.push(i.particleSystem),i.particleSystem.start()}})}},l._capacity=i,l._epsilon=c,l._isAnimationSheetEnabled=a,l._scene=n||R.a.LastCreatedScene,l._attachImageProcessingConfiguration(null),l._customEffect=s,l._scene.particleSystems.push(l),l._useInstancing=l._scene.getEngine().getCaps().instancedArrays,l._createIndexBuffer(),l._createVertexBuffers(),l.particleEmitterType=new rc,l.updateFunction=function(e){var t=null,i=null;l.noiseTexture&&(t=l.noiseTexture.getSize(),i=l.noiseTexture.getContent());for(var n,r=function(){n=e[s];var r=l._scaledUpdateSpeed,a=n.age;if(n.age+=r,n.age>n.lifeTime){var c=n.age-a;r=(n.lifeTime-a)*r/c,n.age=n.lifeTime}var u=n.age/n.lifeTime;l._colorGradients&&l._colorGradients.length>0?ye.h.GetCurrentGradient(u,l._colorGradients,function(e,t,i){e!==n._currentColorGradient&&(n._currentColor1.copyFrom(n._currentColor2),t.getColorToRef(n._currentColor2),n._currentColorGradient=e),o.f.LerpToRef(n._currentColor1,n._currentColor2,i,n.color)}):(n.colorStep.scaleToRef(r,l._scaledColorStep),n.color.addInPlace(l._scaledColorStep),n.color.a<0&&(n.color.a=0)),l._angularSpeedGradients&&l._angularSpeedGradients.length>0&&ye.h.GetCurrentGradient(u,l._angularSpeedGradients,function(e,t,i){e!==n._currentAngularSpeedGradient&&(n._currentAngularSpeed1=n._currentAngularSpeed2,n._currentAngularSpeed2=t.getFactor(),n._currentAngularSpeedGradient=e),n.angularSpeed=D.a.Lerp(n._currentAngularSpeed1,n._currentAngularSpeed2,i)}),n.angle+=n.angularSpeed*r;var h=r;if(l._velocityGradients&&l._velocityGradients.length>0&&ye.h.GetCurrentGradient(u,l._velocityGradients,function(e,t,i){e!==n._currentVelocityGradient&&(n._currentVelocity1=n._currentVelocity2,n._currentVelocity2=t.getFactor(),n._currentVelocityGradient=e),h*=D.a.Lerp(n._currentVelocity1,n._currentVelocity2,i)}),n.direction.scaleToRef(h,l._scaledDirection),l._limitVelocityGradients&&l._limitVelocityGradients.length>0&&ye.h.GetCurrentGradient(u,l._limitVelocityGradients,function(e,t,i){e!==n._currentLimitVelocityGradient&&(n._currentLimitVelocity1=n._currentLimitVelocity2,n._currentLimitVelocity2=t.getFactor(),n._currentLimitVelocityGradient=e);var r=D.a.Lerp(n._currentLimitVelocity1,n._currentLimitVelocity2,i);n.direction.length()>r&&n.direction.scaleInPlace(l.limitVelocityDamping)}),l._dragGradients&&l._dragGradients.length>0&&ye.h.GetCurrentGradient(u,l._dragGradients,function(e,t,i){e!==n._currentDragGradient&&(n._currentDrag1=n._currentDrag2,n._currentDrag2=t.getFactor(),n._currentDragGradient=e);var r=D.a.Lerp(n._currentDrag1,n._currentDrag2,i);l._scaledDirection.scaleInPlace(1-r)}),n.position.addInPlace(l._scaledDirection),i&&t&&n._randomNoiseCoordinates1){var d=l._fetchR(n._randomNoiseCoordinates1.x,n._randomNoiseCoordinates1.y,t.width,t.height,i),f=l._fetchR(n._randomNoiseCoordinates1.z,n._randomNoiseCoordinates2.x,t.width,t.height,i),p=l._fetchR(n._randomNoiseCoordinates2.y,n._randomNoiseCoordinates2.z,t.width,t.height,i),_=o.t.Vector3[0],m=o.t.Vector3[1];_.copyFromFloats((2*d-1)*l.noiseStrength.x,(2*f-1)*l.noiseStrength.y,(2*p-1)*l.noiseStrength.z),_.scaleToRef(r,m),n.direction.addInPlace(m)}if(l.gravity.scaleToRef(r,l._scaledGravity),n.direction.addInPlace(l._scaledGravity),l._sizeGradients&&l._sizeGradients.length>0&&ye.h.GetCurrentGradient(u,l._sizeGradients,function(e,t,i){e!==n._currentSizeGradient&&(n._currentSize1=n._currentSize2,n._currentSize2=t.getFactor(),n._currentSizeGradient=e),n.size=D.a.Lerp(n._currentSize1,n._currentSize2,i)}),l._useRampGradients&&(l._colorRemapGradients&&l._colorRemapGradients.length>0&&ye.h.GetCurrentGradient(u,l._colorRemapGradients,function(e,t,i){var r=D.a.Lerp(e.factor1,t.factor1,i),o=D.a.Lerp(e.factor2,t.factor2,i);n.remapData.x=r,n.remapData.y=o-r}),l._alphaRemapGradients&&l._alphaRemapGradients.length>0&&ye.h.GetCurrentGradient(u,l._alphaRemapGradients,function(e,t,i){var r=D.a.Lerp(e.factor1,t.factor1,i),o=D.a.Lerp(e.factor2,t.factor2,i);n.remapData.z=r,n.remapData.w=o-r})),l._isAnimationSheetEnabled&&n.updateCellIndex(),n._inheritParticleInfoToSubEmitters(),n.age>=n.lifeTime)return l._emitFromParticle(n),n._attachedSubEmitters&&(n._attachedSubEmitters.forEach(function(e){e.particleSystem.disposeOnStop=!0,e.particleSystem.stop()}),n._attachedSubEmitters=null),l.recycleParticle(n),s--,"continue"},s=0;st.gradient?1:0})},t.prototype._removeFactorGradient=function(e,t){if(e)for(var i=0,n=0,r=e;nt.gradient?1:0}),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._createRampGradientTexture(),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,t,i){this._colorGradients||(this._colorGradients=[]);var n=new ye.c;return n.gradient=e,n.color1=t,n.color2=i,this._colorGradients.push(n),this._colorGradients.sort(function(e,t){return e.gradientt.gradient?1:0}),this},t.prototype.removeColorGradient=function(e){if(!this._colorGradients)return this;for(var t=0,i=0,n=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){this.emitter instanceof Fe.a&&this.emitter.computeWorldMatrix(!0);var i=this.noiseTexture;if(i&&i.onGeneratedObservable)i.onGeneratedObservable.addOnce(function(){setTimeout(function(){for(var e=0;e0&&this.getScene().beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop)}},t.prototype.stop=function(e){void 0===e&&(e=!0),this._stopped=!0,e&&this._stopSubEmitters()},t.prototype.reset=function(){this._stockParticles=[],this._particles=[]},t.prototype._appendParticleVertex=function(e,i,n,r){var o=e*this._vertexBufferSize;this._vertexData[o++]=i.position.x+this.worldOffset.x,this._vertexData[o++]=i.position.y+this.worldOffset.y,this._vertexData[o++]=i.position.z+this.worldOffset.z,this._vertexData[o++]=i.color.r,this._vertexData[o++]=i.color.g,this._vertexData[o++]=i.color.b,this._vertexData[o++]=i.color.a,this._vertexData[o++]=i.angle,this._vertexData[o++]=i.scale.x*i.size,this._vertexData[o++]=i.scale.y*i.size,this._isAnimationSheetEnabled&&(this._vertexData[o++]=i.cellIndex),this._isBillboardBased?this.billboardMode===t.BILLBOARDMODE_STRETCHED&&(this._vertexData[o++]=i.direction.x,this._vertexData[o++]=i.direction.y,this._vertexData[o++]=i.direction.z):i._initialDirection?(this._vertexData[o++]=i._initialDirection.x,this._vertexData[o++]=i._initialDirection.y,this._vertexData[o++]=i._initialDirection.z):(this._vertexData[o++]=i.direction.x,this._vertexData[o++]=i.direction.y,this._vertexData[o++]=i.direction.z),this._useRampGradients&&(this._vertexData[o++]=i.remapData.x,this._vertexData[o++]=i.remapData.y,this._vertexData[o++]=i.remapData.z,this._vertexData[o++]=i.remapData.w),this._useInstancing||(this._isAnimationSheetEnabled&&(0===n?n=this._epsilon:1===n&&(n=1-this._epsilon),0===r?r=this._epsilon:1===r&&(r=1-this._epsilon)),this._vertexData[o++]=n,this._vertexData[o++]=r)},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);-1!==e&&this._rootParticleSystem.activeSubSystems.splice(e,1),this._rootParticleSystem=null}},t.prototype._update=function(e){var t,i=this;if(this._alive=this._particles.length>0,this.emitter.position){var n=this.emitter;this._emitterWorldMatrix=n.getWorldMatrix()}else{var r=this.emitter;this._emitterWorldMatrix=o.j.Translation(r.x,r.y,r.z)}this.updateFunction(this._particles);for(var s,a=function(){if(c._particles.length===c._capacity)return"break";t=c._createParticle(),c._particles.push(t);var e=D.a.RandomRange(c.minEmitPower,c.maxEmitPower);if(c.startPositionFunction?c.startPositionFunction(c._emitterWorldMatrix,t.position,t):c.particleEmitterType.startPositionFunction(c._emitterWorldMatrix,t.position,t),c.startDirectionFunction?c.startDirectionFunction(c._emitterWorldMatrix,t.direction,t):c.particleEmitterType.startDirectionFunction(c._emitterWorldMatrix,t.direction,t),0===e?t._initialDirection?t._initialDirection.copyFrom(t.direction):t._initialDirection=t.direction.clone():t._initialDirection=null,t.direction.scaleInPlace(e),c.targetStopDuration&&c._lifeTimeGradients&&c._lifeTimeGradients.length>0){var n=D.a.Clamp(c._actualFrame/c.targetStopDuration);ye.h.GetCurrentGradient(n,c._lifeTimeGradients,function(e,i){var r=e,o=i,s=r.getFactor(),a=o.getFactor(),c=(n-r.gradient)/(o.gradient-r.gradient);t.lifeTime=D.a.Lerp(s,a,c)})}else t.lifeTime=D.a.RandomRange(c.minLifeTime,c.maxLifeTime);if(c._sizeGradients&&0!==c._sizeGradients.length?(t._currentSizeGradient=c._sizeGradients[0],t._currentSize1=t._currentSizeGradient.getFactor(),t.size=t._currentSize1,c._sizeGradients.length>1?t._currentSize2=c._sizeGradients[1].getFactor():t._currentSize2=t._currentSize1):t.size=D.a.RandomRange(c.minSize,c.maxSize),t.scale.copyFromFloats(D.a.RandomRange(c.minScaleX,c.maxScaleX),D.a.RandomRange(c.minScaleY,c.maxScaleY)),c._startSizeGradients&&c._startSizeGradients[0]&&c.targetStopDuration){var r=c._actualFrame/c.targetStopDuration;ye.h.GetCurrentGradient(r,c._startSizeGradients,function(e,n,r){e!==i._currentStartSizeGradient&&(i._currentStartSize1=i._currentStartSize2,i._currentStartSize2=n.getFactor(),i._currentStartSizeGradient=e);var o=D.a.Lerp(i._currentStartSize1,i._currentStartSize2,r);t.scale.scaleInPlace(o)})}c._angularSpeedGradients&&0!==c._angularSpeedGradients.length?(t._currentAngularSpeedGradient=c._angularSpeedGradients[0],t.angularSpeed=t._currentAngularSpeedGradient.getFactor(),t._currentAngularSpeed1=t.angularSpeed,c._angularSpeedGradients.length>1?t._currentAngularSpeed2=c._angularSpeedGradients[1].getFactor():t._currentAngularSpeed2=t._currentAngularSpeed1):t.angularSpeed=D.a.RandomRange(c.minAngularSpeed,c.maxAngularSpeed),t.angle=D.a.RandomRange(c.minInitialRotation,c.maxInitialRotation),c._velocityGradients&&c._velocityGradients.length>0&&(t._currentVelocityGradient=c._velocityGradients[0],t._currentVelocity1=t._currentVelocityGradient.getFactor(),c._velocityGradients.length>1?t._currentVelocity2=c._velocityGradients[1].getFactor():t._currentVelocity2=t._currentVelocity1),c._limitVelocityGradients&&c._limitVelocityGradients.length>0&&(t._currentLimitVelocityGradient=c._limitVelocityGradients[0],t._currentLimitVelocity1=t._currentLimitVelocityGradient.getFactor(),c._limitVelocityGradients.length>1?t._currentLimitVelocity2=c._limitVelocityGradients[1].getFactor():t._currentLimitVelocity2=t._currentLimitVelocity1),c._dragGradients&&c._dragGradients.length>0&&(t._currentDragGradient=c._dragGradients[0],t._currentDrag1=t._currentDragGradient.getFactor(),c._dragGradients.length>1?t._currentDrag2=c._dragGradients[1].getFactor():t._currentDrag2=t._currentDrag1),c._colorGradients&&0!==c._colorGradients.length?(t._currentColorGradient=c._colorGradients[0],t._currentColorGradient.getColorToRef(t.color),t._currentColor1.copyFrom(t.color),c._colorGradients.length>1?c._colorGradients[1].getColorToRef(t._currentColor2):t._currentColor2.copyFrom(t.color)):(s=D.a.RandomRange(0,1),o.f.LerpToRef(c.color1,c.color2,s,t.color),c.colorDead.subtractToRef(t.color,c._colorDiff),c._colorDiff.scaleToRef(1/t.lifeTime,t.colorStep)),c._isAnimationSheetEnabled&&(t._initialStartSpriteCellID=c.startSpriteCellID,t._initialEndSpriteCellID=c.endSpriteCellID),t.direction.addInPlace(c._inheritedVelocityOffset),c._useRampGradients&&(t.remapData=new o.y(0,1,0,1)),c.noiseTexture&&(t._randomNoiseCoordinates1?(t._randomNoiseCoordinates1.copyFromFloats(Math.random(),Math.random(),Math.random()),t._randomNoiseCoordinates2.copyFromFloats(Math.random(),Math.random(),Math.random())):(t._randomNoiseCoordinates1=new o.x(Math.random(),Math.random(),Math.random()),t._randomNoiseCoordinates2=new o.x(Math.random(),Math.random(),Math.random()))),t._inheritParticleInfoToSubEmitters()},c=this,l=0;l-1)i=this.manualEmitCount,this._newPartsExcess=0,this.manualEmitCount=0;else{var n=this.emitRate;if(this._emitRateGradients&&this._emitRateGradients.length>0&&this.targetStopDuration){var r=this._actualFrame/this.targetStopDuration;ye.h.GetCurrentGradient(r,this._emitRateGradients,function(e,i,r){e!==t._currentEmitRateGradient&&(t._currentEmitRate1=t._currentEmitRate2,t._currentEmitRate2=i.getFactor(),t._currentEmitRateGradient=e),n=D.a.Lerp(t._currentEmitRate1,t._currentEmitRate2,r)})}i=n*this._scaledUpdateSpeed>>0,this._newPartsExcess+=n*this._scaledUpdateSpeed-i}if(this._newPartsExcess>1&&(i+=this._newPartsExcess>>0,this._newPartsExcess-=this._newPartsExcess>>0),this._alive=!1,this._stopped?i=0:(this._actualFrame+=this._scaledUpdateSpeed,this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop()),this._update(i),this._stopped&&(this._alive||(this._started=!1,this.onAnimationEnd&&this.onAnimationEnd(),this.disposeOnStop&&this._scene._toBeDisposed.push(this))),!e){for(var o=0,s=0;s-1&&this._scene.particleSystems.splice(t,1),this._scene._activeParticleSystems.dispose(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.reset()},t.prototype.clone=function(e,i){var n=null,r=null;if(null!=this.customShader){var o=(r=this.customShader).shaderOptions.defines.length>0?r.shaderOptions.defines.join("\n"):"";n=this._scene.getEngine().createEffectForParticles(r.shaderPath.fragmentElement,r.shaderOptions.uniforms,r.shaderOptions.samplers,o)}else this._customEffect&&(n=this._customEffect);var s=new t(e,this._capacity,this._scene,n);return s.customShader=r,S.a.DeepCopy(this,s,["particles","customShader","noiseTexture","particleTexture","onDisposeObservable"]),void 0===i&&(i=this.emitter),s.noiseTexture=this.noiseTexture,s.emitter=i,this.particleTexture&&(s.particleTexture=new Ge.a(this.particleTexture.url,this._scene)),this._colorGradients&&this._colorGradients.forEach(function(e){s.addColorGradient(e.gradient,e.color1,e.color2)}),this._dragGradients&&this._dragGradients.forEach(function(e){s.addDragGradient(e.gradient,e.factor1,e.factor2)}),this._angularSpeedGradients&&this._angularSpeedGradients.forEach(function(e){s.addAngularSpeedGradient(e.gradient,e.factor1,e.factor2)}),this._emitRateGradients&&this._emitRateGradients.forEach(function(e){s.addEmitRateGradient(e.gradient,e.factor1,e.factor2)}),this._lifeTimeGradients&&this._lifeTimeGradients.forEach(function(e){s.addLifeTimeGradient(e.gradient,e.factor1,e.factor2)}),this._limitVelocityGradients&&this._limitVelocityGradients.forEach(function(e){s.addLimitVelocityGradient(e.gradient,e.factor1,e.factor2)}),this._sizeGradients&&this._sizeGradients.forEach(function(e){s.addSizeGradient(e.gradient,e.factor1,e.factor2)}),this._startSizeGradients&&this._startSizeGradients.forEach(function(e){s.addStartSizeGradient(e.gradient,e.factor1,e.factor2)}),this._velocityGradients&&this._velocityGradients.forEach(function(e){s.addVelocityGradient(e.gradient,e.factor1,e.factor2)}),this._rampGradients&&this._rampGradients.forEach(function(e){s.addRampGradient(e.gradient,e.color)}),this._colorRemapGradients&&this._colorRemapGradients.forEach(function(e){s.addColorRemapGradient(e.gradient,e.factor1,e.factor2)}),this._alphaRemapGradients&&this._alphaRemapGradients.forEach(function(e){s.addAlphaRemapGradient(e.gradient,e.factor1,e.factor2)}),this.preventAutoStart||s.start(),s},t.prototype.serialize=function(){var e={};if(t._Serialize(e,this),e.textureMask=this.textureMask.asArray(),e.customShader=this.customShader,e.preventAutoStart=this.preventAutoStart,this.subEmitters){e.subEmitters=[],this._subEmitters||this._prepareSubEmitterInternalArray();for(var i=0,n=this._subEmitters;i0?c.shaderOptions.defines.join("\n"):"";a=i.getEngine().createEffectForParticles(c.shaderPath.fragmentElement,c.shaderOptions.uniforms,c.shaderOptions.samplers,l)}var u=new t(s,e.capacity,i,a,e.isAnimationSheetEnabled);if(u.customShader=c,e.id&&(u.id=e.id),e.subEmitters){u.subEmitters=[];for(var h=0,d=e.subEmitters;h1},enumerable:!0,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:!0,configurable:!0}),t.prototype.isReady=function(){return this._updateEffect?!!(this.emitter&&this._updateEffect.isReady()&&this._imageProcessingConfiguration.isReady()&&this._renderEffect.isReady()&&this.particleTexture&&this.particleTexture.isReady()):(this._recreateUpdateEffect(),this._recreateRenderEffect(),!1)},t.prototype.isStarted=function(){return this._started},t.prototype.start=function(e){var t=this;if(void 0===e&&(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(){t.start(0)},e):(this._started=!0,this._stopped=!1,this._preWarmDone=!1,this.beginAnimationOnStart&&this.animations&&this.animations.length>0&&this.getScene().beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop))},t.prototype.stop=function(){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._removeGradientAndTexture=function(t,i,n){return e.prototype._removeGradientAndTexture.call(this,t,i,n),this._releaseBuffers(),this},t.prototype.addColorGradient=function(e,t,i){this._colorGradients||(this._colorGradients=[]);var n=new ye.c;return n.gradient=e,n.color1=t,this._colorGradients.push(n),this._colorGradients.sort(function(e,t){return e.gradientt.gradient?1:0}),this._colorGradientsTexture&&(this._colorGradientsTexture.dispose(),this._colorGradientsTexture=null),this._releaseBuffers(),this},t.prototype.removeColorGradient=function(e){return this._removeGradientAndTexture(e,this._colorGradients,this._colorGradientsTexture),this._colorGradientsTexture=null,this},t.prototype._addFactorGradient=function(e,t,i){var n=new ye.d;n.gradient=t,n.factor1=i,e.push(n),e.sort(function(e,t){return e.gradientt.gradient?1:0}),this._releaseBuffers()},t.prototype.addSizeGradient=function(e,t){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t),this._sizeGradientsTexture&&(this._sizeGradientsTexture.dispose(),this._sizeGradientsTexture=null),this._releaseBuffers(),this},t.prototype.removeSizeGradient=function(e){return this._removeGradientAndTexture(e,this._sizeGradients,this._sizeGradientsTexture),this._sizeGradientsTexture=null,this},t.prototype.addAngularSpeedGradient=function(e,t){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t),this._angularSpeedGradientsTexture&&(this._angularSpeedGradientsTexture.dispose(),this._angularSpeedGradientsTexture=null),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,t){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t),this._velocityGradientsTexture&&(this._velocityGradientsTexture.dispose(),this._velocityGradientsTexture=null),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,t){return this._limitVelocityGradients||(this._limitVelocityGradients=[]),this._addFactorGradient(this._limitVelocityGradients,e,t),this._limitVelocityGradientsTexture&&(this._limitVelocityGradientsTexture.dispose(),this._limitVelocityGradientsTexture=null),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,t){return this._dragGradients||(this._dragGradients=[]),this._addFactorGradient(this._dragGradients,e,t),this._dragGradientsTexture&&(this._dragGradientsTexture.dispose(),this._dragGradientsTexture=null),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,t,i){return this},t.prototype.removeEmitRateGradient=function(e){return this},t.prototype.addStartSizeGradient=function(e,t,i){return this},t.prototype.removeStartSizeGradient=function(e){return this},t.prototype.addColorRemapGradient=function(e,t,i){return this},t.prototype.removeColorRemapGradient=function(){return this},t.prototype.addAlphaRemapGradient=function(e,t,i){return this},t.prototype.removeAlphaRemapGradient=function(){return this},t.prototype.addRampGradient=function(e,t){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:!0,configurable:!0}),t.prototype.addLifeTimeGradient=function(e,t,i){return this},t.prototype.removeLifeTimeGradient=function(e){return this},t.prototype._reset=function(){this._releaseBuffers()},t.prototype._createUpdateVAO=function(e){var t={};t.position=e.createVertexBuffer("position",0,3),t.age=e.createVertexBuffer("age",3,1),t.life=e.createVertexBuffer("life",4,1),t.seed=e.createVertexBuffer("seed",5,4),t.size=e.createVertexBuffer("size",9,3);var i=12;this._colorGradientsTexture||(t.color=e.createVertexBuffer("color",i,4),i+=4),t.direction=e.createVertexBuffer("direction",i,3),i+=3,this._isBillboardBased||(t.initialDirection=e.createVertexBuffer("initialDirection",i,3),i+=3),this._angularSpeedGradientsTexture?(t.angle=e.createVertexBuffer("angle",i,1),i+=1):(t.angle=e.createVertexBuffer("angle",i,2),i+=2),this._isAnimationSheetEnabled&&(t.cellIndex=e.createVertexBuffer("cellIndex",i,1),i+=1,this.spriteRandomStartCell&&(t.cellStartOffset=e.createVertexBuffer("cellStartOffset",i,1),i+=1)),this.noiseTexture&&(t.noiseCoordinates1=e.createVertexBuffer("noiseCoordinates1",i,3),i+=3,t.noiseCoordinates2=e.createVertexBuffer("noiseCoordinates2",i,3),i+=3);var n=this._engine.recordVertexArrayObject(t,null,this._updateEffect);return this._engine.bindArrayBuffer(null),n},t.prototype._createRenderVAO=function(e,t){var i={};i.position=e.createVertexBuffer("position",0,3,this._attributesStrideSize,!0),i.age=e.createVertexBuffer("age",3,1,this._attributesStrideSize,!0),i.life=e.createVertexBuffer("life",4,1,this._attributesStrideSize,!0),i.size=e.createVertexBuffer("size",9,3,this._attributesStrideSize,!0);var n=12;this._colorGradientsTexture||(i.color=e.createVertexBuffer("color",n,4,this._attributesStrideSize,!0),n+=4),this.billboardMode===gc.BILLBOARDMODE_STRETCHED&&(i.direction=e.createVertexBuffer("direction",n,3,this._attributesStrideSize,!0)),n+=3,this._isBillboardBased||(i.initialDirection=e.createVertexBuffer("initialDirection",n,3,this._attributesStrideSize,!0),n+=3),i.angle=e.createVertexBuffer("angle",n,1,this._attributesStrideSize,!0),this._angularSpeedGradientsTexture?n++:n+=2,this._isAnimationSheetEnabled&&(i.cellIndex=e.createVertexBuffer("cellIndex",n,1,this._attributesStrideSize,!0),n+=1,this.spriteRandomStartCell&&(i.cellStartOffset=e.createVertexBuffer("cellStartOffset",n,1,this._attributesStrideSize,!0),n+=1)),this.noiseTexture&&(i.noiseCoordinates1=e.createVertexBuffer("noiseCoordinates1",n,3,this._attributesStrideSize,!0),n+=3,i.noiseCoordinates2=e.createVertexBuffer("noiseCoordinates2",n,3,this._attributesStrideSize,!0),n+=3),i.offset=t.createVertexBuffer("offset",0,2),i.uv=t.createVertexBuffer("uv",2,2);var r=this._engine.recordVertexArrayObject(i,null,this._renderEffect);return this._engine.bindArrayBuffer(null),r},t.prototype._initialize=function(e){if(void 0===e&&(e=!1),!this._buffer0||e){var t=this._scene.getEngine(),i=new Array;this._attributesStrideSize=21,this._targetIndex=0,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 n=0;n=this.targetStopDuration&&this.stop()},t.prototype._createFactorGradientTexture=function(e,t){var i=this[t];if(e&&e.length&&!i){for(var n=new Float32Array(this._rawTextureWidth),r=0;r1){var i=0|this._accumulatedCount;this._accumulatedCount-=i,this._currentActiveCount=Math.min(this._activeCount,this._currentActiveCount+i)}if(!this._currentActiveCount)return 0;var n;if(this._engine.enableEffect(this._updateEffect),this._engine.setState(!1),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){n=this.emitter.getWorldMatrix()}else{var r=this.emitter;n=o.j.Translation(r.x,r.y,r.z)}if(this._updateEffect.setMatrix("emitterWM",n),this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex],null),this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer()),this._engine.setRasterizerState(!1),this._engine.beginTransformFeedback(!0),this._engine.drawArraysType(To.a.PointListDrawMode,0,this._currentActiveCount),this._engine.endTransformFeedback(),this._engine.setRasterizerState(!0),this._engine.bindTransformFeedbackBuffer(null),!e){this._engine.enableEffect(this._renderEffect);var s=this._scene.getViewMatrix();if(this._renderEffect.setMatrix("view",s),this._renderEffect.setMatrix("projection",this._scene.getProjectionMatrix()),this._renderEffect.setTexture("textureSampler",this.particleTexture),this._renderEffect.setVector2("translationPivot",this.translationPivot),this._renderEffect.setVector3("worldOffset",this.worldOffset),this._colorGradientsTexture?this._renderEffect.setTexture("colorGradientSampler",this._colorGradientsTexture):this._renderEffect.setDirectColor4("colorDead",this.colorDead),this._isAnimationSheetEnabled&&this.particleTexture){var a=this.particleTexture.getBaseSize();this._renderEffect.setFloat3("sheetInfos",this.spriteCellWidth/a.width,this.spriteCellHeight/a.height,a.width/this.spriteCellWidth)}if(this._isBillboardBased){var c=this._scene.activeCamera;this._renderEffect.setVector3("eyePosition",c.globalPosition)}if(this._scene.clipPlane||this._scene.clipPlane2||this._scene.clipPlane3||this._scene.clipPlane4){var l=s.clone();l.invert(),this._renderEffect.setMatrix("invView",l),Er.a.BindClipPlane(this._renderEffect,this._scene)}switch(this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._renderEffect),this.blendMode){case gc.BLENDMODE_ADD:this._engine.setAlphaMode(_.a.ALPHA_ADD);break;case gc.BLENDMODE_ONEONE:this._engine.setAlphaMode(_.a.ALPHA_ONEONE);break;case gc.BLENDMODE_STANDARD:this._engine.setAlphaMode(_.a.ALPHA_COMBINE);break;case gc.BLENDMODE_MULTIPLY:this._engine.setAlphaMode(_.a.ALPHA_MULTIPLY)}this.forceDepthWrite&&this._engine.setDepthWrite(!0),this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex],null),this._engine.drawArraysType(To.a.TriangleFanDrawMode,0,4,this._currentActiveCount),this._engine.setAlphaMode(_.a.ALPHA_DISABLE)}this._targetIndex++,2===this._targetIndex&&(this._targetIndex=0);var u=this._sourceBuffer;return this._sourceBuffer=this._targetBuffer,this._targetBuffer=u,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(t,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.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()},t.prototype.clone=function(e,i){var n=new t(e,{capacity:this._capacity,randomTextureSize:this._randomTextureSize},this._scene);return S.a.DeepCopy(this,n),void 0===i&&(i=this.emitter),n.emitter=i,this.particleTexture&&(n.particleTexture=new Ge.a(this.particleTexture.url,this._scene)),n},t.prototype.serialize=function(){var e={};return gc._Serialize(e,this),e.activeParticleCount=this.activeParticleCount,e},t.Parse=function(e,i,n,r){void 0===r&&(r=!1);var o=new t(e.name,{capacity:e.capacity,randomTextureSize:e.randomTextureSize},i);return e.activeParticleCount&&(o.activeParticleCount=e.activeParticleCount),gc._Parse(e,o,i,n),e.preventAutoStart&&(o.preventAutoStart=e.preventAutoStart),r||o.preventAutoStart||o.start(),o},t}(dc),Ac=(function(){}(),function(){function e(){this.systems=new Array}return Object.defineProperty(e.prototype,"emitterNode",{get:function(){return this._emitterNode},enumerable:!0,configurable:!0}),e.prototype.setEmitterAsSphere=function(e,t,i){this._emitterNode&&this._emitterNode.dispose(),this._emitterCreationOptions={kind:"Sphere",options:e,renderingGroupId:t};var n=Zn.a.CreateSphere("emitterSphere",{diameter:e.diameter,segments:e.segments},i);n.renderingGroupId=t;var r=new Pi.a("emitterSphereMaterial",i);r.emissiveColor=e.color,n.material=r;for(var o=0,s=this.systems;o0&&t.set(this._uvs32,Oi.b.UVKind),this._colors32.length>0&&t.set(this._colors32,Oi.b.ColorKind);var i=new fe.a(this.name,this._scene);return t.applyToMesh(i,this._updatable),this.mesh=i,this.mesh.isPickable=this._pickable,this._depthSort||(this._indices=null),this._positions=null,this._normals=null,this._uvs=null,this._colors=null,this._updatable||(this.particles.length=0),i},e.prototype.digest=function(e,t){var i=t&&t.facetNb||1,n=t&&t.number||0,r=t&&t.delta||0,s=e.getVerticesData(Oi.b.PositionKind),a=e.getIndices(),c=e.getVerticesData(Oi.b.UVKind),l=e.getVerticesData(Oi.b.ColorKind),u=e.getVerticesData(Oi.b.NormalKind),h=0,d=a.length/3;n?(n=n>d?d:n,i=Math.round(d/n),r=0):i=i>d?d:i;for(var f=[],p=[],_=[],m=[],g=o.x.Zero(),v=i;hd-(i=v+Math.floor((1+r)*Math.random()))&&(i=d-h),f.length=0,p.length=0,_.length=0,m.length=0;for(var y=0,b=3*h;b<3*(h+i);b++){p.push(y);var T=a[b];f.push(s[3*T],s[3*T+1],s[3*T+2]),c&&_.push(c[2*T],c[2*T+1]),l&&m.push(l[4*T],l[4*T+1],l[4*T+2],l[4*T+3]),y++}var E,x,A=this.nbParticles,P=this._posToShape(f),R=this._uvsToShapeUV(_);for(E=0;E65535&&(this._needs32Bits=!0)}if(this._pickable){var C=n.length/3;for(_=0;_=this.nbParticles?this.nbParticles-1:t,this._computeBoundingBox&&(0!=e||t!=this.nbParticles-1)){var O=this.mesh._boundingInfo;O&&(v.copyFrom(O.minimum),y.copyFrom(O.maximum))}var I=(A=this.particles[e]._pos)/3|0;R=4*I,C=2*I;for(var D=e;D<=t;D++){var L=this.particles[D];this.updateParticle(L);var w=L._model._shape,F=L._model._shapeUV,N=L._rotationMatrix,B=L.position,U=L.rotation,V=L.scaling,k=L._globalPosition;if(this._depthSort&&this._depthSortParticles){var G=this.depthSortedParticles[D];G.ind=L._ind,G.indicesLength=L._model._indicesLength,G.sqDistance=o.x.DistanceSquared(L.position,b)}if(!L.alive||L._stillInvisible&&!L.isVisible)A+=3*(M=w.length),R+=4*M,C+=2*M;else{if(L.isVisible){L._stillInvisible=!1;var z=p[12];if(L.pivot.multiplyToRef(V,z),this.billboard&&(U.x=0,U.y=0),(this._computeParticleRotation||this.billboard)&&L.getRotationMatrix(n),null!==L.parentId){var j=this.particles[L.parentId],W=j._rotationMatrix,H=j._globalPosition,X=B.x*W[1]+B.y*W[4]+B.z*W[7],Y=B.x*W[0]+B.y*W[3]+B.z*W[6],K=B.x*W[2]+B.y*W[5]+B.z*W[8];if(k.x=H.x+Y,k.y=H.y+X,k.z=H.z+K,this._computeParticleRotation||this.billboard){var Q=n.m;N[0]=Q[0]*W[0]+Q[1]*W[3]+Q[2]*W[6],N[1]=Q[0]*W[1]+Q[1]*W[4]+Q[2]*W[7],N[2]=Q[0]*W[2]+Q[1]*W[5]+Q[2]*W[8],N[3]=Q[4]*W[0]+Q[5]*W[3]+Q[6]*W[6],N[4]=Q[4]*W[1]+Q[5]*W[4]+Q[6]*W[7],N[5]=Q[4]*W[2]+Q[5]*W[5]+Q[6]*W[8],N[6]=Q[8]*W[0]+Q[9]*W[3]+Q[10]*W[6],N[7]=Q[8]*W[1]+Q[9]*W[4]+Q[10]*W[7],N[8]=Q[8]*W[2]+Q[9]*W[5]+Q[10]*W[8]}}else if(k.x=B.x,k.y=B.y,k.z=B.z,this._computeParticleRotation||this.billboard){Q=n.m;N[0]=Q[0],N[1]=Q[1],N[2]=Q[2],N[3]=Q[4],N[4]=Q[5],N[5]=Q[6],N[6]=Q[8],N[7]=Q[9],N[8]=Q[10]}var q=p[11];for(L.translateFromPivot?q.setAll(0):q.copyFrom(z),M=0;Mthis._options.radius)return null;var s=this._options.falloff===Ic.Constant?this._options.strength:this._options.strength*(1-r/this._options.radius);return{force:i.multiplyByFloats(s,s,s),contactPoint:n,distanceFromOrigin:r}},e.prototype.triggerAffectedImpostorsCallback=function(e){this._options.affectedImpostorsCallback&&this._options.affectedImpostorsCallback(e)},e.prototype.dispose=function(e){var t=this;void 0===e&&(e=!0),e?this._sphere.dispose():setTimeout(function(){t._dataFetched||t._sphere.dispose()},0)},e.prototype._prepareSphere=function(){this._sphere||(this._sphere=Zn.a.CreateSphere("radialExplosionEventSphere",this._options.sphere,this._scene),this._sphere.isVisible=!1)},e.prototype._intersectsWithSphere=function(e,t,i){var n=e.object;return this._prepareSphere(),this._sphere.position=t,this._sphere.scaling=new o.x(2*i,2*i,2*i),this._sphere._updateBoundingInfo(),this._sphere.computeWorldMatrix(!0),this._sphere.intersectsMesh(n,!0)},e}(),Nc=function(){function e(e,t,i,n){this._physicsHelper=e,this._scene=t,this._origin=i,this._options=n,this._dataFetched=!1,this._options=l.a({},new Vc,this._options),this._tickCallback=this._tick.bind(this),this._options.strength=-1*this._options.strength}return e.prototype.getData=function(){return this._dataFetched=!0,{sphere:this._sphere}},e.prototype.enable=function(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)},e.prototype.disable=function(){this._scene.unregisterBeforeRender(this._tickCallback)},e.prototype.dispose=function(e){var t=this;void 0===e&&(e=!0),e?this._sphere.dispose():setTimeout(function(){t._dataFetched||t._sphere.dispose()},0)},e.prototype._tick=function(){if(this._sphere)this._physicsHelper.applyRadialExplosionForce(this._origin,this._options);else{var e=this._physicsHelper.applyRadialExplosionForce(this._origin,this._options);e&&(this._sphere=e.getData().sphere.clone("radialExplosionEventSphereClone"))}},e}(),Bc=function(){function e(e,t,i){this._scene=e,this._origin=t,this._options=i,this._originTop=o.x.Zero(),this._originDirection=o.x.Zero(),this._cylinderPosition=o.x.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options=l.a({},new kc,this._options),this._origin.addToRef(new o.x(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new o.x(0,this._options.height,0),this._originTop),this._options.updraftMode===Dc.Perpendicular&&(this._originDirection=this._origin.subtract(this._originTop).normalize()),this._tickCallback=this._tick.bind(this),this._prepareCylinder()}return e.prototype.getData=function(){return this._dataFetched=!0,{cylinder:this._cylinder}},e.prototype.enable=function(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)},e.prototype.disable=function(){this._scene.unregisterBeforeRender(this._tickCallback)},e.prototype.dispose=function(e){var t=this;void 0===e&&(e=!0),this._cylinder&&(e?this._cylinder.dispose():setTimeout(function(){t._dataFetched||t._cylinder.dispose()},0))},e.prototype.getImpostorHitData=function(e){if(0===e.mass)return null;if(!this._intersectsWithCylinder(e))return null;var t=e.getObjectCenter();if(this._options.updraftMode===Dc.Perpendicular)var i=this._originDirection;else i=t.subtract(this._originTop);var n=o.x.Distance(this._origin,t),r=-1*this._options.strength;return{force:i.multiplyByFloats(r,r,r),contactPoint:t,distanceFromOrigin:n}},e.prototype._tick=function(){var e=this;this._physicsEngine.getImpostors().forEach(function(t){var i=e.getImpostorHitData(t);i&&t.applyForce(i.force,i.contactPoint)})},e.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)},e.prototype._intersectsWithCylinder=function(e){var t=e.object;return this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(t,!0)},e}(),Uc=function(){function e(e,t,i){this._scene=e,this._origin=t,this._options=i,this._originTop=o.x.Zero(),this._cylinderPosition=o.x.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options=l.a({},new Gc,this._options),this._origin.addToRef(new o.x(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new o.x(0,this._options.height,0),this._originTop),this._tickCallback=this._tick.bind(this),this._prepareCylinder()}return e.prototype.getData=function(){return this._dataFetched=!0,{cylinder:this._cylinder}},e.prototype.enable=function(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)},e.prototype.disable=function(){this._scene.unregisterBeforeRender(this._tickCallback)},e.prototype.dispose=function(e){var t=this;void 0===e&&(e=!0),e?this._cylinder.dispose():setTimeout(function(){t._dataFetched||t._cylinder.dispose()},0)},e.prototype.getImpostorHitData=function(e){if(0===e.mass)return null;if(!this._intersectsWithCylinder(e))return null;if("Mesh"!==e.object.getClassName()&&"InstancedMesh"!==e.object.getClassName())return null;var t=e.getObjectCenter(),i=new o.x(this._origin.x,t.y,this._origin.z),n=t.subtract(i),r=new It.a(i,n,this._options.radius).intersectsMesh(e.object),s=r.pickedPoint;if(!s)return null;var a=r.distance/this._options.radius,c=s.normalize();if(a>this._options.centripetalForceThreshold&&(c=c.negate()),a>this._options.centripetalForceThreshold)var l=c.x*this._options.centripetalForceMultiplier,u=c.y*this._options.updraftForceMultiplier,h=c.z*this._options.centripetalForceMultiplier;else{var d=o.x.Cross(i,t).normalize();l=(d.x+c.x)*this._options.centrifugalForceMultiplier,u=this._originTop.y*this._options.updraftForceMultiplier,h=(d.z+c.z)*this._options.centrifugalForceMultiplier}var f=new o.x(l,u,h);return{force:f=f.multiplyByFloats(this._options.strength,this._options.strength,this._options.strength),contactPoint:t,distanceFromOrigin:a}},e.prototype._tick=function(){var e=this;this._physicsEngine.getImpostors().forEach(function(t){var i=e.getImpostorHitData(t);i&&t.applyForce(i.force,i.contactPoint)})},e.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)},e.prototype._intersectsWithCylinder=function(e){var t=e.object;return this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(t,!0)},e}(),Vc=function(){return function(){this.radius=5,this.strength=10,this.falloff=Ic.Constant,this.sphere={segments:32,diameter:1}}}(),kc=function(){return function(){this.radius=5,this.strength=10,this.height=10,this.updraftMode=Dc.Center}}(),Gc=function(){return function(){this.radius=5,this.strength=10,this.height=10,this.centripetalForceThreshold=.7,this.centripetalForceMultiplier=5,this.centrifugalForceMultiplier=.5,this.updraftForceMultiplier=.02}}();!function(e){e[e.Constant=0]="Constant",e[e.Linear=1]="Linear"}(Ic||(Ic={})),function(e){e[e.Center=0]="Center",e[e.Perpendicular=1]="Perpendicular"}(Dc||(Dc={}));var zc="\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void)\n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11));\nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}";zt.a.ShadersStore.blackAndWhitePixelShader=zc;var jc=function(e){function t(t,i,n,r,o,s){var a=e.call(this,t,"blackAndWhite",["degree"],null,i,n,r,o,s)||this;return a.degree=1,a.onApplyObservable.add(function(e){e.setFloat("degree",a.degree)}),a}return l.d(t,e),t}(Wt),Wc=function(){function e(e,t,i,n){this._name=t,this._singleInstance=n||!0,this._getPostProcesses=i,this._cameras={},this._indicesForCamera={},this._postProcesses={}}return Object.defineProperty(e.prototype,"isSupported",{get:function(){for(var e in this._postProcesses)if(this._postProcesses.hasOwnProperty(e))for(var t=this._postProcesses[e],i=0;i-1?"#define MALI 1\n":null},t}(Wt),gl="#include\n\nuniform sampler2D textureSampler;\n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}";zt.a.ShadersStore.grainPixelShader=gl;var vl=function(e){function t(t,i,n,r,o,s,a,c){void 0===a&&(a=_.a.TEXTURETYPE_UNSIGNED_INT),void 0===c&&(c=!1);var l=e.call(this,t,"grain",["intensity","animatedSeed"],[],i,n,r,o,s,null,a,void 0,null,c)||this;return l.intensity=30,l.animated=!1,l.onApplyObservable.add(function(e){e.setFloat("intensity",l.intensity),e.setFloat("animatedSeed",l.animated?Math.random()+1:1)}),l}return l.d(t,e),t}(Wt),yl="\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void)\n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a);\n}";zt.a.ShadersStore.highlightsPixelShader=yl;var bl=function(e){function t(t,i,n,r,o,s,a){return void 0===a&&(a=_.a.TEXTURETYPE_UNSIGNED_INT),e.call(this,t,"highlights",null,null,i,n,r,o,s,null,a)||this}return l.d(t,e),t}(Wt);zt.a.IncludesShadersStore.mrtFragmentDeclaration="#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n";var Tl="#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef VELOCITY\nvarying vec4 vCurrentPosition;\nvarying vec4 vPreviousPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include[RENDER_TARGET_COUNT]\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[POSITION_INDEX]=vec4(vPosition,1.0);\n#endif\n#ifdef VELOCITY\nvec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;\nvec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;\nvec2 velocity=abs(a-b);\nvelocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;\ngl_FragData[VELOCITY_INDEX]=vec4(velocity,0.0,1.0);\n#endif\n}";zt.a.ShadersStore.geometryPixelShader=Tl;var El="precision highp float;\nprecision highp int;\n#include\n#include\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef VELOCITY\nuniform mat4 previousWorld;\nuniform mat4 previousViewProjection;\n#ifdef BONES_VELOCITY_ENABLED\n#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mPreviousBones[BonesPerMesh];\n#endif\n#endif\nvarying vec4 vCurrentPosition;\nvarying vec4 vPreviousPosition;\n#endif\nvoid main(void)\n{\n#include\n#if defined(VELOCITY) && !defined(BONES_VELOCITY_ENABLED)\n\nvCurrentPosition=viewProjection*finalWorld*vec4(position,1.0);\nvPreviousPosition=previousViewProjection*previousWorld*vec4(position,1.0);\n#endif\n#include\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#if defined(VELOCITY) && defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=viewProjection*finalWorld*vec4(position,1.0);\n#if NUM_BONE_INFLUENCERS>0\nmat4 previousInfluence;\npreviousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\npreviousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif\n#if NUM_BONE_INFLUENCERS>2\npreviousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif\n#if NUM_BONE_INFLUENCERS>3\npreviousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif\n#if NUM_BONE_INFLUENCERS>5\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif\n#if NUM_BONE_INFLUENCERS>6\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif\n#if NUM_BONE_INFLUENCERS>7\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif\nvPreviousPosition=previousViewProjection*previousWorld*previousInfluence*vec4(position,1.0);\n#else\nvPreviousPosition=previousViewProjection*previousWorld*vec4(position,1.0);\n#endif\n#endif\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}";zt.a.ShadersStore.geometryVertexShader=El;var xl=function(){function e(t,i){void 0===i&&(i=1),this._previousTransformationMatrices={},this._previousBonesTransformationMatrices={},this.excludedSkinnedMeshesFromVelocity=[],this._enablePosition=!1,this._enableVelocity=!1,this._positionIndex=-1,this._velocityIndex=-1,this._scene=t,this._ratio=i,e._SceneComponentInitialization(this._scene),this._createRenderTargets()}return Object.defineProperty(e.prototype,"renderList",{set:function(e){this._multiRenderTarget.renderList=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isSupported",{get:function(){return this._multiRenderTarget.isSupported},enumerable:!0,configurable:!0}),e.prototype.getTextureIndex=function(t){switch(t){case e.POSITION_TEXTURE_TYPE:return this._positionIndex;case e.VELOCITY_TEXTURE_TYPE:return this._velocityIndex;default:return-1}},Object.defineProperty(e.prototype,"enablePosition",{get:function(){return this._enablePosition},set:function(e){this._enablePosition=e,this.dispose(),this._createRenderTargets()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"enableVelocity",{get:function(){return this._enableVelocity},set:function(e){this._enableVelocity=e,e||(this._previousTransformationMatrices={}),this.dispose(),this._createRenderTargets()},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"scene",{get:function(){return this._scene},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"ratio",{get:function(){return this._ratio},enumerable:!0,configurable:!0}),e.prototype.isReady=function(e,t){var i=e.getMaterial();if(i&&i.disableDepthWrite)return!1;var n=[],r=[Oi.b.PositionKind,Oi.b.NormalKind],o=e.getMesh();i&&i.needAlphaTesting()&&(n.push("#define ALPHATEST"),o.isVerticesDataPresent(Oi.b.UVKind)&&(r.push(Oi.b.UVKind),n.push("#define UV1")),o.isVerticesDataPresent(Oi.b.UV2Kind)&&(r.push(Oi.b.UV2Kind),n.push("#define UV2"))),this._enablePosition&&(n.push("#define POSITION"),n.push("#define POSITION_INDEX "+this._positionIndex)),this._enableVelocity&&(n.push("#define VELOCITY"),n.push("#define VELOCITY_INDEX "+this._velocityIndex),-1===this.excludedSkinnedMeshesFromVelocity.indexOf(o)&&n.push("#define BONES_VELOCITY_ENABLED")),o.useBones&&o.computeBonesUsingShaders?(r.push(Oi.b.MatricesIndicesKind),r.push(Oi.b.MatricesWeightsKind),o.numBoneInfluencers>4&&(r.push(Oi.b.MatricesIndicesExtraKind),r.push(Oi.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"),t&&(n.push("#define INSTANCES"),Er.a.PushAttributesForInstances(r)),n.push("#define RENDER_TARGET_COUNT "+this._multiRenderTarget.textures.length);var s=n.join("\n");return this._cachedDefines!==s&&(this._cachedDefines=s,this._effect=this._scene.getEngine().createEffect("geometry",r,["world","mBones","viewProjection","diffuseMatrix","view","previousWorld","previousViewProjection","mPreviousBones"],["diffuseSampler"],s,void 0,void 0,void 0,{buffersCount:this._enablePosition?3:2})),this._effect.isReady()},e.prototype.getGBuffer=function(){return this._multiRenderTarget},Object.defineProperty(e.prototype,"samples",{get:function(){return this._multiRenderTarget.samples},set:function(e){this._multiRenderTarget.samples=e},enumerable:!0,configurable:!0}),e.prototype.dispose=function(){this.getGBuffer().dispose()},e.prototype._createRenderTargets=function(){var e=this,t=this._scene.getEngine(),i=2;if(this._enablePosition&&(this._positionIndex=i,i++),this._enableVelocity&&(this._velocityIndex=i,i++),this._multiRenderTarget=new Rs("gBuffer",{width:t.getRenderWidth()*this._ratio,height:t.getRenderHeight()*this._ratio},i,this._scene,{generateMipMaps:!1,generateDepthTexture:!0,defaultType:_.a.TEXTURETYPE_FLOAT}),this.isSupported){this._multiRenderTarget.wrapU=Ge.a.CLAMP_ADDRESSMODE,this._multiRenderTarget.wrapV=Ge.a.CLAMP_ADDRESSMODE,this._multiRenderTarget.refreshRate=1,this._multiRenderTarget.renderParticles=!1,this._multiRenderTarget.renderList=null,this._multiRenderTarget.onClearObservable.add(function(e){e.clear(new o.f(0,0,0,1),!0,!0,!0)});var n=function(t){var i=t.getRenderingMesh(),n=e._scene,r=n.getEngine(),s=t.getMaterial();if(s){if(e._enableVelocity&&!e._previousTransformationMatrices[i.uniqueId]&&(e._previousTransformationMatrices[i.uniqueId]={world:o.j.Identity(),viewProjection:n.getTransformMatrix()},i.skeleton)){var a=i.skeleton.getTransformMatrices(i);e._previousBonesTransformationMatrices[i.uniqueId]=e._copyBonesTransformationMatrices(a,new Float32Array(a.length))}r.setState(s.backFaceCulling,0,!1,n.useRightHandedSystem);var c=i._getInstancesRenderList(t._id);if(!c.mustReturn){var l=r.getCaps().instancedArrays&&null!==c.visibleInstances[t._id];if(e.isReady(t,l)){if(r.enableEffect(e._effect),i._bind(t,e._effect,To.a.TriangleFillMode),e._effect.setMatrix("viewProjection",n.getTransformMatrix()),e._effect.setMatrix("view",n.getViewMatrix()),s&&s.needAlphaTesting()){var u=s.getAlphaTestTexture();u&&(e._effect.setTexture("diffuseSampler",u),e._effect.setMatrix("diffuseMatrix",u.getTextureMatrix()))}i.useBones&&i.computeBonesUsingShaders&&i.skeleton&&(e._effect.setMatrices("mBones",i.skeleton.getTransformMatrices(i)),e._enableVelocity&&e._effect.setMatrices("mPreviousBones",e._previousBonesTransformationMatrices[i.uniqueId])),e._enableVelocity&&(e._effect.setMatrix("previousWorld",e._previousTransformationMatrices[i.uniqueId].world),e._effect.setMatrix("previousViewProjection",e._previousTransformationMatrices[i.uniqueId].viewProjection)),i._processRendering(t,e._effect,To.a.TriangleFillMode,c,l,function(t,i){return e._effect.setMatrix("world",i)})}e._enableVelocity&&(e._previousTransformationMatrices[i.uniqueId].world=i.getWorldMatrix().clone(),e._previousTransformationMatrices[i.uniqueId].viewProjection=e._scene.getTransformMatrix().clone(),i.skeleton&&e._copyBonesTransformationMatrices(i.skeleton.getTransformMatrices(i),e._previousBonesTransformationMatrices[i.uniqueId]))}}};this._multiRenderTarget.customRenderFunction=function(e,i,r,o){var s;if(o.length){for(t.setColorWrite(!1),s=0;s0){var i=this._renderEffects[t[0]].getPostProcesses();i&&(i[0].samples=e)}return!0},e.prototype.dispose=function(){},l.c([Object(L.c)()],e.prototype,"_name",void 0),e}(),Dl=function(){function e(){this._renderPipelines={}}return Object.defineProperty(e.prototype,"supportedPipelines",{get:function(){var e=[];for(var t in this._renderPipelines)if(this._renderPipelines.hasOwnProperty(t)){var i=this._renderPipelines[t];i.isSupported&&e.push(i)}return e},enumerable:!0,configurable:!0}),e.prototype.addPipeline=function(e){this._renderPipelines[e._name]=e},e.prototype.attachCamerasToRenderPipeline=function(e,t,i){void 0===i&&(i=!1);var n=this._renderPipelines[e];n&&n._attachCameras(t,i)},e.prototype.detachCamerasFromRenderPipeline=function(e,t){var i=this._renderPipelines[e];i&&i._detachCameras(t)},e.prototype.enableEffectInPipeline=function(e,t,i){var n=this._renderPipelines[e];n&&n._enableEffect(t,i)},e.prototype.disableEffectInPipeline=function(e,t,i){var n=this._renderPipelines[e];n&&n._disableEffect(t,i)},e.prototype.update=function(){for(var e in this._renderPipelines)if(this._renderPipelines.hasOwnProperty(e)){var t=this._renderPipelines[e];t.isSupported?t._update():(t.dispose(),delete this._renderPipelines[e])}},e.prototype._rebuild=function(){for(var e in this._renderPipelines){if(this._renderPipelines.hasOwnProperty(e))this._renderPipelines[e]._rebuild()}},e.prototype.dispose=function(){for(var e in this._renderPipelines){if(this._renderPipelines.hasOwnProperty(e))this._renderPipelines[e].dispose()}},e}();Object.defineProperty(H.a.prototype,"postProcessRenderPipelineManager",{get:function(){if(!this._postProcessRenderPipelineManager){var e=this._getComponent(xe.a.NAME_POSTPROCESSRENDERPIPELINEMANAGER);e||(e=new Ll(this),this._addComponent(e)),this._postProcessRenderPipelineManager=new Dl}return this._postProcessRenderPipelineManager},enumerable:!0,configurable:!0});var Ll=function(){function e(e){this.name=xe.a.NAME_POSTPROCESSRENDERPIPELINEMANAGER,this.scene=e}return e.prototype.register=function(){this.scene._gatherRenderTargetsStage.registerStep(xe.a.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER,this,this._gatherRenderTargets)},e.prototype.rebuild=function(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager._rebuild()},e.prototype.dispose=function(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager.dispose()},e.prototype._gatherRenderTargets=function(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager.update()},e}(),wl=function(e){function t(t,i,n,r,o){void 0===t&&(t=""),void 0===i&&(i=!0),void 0===n&&(n=R.a.LastCreatedScene),void 0===o&&(o=!0);var s=e.call(this,n.getEngine(),t)||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=sl.Low,s._fxaaEnabled=!1,s._imageProcessingEnabled=!0,s._bloomScale=.5,s._chromaticAberrationEnabled=!1,s._grainEnabled=!1,s._buildAllowed=!0,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=r||n.cameras,s._cameras=s._cameras.slice(),s._camerasToBeAttached=s._cameras.slice(),s._buildAllowed=o,s._scene=n;var a=s._scene.getEngine().getCaps();s._hdr=i&&(a.textureHalfFloatRender||a.textureFloatRender),s._hdr?a.textureHalfFloatRender?s._defaultPipelineTextureType=_.a.TEXTURETYPE_HALF_FLOAT:a.textureFloatRender&&(s._defaultPipelineTextureType=_.a.TEXTURETYPE_FLOAT):s._defaultPipelineTextureType=_.a.TEXTURETYPE_UNSIGNED_INT,n.postProcessRenderPipelineManager.addPipeline(s);var c=s._scene.getEngine();return s.sharpen=new Ol("sharpen",1,null,Ge.a.BILINEAR_SAMPLINGMODE,c,!1,s._defaultPipelineTextureType,!0),s._sharpenEffect=new Wc(c,s.SharpenPostProcessId,function(){return s.sharpen},!0),s.depthOfField=new ll(s._scene,null,s._depthOfFieldBlurLevel,s._defaultPipelineTextureType,!0),s.bloom=new Qc(s._scene,s._bloomScale,s._bloomWeight,s.bloomKernel,s._defaultPipelineTextureType,!0),s.chromaticAberration=new Zc("ChromaticAberration",c.getRenderWidth(),c.getRenderHeight(),1,null,Ge.a.BILINEAR_SAMPLINGMODE,c,!1,s._defaultPipelineTextureType,!0),s._chromaticAberrationEffect=new Wc(c,s.ChromaticAberrationPostProcessId,function(){return s.chromaticAberration},!0),s.grain=new vl("Grain",1,null,Ge.a.BILINEAR_SAMPLINGMODE,c,!1,s._defaultPipelineTextureType,!0),s._grainEffect=new Wc(c,s.GrainPostProcessId,function(){return s.grain},!0),s._resizeObserver=c.onResizeObservable.add(function(){s._hardwareScaleLevel=c.getHardwareScalingLevel(),s.bloomKernel=s.bloomKernel}),s._imageProcessingConfigurationObserver=s._scene.imageProcessingConfiguration.onUpdateParameters.add(function(){s.bloom._downscale._exposure=s._scene.imageProcessingConfiguration.exposure}),s._buildPipeline(),s}return l.d(t,e),Object.defineProperty(t.prototype,"scene",{get:function(){return this._scene},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"sharpenEnabled",{get:function(){return this._sharpenEnabled},set:function(e){this._sharpenEnabled!==e&&(this._sharpenEnabled=e,this._buildPipeline())},enumerable:!0,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:!0,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:!0,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:!0,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:!0,configurable:!0}),Object.defineProperty(t.prototype,"bloomEnabled",{get:function(){return this._bloomEnabled},set:function(e){this._bloomEnabled!==e&&(this._bloomEnabled=e,this._buildPipeline())},enumerable:!0,configurable:!0}),t.prototype._rebuildBloom=function(){var e=this.bloom;this.bloom=new Qc(this._scene,this.bloomScale,this._bloomWeight,this.bloomKernel,this._defaultPipelineTextureType,!1),this.bloom.threshold=e.threshold;for(var t=0;t1){for(var i=0,n=this._cameras;i-1&&(e.depthOfField.depthTexture=t.enableDepthRenderer(t.activeCamera).getDepthMap())})}else{this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);var o=this._scene.enableDepthRenderer(this._cameras[0]);this.depthOfField.depthTexture=o.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 Ci("imageProcessing",1,null,Ge.a.BILINEAR_SAMPLINGMODE,t,!1,this._defaultPipelineTextureType),this._hdr?(this.addEffect(new Wc(t,this.ImageProcessingPostProcessId,function(){return e.imageProcessing},!0)),this._setAutoClearAndTextureSharing(this.imageProcessing)):this._scene.imageProcessingConfiguration.applyByPostProcess=!1),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 ml("fxaa",1,null,Ge.a.BILINEAR_SAMPLINGMODE,t,!1,this._defaultPipelineTextureType),this.addEffect(new Wc(t,this.FxaaPostProcessId,function(){return e.fxaa},!0)),this._setAutoClearAndTextureSharing(this.fxaa,!0)),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),this._scene.activeCameras&&this._scene.activeCameras.length>1&&(this._scene.autoClear=!0),!this._enableMSAAOnFirstPostProcess(this.samples)&&this.samples>1&&p.a.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0")}},t.prototype._disposePostProcesses=function(e){void 0===e&&(e=!1);for(var t=0;t0?i._ssaoCombinePostProcess.width:i._originalColorPostProcess.width),e.setFloat("near",i._scene.activeCamera.minZ),e.setFloat("far",i._scene.activeCamera.maxZ),e.setFloat("radius",i.radius),e.setTexture("depthSampler",i._depthTexture),i._firstUpdate&&e.setArray("samplerOffsets",i._samplerOffsets))},this._blurVPostProcess=new Wt("BlurV","ssao2",["outSize","samplerOffsets","near","far","radius"],["depthSampler"],t,null,Ge.a.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,"#define BILATERAL_BLUR\n#define BILATERAL_BLUR_V\n#define SAMPLES 16\n#define EXPENSIVE "+(n?"1":"0")+"\n"),this._blurVPostProcess.onApply=function(e){i._scene.activeCamera&&(e.setFloat("outSize",i._ssaoCombinePostProcess.height>0?i._ssaoCombinePostProcess.height:i._originalColorPostProcess.height),e.setFloat("near",i._scene.activeCamera.minZ),e.setFloat("far",i._scene.activeCamera.maxZ),e.setFloat("radius",i.radius),e.setTexture("depthSampler",i._depthTexture),i._firstUpdate&&(e.setArray("samplerOffsets",i._samplerOffsets),i._firstUpdate=!1))},this._blurHPostProcess.samples=this.textureSamples,this._blurVPostProcess.samples=this.textureSamples},t.prototype._rebuild=function(){this._firstUpdate=!0,e.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,2.3283064365386963e-10*this._bits[0]},t.prototype._hammersley=function(e,t){return[e/t,this._radicalInverse_VdC(e)]},t.prototype._hemisphereSample_uniform=function(e,t){var i=2*t*Math.PI,n=1-(.85*e+.15),r=Math.sqrt(1-n*n);return new o.x(Math.cos(i)*r,Math.sin(i)*r,n)},t.prototype._generateHemisphere=function(){for(var e,t=this.samples,i=[],n=0;n1&&p.a.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0")},t.prototype._createDownSampleX4PostProcess=function(e,t){var i=this,n=new Array(32);this.downSampleX4PostProcess=new Wt("HDRDownSampleX4","standard",["dsOffsets"],[],t,null,Ge.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DOWN_SAMPLE_X4",_.a.TEXTURETYPE_UNSIGNED_INT),this.downSampleX4PostProcess.onApply=function(e){for(var t=0,r=i.downSampleX4PostProcess.width,o=i.downSampleX4PostProcess.height,s=-2;s<2;s++)for(var a=-2;a<2;a++)n[t]=(s+.5)*(1/r),n[t+1]=(a+.5)*(1/o),t+=2;e.setArray2("dsOffsets",n)},this.addEffect(new Wc(e.getEngine(),"HDRDownSampleX4",function(){return i.downSampleX4PostProcess},!0))},t.prototype._createBrightPassPostProcess=function(e,t){var i=this,n=new Array(8);this.brightPassPostProcess=new Wt("HDRBrightPass","standard",["dsOffsets","brightThreshold"],[],t,null,Ge.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define BRIGHT_PASS",_.a.TEXTURETYPE_UNSIGNED_INT),this.brightPassPostProcess.onApply=function(e){var t=1/i.brightPassPostProcess.width,r=1/i.brightPassPostProcess.height;n[0]=-.5*t,n[1]=.5*r,n[2]=.5*t,n[3]=.5*r,n[4]=-.5*t,n[5]=-.5*r,n[6]=.5*t,n[7]=-.5*r,e.setArray2("dsOffsets",n),e.setFloat("brightThreshold",i.brightThreshold)},this.addEffect(new Wc(e.getEngine(),"HDRBrightPass",function(){return i.brightPassPostProcess},!0))},t.prototype._createBlurPostProcesses=function(e,t,i,n){var r=this;void 0===n&&(n="blurWidth");var s=e.getEngine(),a=new yr("HDRBlurH_"+i,new o.w(1,0),this[n],t,null,Ge.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,_.a.TEXTURETYPE_UNSIGNED_INT),c=new yr("HDRBlurV_"+i,new o.w(0,1),this[n],t,null,Ge.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,_.a.TEXTURETYPE_UNSIGNED_INT);a.onActivateObservable.add(function(){var e=a.width/s.getRenderWidth();a.kernel=r[n]*e}),c.onActivateObservable.add(function(){var e=c.height/s.getRenderHeight();c.kernel=r.horizontalBlur?64*e:r[n]*e}),this.addEffect(new Wc(e.getEngine(),"HDRBlurH"+i,function(){return a},!0)),this.addEffect(new Wc(e.getEngine(),"HDRBlurV"+i,function(){return c},!0)),this.blurHPostProcesses.push(a),this.blurVPostProcesses.push(c)},t.prototype._createTextureAdderPostProcess=function(e,t){var i=this;this.textureAdderPostProcess=new Wt("HDRTextureAdder","standard",["exposure"],["otherSampler","lensSampler"],t,null,Ge.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define TEXTURE_ADDER",_.a.TEXTURETYPE_UNSIGNED_INT),this.textureAdderPostProcess.onApply=function(e){e.setTextureFromPostProcess("otherSampler",i._vlsEnabled?i._currentDepthOfFieldSource:i.originalPostProcess),e.setTexture("lensSampler",i.lensTexture),e.setFloat("exposure",i._currentExposure),i._currentDepthOfFieldSource=i.textureAdderFinalPostProcess},this.addEffect(new Wc(e.getEngine(),"HDRTextureAdder",function(){return i.textureAdderPostProcess},!0))},t.prototype._createVolumetricLightPostProcess=function(e,t){var i=this,n=e.enableGeometryBufferRenderer();n.enablePosition=!0;var r=n.getGBuffer();this.volumetricLightPostProcess=new Wt("HDRVLS","standard",["shadowViewProjection","cameraPosition","sunDirection","sunColor","scatteringCoefficient","scatteringPower","depthValues"],["shadowMapSampler","positionSampler"],t/8,null,Ge.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define VLS\n#define NB_STEPS "+this._volumetricLightStepsCount.toFixed(1));var s=o.w.Zero();this.volumetricLightPostProcess.onApply=function(e){if(i.sourceLight&&i.sourceLight.getShadowGenerator()&&i._scene.activeCamera){var t=i.sourceLight.getShadowGenerator();e.setTexture("shadowMapSampler",t.getShadowMap()),e.setTexture("positionSampler",r.textures[2]),e.setColor3("sunColor",i.sourceLight.diffuse),e.setVector3("sunDirection",i.sourceLight.getShadowDirection()),e.setVector3("cameraPosition",i._scene.activeCamera.globalPosition),e.setMatrix("shadowViewProjection",t.getTransformMatrix()),e.setFloat("scatteringCoefficient",i.volumetricLightCoefficient),e.setFloat("scatteringPower",i.volumetricLightPower),s.x=i.sourceLight.getDepthMinZ(i._scene.activeCamera),s.y=i.sourceLight.getDepthMaxZ(i._scene.activeCamera),e.setVector2("depthValues",s)}},this.addEffect(new Wc(e.getEngine(),"HDRVLS",function(){return i.volumetricLightPostProcess},!0)),this._createBlurPostProcesses(e,t/4,0,"volumetricLightBlurScale"),this.volumetricLightMergePostProces=new Wt("HDRVLSMerge","standard",[],["originalSampler"],t,null,Ge.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define VLSMERGE"),this.volumetricLightMergePostProces.onApply=function(e){e.setTextureFromPostProcess("originalSampler",i._bloomEnabled?i.textureAdderFinalPostProcess:i.originalPostProcess),i._currentDepthOfFieldSource=i.volumetricLightFinalPostProcess},this.addEffect(new Wc(e.getEngine(),"HDRVLSMerge",function(){return i.volumetricLightMergePostProces},!0))},t.prototype._createLuminancePostProcesses=function(e,i){var n=this,r=Math.pow(3,t.LuminanceSteps);this.luminancePostProcess=new Wt("HDRLuminance","standard",["lumOffsets"],[],{width:r,height:r},null,Ge.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LUMINANCE",i);var s=[];this.luminancePostProcess.onApply=function(e){var t=1/n.luminancePostProcess.width,i=1/n.luminancePostProcess.height;s[0]=-.5*t,s[1]=.5*i,s[2]=.5*t,s[3]=.5*i,s[4]=-.5*t,s[5]=-.5*i,s[6]=.5*t,s[7]=-.5*i,e.setArray2("lumOffsets",s)},this.addEffect(new Wc(e.getEngine(),"HDRLuminance",function(){return n.luminancePostProcess},!0));for(var a=t.LuminanceSteps-1;a>=0;a--){r=Math.pow(3,a);var c="#define LUMINANCE_DOWN_SAMPLE\n";0===a&&(c+="#define FINAL_DOWN_SAMPLER");var l=new Wt("HDRLuminanceDownSample"+a,"standard",["dsOffsets","halfDestPixelSize"],[],{width:r,height:r},null,Ge.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,c,i);this.luminanceDownSamplePostProcesses.push(l)}var u=this.luminancePostProcess;this.luminanceDownSamplePostProcesses.forEach(function(t,i){var r=new Array(18);t.onApply=function(e){if(u){for(var o=0,s=-1;s<2;s++)for(var a=-1;a<2;a++)r[o]=s/u.width,r[o+1]=a/u.height,o+=2;e.setArray2("dsOffsets",r),e.setFloat("halfDestPixelSize",.5/u.width),u=i===n.luminanceDownSamplePostProcesses.length-1?n.luminancePostProcess:t}},i===n.luminanceDownSamplePostProcesses.length-1&&(t.onAfterRender=function(){var t=e.getEngine().readPixels(0,0,1,1),i=new o.y(1/16581375,1/65025,1/255,1);n._hdrCurrentLuminance=(t[0]*i.x+t[1]*i.y+t[2]*i.z+t[3]*i.w)/100}),n.addEffect(new Wc(e.getEngine(),"HDRLuminanceDownSample"+i,function(){return t},!0))})},t.prototype._createHdrPostProcess=function(e,t){var i=this,n=["#define HDR"];this._hdrAutoExposure&&n.push("#define AUTO_EXPOSURE"),this.hdrPostProcess=new Wt("HDR","standard",["averageLuminance"],["textureAdderSampler"],t,null,Ge.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,n.join("\n"),_.a.TEXTURETYPE_UNSIGNED_INT);var r=1,o=0,s=0;this.hdrPostProcess.onApply=function(t){if(t.setTextureFromPostProcess("textureAdderSampler",i._currentDepthOfFieldSource),o+=e.getEngine().getDeltaTime(),r<0)r=i._hdrCurrentLuminance;else{var n=(s-o)/1e3;i._hdrCurrentLuminancer-i.hdrIncreaseRate*n?r-=i.hdrIncreaseRate*n:r=i._hdrCurrentLuminance}i.hdrAutoExposure?i._currentExposure=i._fixedExposure/r:(r=D.a.Clamp(r,i.hdrMinimumLuminance,1e20),t.setFloat("averageLuminance",r)),s=o,i._currentDepthOfFieldSource=i.hdrFinalPostProcess},this.addEffect(new Wc(e.getEngine(),"HDR",function(){return i.hdrPostProcess},!0))},t.prototype._createLensFlarePostProcess=function(e,t){var i=this;this.lensFlarePostProcess=new Wt("HDRLensFlare","standard",["strength","ghostDispersal","haloWidth","resolution","distortionStrength"],["lensColorSampler"],t/2,null,Ge.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE",_.a.TEXTURETYPE_UNSIGNED_INT),this.addEffect(new Wc(e.getEngine(),"HDRLensFlare",function(){return i.lensFlarePostProcess},!0)),this._createBlurPostProcesses(e,t/4,2),this.lensFlareComposePostProcess=new Wt("HDRLensFlareCompose","standard",["lensStarMatrix"],["otherSampler","lensDirtSampler","lensStarSampler"],t,null,Ge.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE_COMPOSE",_.a.TEXTURETYPE_UNSIGNED_INT),this.addEffect(new Wc(e.getEngine(),"HDRLensFlareCompose",function(){return i.lensFlareComposePostProcess},!0));var n=new o.w(0,0);this.lensFlarePostProcess.onApply=function(e){e.setTextureFromPostProcess("textureSampler",i._bloomEnabled?i.blurHPostProcesses[0]:i.originalPostProcess),e.setTexture("lensColorSampler",i.lensColorTexture),e.setFloat("strength",i.lensFlareStrength),e.setFloat("ghostDispersal",i.lensFlareGhostDispersal),e.setFloat("haloWidth",i.lensFlareHaloWidth),n.x=i.lensFlarePostProcess.width,n.y=i.lensFlarePostProcess.height,e.setVector2("resolution",n),e.setFloat("distortionStrength",i.lensFlareDistortionStrength)};var r=o.j.FromValues(2,0,-1,0,0,2,-1,0,0,0,1,0,0,0,0,1),s=o.j.FromValues(.5,0,.5,0,0,.5,.5,0,0,0,1,0,0,0,0,1);this.lensFlareComposePostProcess.onApply=function(e){if(i._scene.activeCamera){e.setTextureFromPostProcess("otherSampler",i._currentDepthOfFieldSource),e.setTexture("lensDirtSampler",i.lensFlareDirtTexture),e.setTexture("lensStarSampler",i.lensStarTexture);var t=i._scene.activeCamera.getViewMatrix().getRow(0),n=i._scene.activeCamera.getViewMatrix().getRow(2),a=o.x.Dot(t.toVector3(),new o.x(1,0,0))+o.x.Dot(n.toVector3(),new o.x(0,0,1));a*=4;var c=o.j.FromValues(.5*Math.cos(a),-Math.sin(a),0,0,Math.sin(a),.5*Math.cos(a),0,0,0,0,1,0,0,0,0,1),l=s.multiply(c).multiply(r);e.setMatrix("lensStarMatrix",l),i._currentDepthOfFieldSource=i.lensFlareFinalPostProcess}}},t.prototype._createDepthOfFieldPostProcess=function(e,t){var i=this;this.depthOfFieldPostProcess=new Wt("HDRDepthOfField","standard",["distance"],["otherSampler","depthSampler"],t,null,Ge.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DEPTH_OF_FIELD",_.a.TEXTURETYPE_UNSIGNED_INT),this.depthOfFieldPostProcess.onApply=function(e){e.setTextureFromPostProcess("otherSampler",i._currentDepthOfFieldSource),e.setTexture("depthSampler",i._getDepthTexture()),e.setFloat("distance",i.depthOfFieldDistance)},this.addEffect(new Wc(e.getEngine(),"HDRDepthOfField",function(){return i.depthOfFieldPostProcess},!0))},t.prototype._createMotionBlurPostProcess=function(e,t){var i=this;if(this._isObjectBasedMotionBlur){var n=new Rl("HDRMotionBlur",e,t,null,Ge.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,_.a.TEXTURETYPE_UNSIGNED_INT);n.motionStrength=this.motionStrength,n.motionBlurSamples=this.motionBlurSamples,this.motionBlurPostProcess=n}else{this.motionBlurPostProcess=new Wt("HDRMotionBlur","standard",["inverseViewProjection","prevViewProjection","screenSize","motionScale","motionStrength"],["depthSampler"],t,null,Ge.a.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES "+this.motionBlurSamples.toFixed(1),_.a.TEXTURETYPE_UNSIGNED_INT);var r=0,s=o.j.Identity(),a=o.j.Identity(),c=o.j.Identity(),l=o.w.Zero();this.motionBlurPostProcess.onApply=function(t){(c=e.getProjectionMatrix().multiply(e.getViewMatrix())).invertToRef(a),t.setMatrix("inverseViewProjection",a),t.setMatrix("prevViewProjection",s),s=c,l.x=i.motionBlurPostProcess.width,l.y=i.motionBlurPostProcess.height,t.setVector2("screenSize",l),r=e.getEngine().getFps()/60,t.setFloat("motionScale",r),t.setFloat("motionStrength",i.motionStrength),t.setTexture("depthSampler",i._getDepthTexture())}}this.addEffect(new Wc(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&&-1!==this.excludedMeshes.indexOf(e)},t.prototype._createPass=function(e,t){var i=this,n=e.getEngine();this._volumetricLightScatteringRTT=new _i("volumetricLightScatteringMap",{width:n.getRenderWidth()*t,height:n.getRenderHeight()*t},e,!1,!0,_.a.TEXTURETYPE_UNSIGNED_INT),this._volumetricLightScatteringRTT.wrapU=Ge.a.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.wrapV=Ge.a.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.renderList=null,this._volumetricLightScatteringRTT.renderParticles=!1,this._volumetricLightScatteringRTT.ignoreCameraViewport=!0;var r=this.getCamera();r?r.customRenderTargets.push(this._volumetricLightScatteringRTT):e.customRenderTargets.push(this._volumetricLightScatteringRTT);var s,a=function(e){var t=e.getRenderingMesh();if(!i._meshExcluded(t)){var n=e.getMaterial();if(n){var r=t.getScene(),o=r.getEngine();o.setState(n.backFaceCulling);var s=t._getInstancesRenderList(e._id);if(!s.mustReturn){var a=o.getCaps().instancedArrays&&null!==s.visibleInstances[e._id];if(i._isReady(e,a)){var c=i._volumetricLightScatteringPass;if(t===i.mesh&&(c=e.effect?e.effect:n.getEffect()),o.enableEffect(c),t._bind(e,c,To.a.TriangleFillMode),t===i.mesh)n.bind(t.getWorldMatrix(),t);else{if(i._volumetricLightScatteringPass.setMatrix("viewProjection",r.getTransformMatrix()),n&&n.needAlphaTesting()){var l=n.getAlphaTestTexture();i._volumetricLightScatteringPass.setTexture("diffuseSampler",l),l&&i._volumetricLightScatteringPass.setMatrix("diffuseMatrix",l.getTextureMatrix())}t.useBones&&t.computeBonesUsingShaders&&t.skeleton&&i._volumetricLightScatteringPass.setMatrices("mBones",t.skeleton.getTransformMatrices(t))}t._processRendering(e,i._volumetricLightScatteringPass,To.a.TriangleFillMode,s,a,function(e,t){return c.setMatrix("world",t)})}}}}},c=new o.f(0,0,0,1);this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function(){s=e.clearColor,e.clearColor=c}),this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function(){e.clearColor=s}),this._volumetricLightScatteringRTT.customRenderFunction=function(t,i,n,r){var o,s=e.getEngine();if(r.length){for(s.setColorWrite(!1),o=0;ot._alphaIndex?1:e._alphaIndext._distanceToCamera?-1:0}),s.setAlphaMode(_.a.ALPHA_COMBINE),o=0;o4&&(r.push(Oi.b.MatricesIndicesExtraKind),r.push(Oi.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"),t&&(n.push("#define INSTANCES"),Er.a.PushAttributesForInstances(r));var s=n.join("\n");return this._cachedDefines!==s&&(this._cachedDefines=s,this._effect=this._scene.getEngine().createEffect("depth",r,["world","mBones","viewProjection","diffuseMatrix","depthValues"],["diffuseSampler"],s)),this._effect.isReady()},e.prototype.getDepthMap=function(){return this._depthMap},e.prototype.dispose=function(){this._depthMap.dispose()},e._SceneComponentInitialization=function(e){throw be.a.WarnImport("DepthRendererSceneComponent")},e}();H.a.prototype.enableDepthRenderer=function(e){if(!(e=e||this.activeCamera))throw"No camera available to enable depth renderer";if(this._depthRenderer||(this._depthRenderer={}),!this._depthRenderer[e.id]){var t=0;if(this.getEngine().getCaps().textureHalfFloatRender)t=_.a.TEXTURETYPE_HALF_FLOAT;else{if(!this.getEngine().getCaps().textureFloatRender)throw"Depth renderer does not support int texture type";t=_.a.TEXTURETYPE_FLOAT}this._depthRenderer[e.id]=new eu(this,t,e)}return this._depthRenderer[e.id]},H.a.prototype.disableDepthRenderer=function(e){(e=e||this.activeCamera)&&this._depthRenderer&&this._depthRenderer[e.id]&&(this._depthRenderer[e.id].dispose(),delete this._depthRenderer[e.id])};var tu=function(){function e(e){this.name=xe.a.NAME_DEPTHRENDERER,this.scene=e}return e.prototype.register=function(){this.scene._gatherRenderTargetsStage.registerStep(xe.a.STEP_GATHERRENDERTARGETS_DEPTHRENDERER,this,this._gatherRenderTargets),this.scene._gatherActiveCameraRenderTargetsStage.registerStep(xe.a.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER,this,this._gatherActiveCameraRenderTargets)},e.prototype.rebuild=function(){},e.prototype.dispose=function(){for(var e in this.scene._depthRenderer)this.scene._depthRenderer[e].dispose()},e.prototype._gatherRenderTargets=function(e){if(this.scene._depthRenderer)for(var t in this.scene._depthRenderer){var i=this.scene._depthRenderer[t];i.useOnlyInActiveCamera||e.push(i.getDepthMap())}},e.prototype._gatherActiveCameraRenderTargets=function(e){if(this.scene._depthRenderer)for(var t in this.scene._depthRenderer){var i=this.scene._depthRenderer[t];i.useOnlyInActiveCamera&&this.scene.activeCamera.id===t&&e.push(i.getDepthMap())}},e}();eu._SceneComponentInitialization=function(e){var t=e._getComponent(xe.a.NAME_DEPTHRENDERER);t||(t=new tu(e),e._addComponent(t))};var iu="uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}";zt.a.ShadersStore.linePixelShader=iu;var nu="\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}";zt.a.ShadersStore.lineVertexShader=nu;Fe.a.prototype.disableEdgesRendering=function(){return this._edgesRenderer&&(this._edgesRenderer.dispose(),this._edgesRenderer=null),this},Fe.a.prototype.enableEdgesRendering=function(e,t){return void 0===e&&(e=.95),void 0===t&&(t=!1),this.disableEdgesRendering(),this._edgesRenderer=new ou(this,e,t),this},Object.defineProperty(Fe.a.prototype,"edgesRenderer",{get:function(){return this._edgesRenderer},enumerable:!0,configurable:!0}),Oa.b.prototype.enableEdgesRendering=function(e,t){return void 0===e&&(e=.95),void 0===t&&(t=!1),this.disableEdgesRendering(),this._edgesRenderer=new su(this,e,t),this},Oa.a.prototype.enableEdgesRendering=function(e,t){return void 0===e&&(e=.95),void 0===t&&(t=!1),Oa.b.prototype.enableEdgesRendering.apply(this,arguments),this};var ru=function(){return function(){this.edges=new Array,this.edgesConnectedCount=0}}(),ou=function(){function e(e,t,i,n){var r=this;void 0===t&&(t=.95),void 0===i&&(i=!1),void 0===n&&(n=!0),this.edgesWidthScalerForOrthographic=1e3,this.edgesWidthScalerForPerspective=50,this._linesPositions=new Array,this._linesNormals=new Array,this._linesIndices=new Array,this._buffers={},this._checkVerticesInsteadOfIndices=!1,this.isEnabled=!0,this._source=e,this._checkVerticesInsteadOfIndices=i,this._epsilon=t,this._prepareRessources(),n&&this._generateEdgesLines(),this._meshRebuildObserver=this._source.onRebuildObservable.add(function(){r._rebuild()}),this._meshDisposeObserver=this._source.onDisposeObservable.add(function(){r.dispose()})}return e.prototype._prepareRessources=function(){this._lineShader||(this._lineShader=new Ts.a("lineShader",this._source.getScene(),"line",{attributes:["position","normal"],uniforms:["worldViewProjection","color","width","aspectRatio"]}),this._lineShader.disableDepthWrite=!0,this._lineShader.backFaceCulling=!1)},e.prototype._rebuild=function(){var e=this._buffers[Oi.b.PositionKind];e&&e._rebuild(),(e=this._buffers[Oi.b.NormalKind])&&e._rebuild();var t=this._source.getScene().getEngine();this._ib=t.createIndexBuffer(this._linesIndices)},e.prototype.dispose=function(){this._source.onRebuildObservable.remove(this._meshRebuildObserver),this._source.onDisposeObservable.remove(this._meshDisposeObserver);var e=this._buffers[Oi.b.PositionKind];e&&(e.dispose(),this._buffers[Oi.b.PositionKind]=null),(e=this._buffers[Oi.b.NormalKind])&&(e.dispose(),this._buffers[Oi.b.NormalKind]=null),this._source.getScene().getEngine()._releaseBuffer(this._ib),this._lineShader.dispose()},e.prototype._processEdgeForAdjacencies=function(e,t,i,n,r){return e===i&&t===n||e===n&&t===i?0:e===n&&t===r||e===r&&t===n?1:e===r&&t===i||e===i&&t===r?2:-1},e.prototype._processEdgeForAdjacenciesWithVertices=function(e,t,i,n,r){return e.equalsWithEpsilon(i)&&t.equalsWithEpsilon(n)||e.equalsWithEpsilon(n)&&t.equalsWithEpsilon(i)?0:e.equalsWithEpsilon(n)&&t.equalsWithEpsilon(r)||e.equalsWithEpsilon(r)&&t.equalsWithEpsilon(n)?1:e.equalsWithEpsilon(r)&&t.equalsWithEpsilon(i)||e.equalsWithEpsilon(i)&&t.equalsWithEpsilon(r)?2:-1},e.prototype._checkEdge=function(e,t,i,n,r){var s;void 0===t?s=!0:s=o.x.Dot(i[e],i[t])\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include\ngl_FragColor=color;\n}";zt.a.ShadersStore.outlinePixelShader=au;var cu="\nattribute vec3 position;\nattribute vec3 normal;\n#include\n\nuniform float offset;\n#include\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include\n#include\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include\n}\n";zt.a.ShadersStore.outlineVertexShader=cu;H.a.prototype.getOutlineRenderer=function(){return this._outlineRenderer||(this._outlineRenderer=new lu(this)),this._outlineRenderer},Object.defineProperty(Fe.a.prototype,"renderOutline",{get:function(){return this._renderOutline},set:function(e){e&&this.getScene().getOutlineRenderer(),this._renderOutline=e},enumerable:!0,configurable:!0}),Object.defineProperty(Fe.a.prototype,"renderOverlay",{get:function(){return this._renderOverlay},set:function(e){e&&this.getScene().getOutlineRenderer(),this._renderOverlay=e},enumerable:!0,configurable:!0});var lu=function(){function e(e){this.name=xe.a.NAME_OUTLINERENDERER,this.zOffset=1,this.scene=e,this._engine=e.getEngine(),this.scene._addComponent(this)}return e.prototype.register=function(){this.scene._beforeRenderingMeshStage.registerStep(xe.a.STEP_BEFORERENDERINGMESH_OUTLINE,this,this._beforeRenderingMesh),this.scene._afterRenderingMeshStage.registerStep(xe.a.STEP_AFTERRENDERINGMESH_OUTLINE,this,this._afterRenderingMesh)},e.prototype.rebuild=function(){},e.prototype.dispose=function(){},e.prototype.render=function(e,t,i){var n=this;void 0===i&&(i=!1);var r=this.scene,o=r.getEngine(),s=o.getCaps().instancedArrays&&null!==t.visibleInstances[e._id]&&void 0!==t.visibleInstances[e._id];if(this.isReady(e,s)){var a=e.getRenderingMesh(),c=e.getMaterial();if(c&&r.activeCamera){if(o.enableEffect(this._effect),c.useLogarithmicDepth&&this._effect.setFloat("logarithmicDepthConstant",2/(Math.log(r.activeCamera.maxZ+1)/Math.LN2)),this._effect.setFloat("offset",i?0:a.outlineWidth),this._effect.setColor4("color",i?a.overlayColor:a.outlineColor,i?a.overlayAlpha:c.alpha),this._effect.setMatrix("viewProjection",r.getTransformMatrix()),a.useBones&&a.computeBonesUsingShaders&&a.skeleton&&this._effect.setMatrices("mBones",a.skeleton.getTransformMatrices(a)),a._bind(e,this._effect,To.a.TriangleFillMode),c&&c.needAlphaTesting()){var l=c.getAlphaTestTexture();l&&(this._effect.setTexture("diffuseSampler",l),this._effect.setMatrix("diffuseMatrix",l.getTextureMatrix()))}o.setZOffset(-this.zOffset),a._processRendering(e,this._effect,To.a.TriangleFillMode,t,s,function(e,t){n._effect.setMatrix("world",t)}),o.setZOffset(0)}}},e.prototype.isReady=function(e,t){var i=[],n=[Oi.b.PositionKind,Oi.b.NormalKind],r=e.getMesh(),o=e.getMaterial();o&&(o.needAlphaTesting()&&(i.push("#define ALPHATEST"),r.isVerticesDataPresent(Oi.b.UVKind)&&(n.push(Oi.b.UVKind),i.push("#define UV1")),r.isVerticesDataPresent(Oi.b.UV2Kind)&&(n.push(Oi.b.UV2Kind),i.push("#define UV2"))),o.useLogarithmicDepth&&i.push("#define LOGARITHMICDEPTH")),r.useBones&&r.computeBonesUsingShaders?(n.push(Oi.b.MatricesIndicesKind),n.push(Oi.b.MatricesWeightsKind),r.numBoneInfluencers>4&&(n.push(Oi.b.MatricesIndicesExtraKind),n.push(Oi.b.MatricesWeightsExtraKind)),i.push("#define NUM_BONE_INFLUENCERS "+r.numBoneInfluencers),i.push("#define BonesPerMesh "+(r.skeleton?r.skeleton.bones.length+1:0))):i.push("#define NUM_BONE_INFLUENCERS 0"),t&&(i.push("#define INSTANCES"),Er.a.PushAttributesForInstances(n));var s=i.join("\n");return this._cachedDefines!==s&&(this._cachedDefines=s,this._effect=this.scene.getEngine().createEffect("outline",n,["world","mBones","viewProjection","diffuseMatrix","offset","color","logarithmicDepthConstant"],["diffuseSampler"],s)),this._effect.isReady()},e.prototype._beforeRenderingMesh=function(t,i,n){if(this._savedDepthWrite=this._engine.getDepthWrite(),t.renderOutline){var r=i.getMaterial();r&&r.needAlphaBlending&&(this._engine.cacheStencilState(),this._engine.setDepthWrite(!1),this._engine.setColorWrite(!1),this._engine.setStencilBuffer(!0),this._engine.setStencilOperationPass(_.a.REPLACE),this._engine.setStencilFunction(_.a.ALWAYS),this._engine.setStencilMask(e._StencilReference),this._engine.setStencilFunctionReference(e._StencilReference),this.render(i,n,!0),this._engine.setColorWrite(!0),this._engine.setStencilFunction(_.a.NOTEQUAL)),this._engine.setDepthWrite(!1),this.render(i,n),this._engine.setDepthWrite(this._savedDepthWrite),r&&r.needAlphaBlending&&this._engine.restoreStencilState()}},e.prototype._afterRenderingMesh=function(e,t,i){if(e.renderOverlay){var n=this._engine.getAlphaMode();this._engine.setAlphaMode(_.a.ALPHA_COMBINE),this.render(t,i,!0),this._engine.setAlphaMode(n)}e.renderOutline&&this._savedDepthWrite&&(this._engine.setDepthWrite(!0),this._engine.setColorWrite(!1),this.render(t,i),this._engine.setColorWrite(!0))},e._StencilReference=4,e}(),uu=i(110),hu=function(){function e(e,t){this.name=e,this.color=new o.f(1,1,1,1),this.width=1,this.height=1,this.angle=0,this.cellIndex=0,this.invertU=0,this.invertV=0,this.animations=new Array,this.isPickable=!1,this._animationStarted=!1,this._loopAnimation=!1,this._fromIndex=0,this._toIndex=0,this._delay=0,this._direction=1,this._time=0,this.isVisible=!0,this._manager=t,this._manager.sprites.push(this),this.position=o.x.Zero()}return Object.defineProperty(e.prototype,"size",{get:function(){return this.width},set:function(e){this.width=e,this.height=e},enumerable:!0,configurable:!0}),e.prototype.playAnimation=function(e,t,i,n,r){this._fromIndex=e,this._toIndex=t,this._loopAnimation=i,this._delay=n,this._animationStarted=!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._onAnimationEnd&&this._onAnimationEnd(),this.disposeWhenFinishedAnimating&&this.dispose()))))},e.prototype.dispose=function(){for(var e=0;e0)for(var o=0;o=r.distance))&&(r=a,i))break}}return r||new en.a},H.a.prototype.pickSprite=function(e,t,i,n,r){return this.createPickingRayInCameraSpaceToRef(e,t,this._tempSpritePickingRay,r),this._internalPickSprites(this._tempSpritePickingRay,i,n,r)},H.a.prototype.pickSpriteWithRay=function(e,t,i,n){if(!this._tempSpritePickingRay)return null;if(!n){if(!this.activeCamera)return null;n=this.activeCamera}return It.a.TransformToRef(e,n.getViewMatrix(),this._tempSpritePickingRay),this._internalPickSprites(this._tempSpritePickingRay,t,i,n)},H.a.prototype.setPointerOverSprite=function(e){this._pointerOverSprite!==e&&(this._pointerOverSprite&&this._pointerOverSprite.actionManager&&this._pointerOverSprite.actionManager.processTrigger(_.a.ACTION_OnPointerOutTrigger,c.a.CreateNewFromSprite(this._pointerOverSprite,this)),this._pointerOverSprite=e,this._pointerOverSprite&&this._pointerOverSprite.actionManager&&this._pointerOverSprite.actionManager.processTrigger(_.a.ACTION_OnPointerOverTrigger,c.a.CreateNewFromSprite(this._pointerOverSprite,this)))},H.a.prototype.getPointerOverSprite=function(){return this._pointerOverSprite};var du=function(){function e(e){this.name=xe.a.NAME_SPRITE,this.scene=e,this.scene.spriteManagers=new Array,this.scene._tempSpritePickingRay=It.a?It.a.Zero():null,this.scene.onBeforeSpritesRenderingObservable=new r.c,this.scene.onAfterSpritesRenderingObservable=new r.c,this._spritePredicate=function(e){return!!e.actionManager&&(e.isPickable&&e.actionManager.hasPointerTriggers)}}return e.prototype.register=function(){this.scene._pointerMoveStage.registerStep(xe.a.STEP_POINTERMOVE_SPRITE,this,this._pointerMove),this.scene._pointerDownStage.registerStep(xe.a.STEP_POINTERDOWN_SPRITE,this,this._pointerDown),this.scene._pointerUpStage.registerStep(xe.a.STEP_POINTERUP_SPRITE,this,this._pointerUp)},e.prototype.rebuild=function(){},e.prototype.dispose=function(){this.scene.onBeforeSpritesRenderingObservable.clear(),this.scene.onAfterSpritesRenderingObservable.clear();for(var e=this.scene.spriteManagers;e.length;)e[0].dispose()},e.prototype._pickSpriteButKeepRay=function(e,t,i,n,r){var o=this.scene.pickSprite(t,i,this._spritePredicate,n,r);return o&&(o.ray=e?e.ray:null),o},e.prototype._pointerMove=function(e,t,i,n,r){var o=this.scene;return n?o.setPointerOverSprite(null):(i=this._pickSpriteButKeepRay(i,e,t,!1,o.cameraToUseForPointers||void 0))&&i.hit&&i.pickedSprite?(o.setPointerOverSprite(i.pickedSprite),o._pointerOverSprite&&o._pointerOverSprite.actionManager&&o._pointerOverSprite.actionManager.hoverCursor?r.style.cursor=o._pointerOverSprite.actionManager.hoverCursor:r.style.cursor=o.hoverCursor):o.setPointerOverSprite(null),i},e.prototype._pointerDown=function(e,t,i,n){var r=this.scene;if(r._pickedDownSprite=null,r.spriteManagers.length>0&&(i=r.pickSprite(e,t,this._spritePredicate,!1,r.cameraToUseForPointers||void 0))&&i.hit&&i.pickedSprite&&i.pickedSprite.actionManager){switch(r._pickedDownSprite=i.pickedSprite,n.button){case 0:i.pickedSprite.actionManager.processTrigger(_.a.ACTION_OnLeftPickTrigger,c.a.CreateNewFromSprite(i.pickedSprite,r,n));break;case 1:i.pickedSprite.actionManager.processTrigger(_.a.ACTION_OnCenterPickTrigger,c.a.CreateNewFromSprite(i.pickedSprite,r,n));break;case 2:i.pickedSprite.actionManager.processTrigger(_.a.ACTION_OnRightPickTrigger,c.a.CreateNewFromSprite(i.pickedSprite,r,n))}i.pickedSprite.actionManager&&i.pickedSprite.actionManager.processTrigger(_.a.ACTION_OnPickDownTrigger,c.a.CreateNewFromSprite(i.pickedSprite,r,n))}return i},e.prototype._pointerUp=function(e,t,i,n){var r=this.scene;if(r.spriteManagers.length>0){var o=r.pickSprite(e,t,this._spritePredicate,!1,r.cameraToUseForPointers||void 0);o&&(o.hit&&o.pickedSprite&&o.pickedSprite.actionManager&&(o.pickedSprite.actionManager.processTrigger(_.a.ACTION_OnPickUpTrigger,c.a.CreateNewFromSprite(o.pickedSprite,r,n)),o.pickedSprite.actionManager&&(this.scene._inputManager._isPointerSwiping()||o.pickedSprite.actionManager.processTrigger(_.a.ACTION_OnPickTrigger,c.a.CreateNewFromSprite(o.pickedSprite,r,n)))),r._pickedDownSprite&&r._pickedDownSprite.actionManager&&r._pickedDownSprite!==o.pickedSprite&&r._pickedDownSprite.actionManager.processTrigger(_.a.ACTION_OnPickOutTrigger,c.a.CreateNewFromSprite(r._pickedDownSprite,r,n)))}return i},e}(),fu="uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest)\n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include\ngl_FragColor=color;\n}";zt.a.ShadersStore.spritesPixelShader=fu;var pu="\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include\nvoid main(void) {\nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz;\nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0);\n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}";zt.a.ShadersStore.spritesVertexShader=pu;var _u,mu=function(){function e(e,t,i,n,o,s,a){if(void 0===s&&(s=.01),void 0===a&&(a=Ge.a.TRILINEAR_SAMPLINGMODE),this.name=e,this.sprites=new Array,this.renderingGroupId=0,this.layerMask=268435455,this.fogEnabled=!0,this.isPickable=!1,this.onDisposeObservable=new r.c,this._vertexBuffers={},o._getComponent(xe.a.NAME_SPRITE)||o._addComponent(new du(o)),this._capacity=i,this._spriteTexture=new Ge.a(t,o,!0,!1,a),this._spriteTexture.wrapU=Ge.a.CLAMP_ADDRESSMODE,this._spriteTexture.wrapV=Ge.a.CLAMP_ADDRESSMODE,n.width&&n.height)this.cellWidth=n.width,this.cellHeight=n.height;else{if(void 0===n)return;this.cellWidth=n,this.cellHeight=n}this._epsilon=s,this._scene=o,this._scene.spriteManagers.push(this);for(var c=[],l=0,u=0;u>0;this._vertexData[o+10]=t.cellIndex-s*r,this._vertexData[o+11]=s,this._vertexData[o+12]=t.color.r,this._vertexData[o+13]=t.color.g,this._vertexData[o+14]=t.color.b,this._vertexData[o+15]=t.color.a},e.prototype.intersects=function(e,t,i,n){for(var r=Math.min(this._capacity,this.sprites.length),s=o.x.Zero(),a=o.x.Zero(),c=Number.MAX_VALUE,l=null,u=o.x.Zero(),h=o.x.Zero(),d=t.getViewMatrix(),f=0;f_&&(c=_,l=p,n))break}}}if(l){var m=new en.a;d.invertToRef(o.t.Matrix[0]),m.hit=!0,m.pickedSprite=l,m.distance=c;var g=o.t.Vector3[0];return g.copyFrom(e.direction),g.normalize(),g.scaleInPlace(c),e.origin.addToRef(g,u),m.pickedPoint=o.x.TransformCoordinates(u,o.t.Matrix[0]),m}return null},e.prototype.render=function(){if(this._effectBase.isReady()&&this._effectFog.isReady()&&this._spriteTexture&&this._spriteTexture.isReady()&&this.sprites.length){for(var e=this._scene.getEngine(),t=this._spriteTexture.getBaseSize(),i=e.getDeltaTime(),n=Math.min(this._capacity,this.sprites.length),r=t.width/this.cellWidth,o=0,s=!0,a=0;a-1&&this._tasks.splice(t,1)},e.prototype._decreaseWaitingTasksCount=function(e){this._waitingTasksCount--;try{this.onProgress&&this.onProgress(this._waitingTasksCount,this._totalTasksCount,e),this.onProgressObservable.notifyObservers(new Tu(this._waitingTasksCount,this._totalTasksCount,e))}catch(e){p.a.Error("Error running progress callbacks."),console.log(e)}if(0===this._waitingTasksCount){try{this.onFinish&&this.onFinish(this._tasks);for(var t=this._tasks.slice(),i=0,n=t;i-1&&this._tasks.splice(r,1)}}this.onTasksDoneObservable.notifyObservers(this._tasks)}catch(e){p.a.Error("Error running tasks-done callbacks."),console.log(e)}this._isLoading=!1,this._scene.getEngine().hideLoadingUI()}},e.prototype._runTask=function(e){var t=this,i=function(i,n){e._setErrorObject(i,n),t.onTaskError&&t.onTaskError(e),t.onTaskErrorObservable.notifyObservers(e),t._decreaseWaitingTasksCount(e)};e.run(this._scene,function(){try{t.onTaskSuccess&&t.onTaskSuccess(e),t.onTaskSuccessObservable.notifyObservers(e),t._decreaseWaitingTasksCount(e)}catch(e){i("Error executing task success callbacks",e)}},i)},e.prototype.reset=function(){return this._isLoading=!1,this._tasks=new Array,this},e.prototype.load=function(){if(this._isLoading)return this;if(this._isLoading=!0,this._waitingTasksCount=this._tasks.length,this._totalTasksCount=this._tasks.length,0===this._waitingTasksCount)return this._isLoading=!1,this.onFinish&&this.onFinish(this._tasks),this.onTasksDoneObservable.notifyObservers(this._tasks),this;this.useDefaultLoadingScreen&&this._scene.getEngine().displayLoadingUI();for(var e=0;e=0&&this._meshes.splice(i,1),this._centerPosition=this._centerMesh.getAbsolutePosition().clone();for(var n=0;n0&&this._textureLoadingCallback(e)}this._currentScene.render()}},e.prototype.drag=function(e){e.stopPropagation(),e.preventDefault()},e.prototype.drop=function(e){e.stopPropagation(),e.preventDefault(),this.loadFiles(e)},e.prototype._traverseFolder=function(e,t,i,n){var r=this,o=e.createReader(),s=e.fullPath.replace(/^\//,"").replace(/(.+?)\/?$/,"$1/");o.readEntries(function(e){i.count+=e.length;for(var o=0,a=e;o0)){for(var i=new Array,n=[],r=e.dataTransfer?e.dataTransfer.items:null,o=0;o0&&p.a.ClearLogCache(),this._engine.stopRenderLoop()),Un.LoadAsync("file:",this._sceneFileToLoad,this._engine,function(t){e._progressCallback&&e._progressCallback(t)}).then(function(t){e._currentScene&&e._currentScene.dispose(),e._currentScene=t,e._sceneLoadedCallback&&e._sceneLoadedCallback(e._sceneFileToLoad,e._currentScene),e._currentScene.executeWhenReady(function(){e._engine.runRenderLoop(function(){e.renderFunction()})})}).catch(function(t){e._errorCallback&&e._errorCallback(e._sceneFileToLoad,e._currentScene,t.message)})):p.a.Error("Please provide a valid .babylon file.")},e}(),wu=i(106),Fu=i(107),Nu=function(){function e(e){void 0===e&&(e=0),this.priority=e}return e.prototype.getDescription=function(){return""},e.prototype.apply=function(e,t){return!0},e}(),Bu=function(e){function t(t,i,n){void 0===t&&(t=0),void 0===i&&(i=1024),void 0===n&&(n=.5);var r=e.call(this,t)||this;return r.priority=t,r.maximumSize=i,r.step=n,r}return l.d(t,e),t.prototype.getDescription=function(){return"Reducing render target texture size to "+this.maximumSize},t.prototype.apply=function(e,t){for(var i=!0,n=0;nthis.maximumSize&&(r.scale(this.step),i=!1)}}return i},t}(Nu),Uu=function(e){function t(t,i,n){void 0===t&&(t=0),void 0===i&&(i=2),void 0===n&&(n=.25);var r=e.call(this,t)||this;return r.priority=t,r.maximumScale=i,r.step=n,r._currentScale=-1,r._directionOffset=1,r}return l.d(t,e),t.prototype.getDescription=function(){return"Setting hardware scaling level to "+this._currentScale},t.prototype.apply=function(e,t){return-1===this._currentScale&&(this._currentScale=e.getEngine().getHardwareScalingLevel(),this._currentScale>this.maximumScale&&(this._directionOffset=-1)),this._currentScale+=this._directionOffset*this.step,e.getEngine().setHardwareScalingLevel(this._currentScale),1===this._directionOffset?this._currentScale>=this.maximumScale:this._currentScale<=this.maximumScale},t}(Nu),Vu=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return l.d(t,e),t.prototype.getDescription=function(){return"Turning shadows on/off"},t.prototype.apply=function(e,t){return e.shadowsEnabled=t.isInImprovementMode,!0},t}(Nu),ku=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return l.d(t,e),t.prototype.getDescription=function(){return"Turning post-processes on/off"},t.prototype.apply=function(e,t){return e.postProcessesEnabled=t.isInImprovementMode,!0},t}(Nu),Gu=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return l.d(t,e),t.prototype.getDescription=function(){return"Turning lens flares on/off"},t.prototype.apply=function(e,t){return e.lensFlaresEnabled=t.isInImprovementMode,!0},t}(Nu),zu=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return l.d(t,e),t.prototype.getDescription=function(){return this.onGetDescription?this.onGetDescription():"Running user defined callback"},t.prototype.apply=function(e,t){return!this.onApply||this.onApply(e,t)},t}(Nu),ju=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return l.d(t,e),t.prototype.getDescription=function(){return"Turning particles on/off"},t.prototype.apply=function(e,t){return e.particlesEnabled=t.isInImprovementMode,!0},t}(Nu),Wu=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return l.d(t,e),t.prototype.getDescription=function(){return"Turning render targets off"},t.prototype.apply=function(e,t){return e.renderTargetsEnabled=t.isInImprovementMode,!0},t}(Nu),Hu=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t._canBeMerged=function(e){if(!(e instanceof fe.a))return!1;var t=e;return!t.isDisposed()&&(!(!t.isVisible||!t.isEnabled())&&(!(t.instances.length>0)&&(!t.skeleton&&!t.hasLODLevels)))},t}return l.d(t,e),Object.defineProperty(t,"UpdateSelectionTree",{get:function(){return t._UpdateSelectionTree},set:function(e){t._UpdateSelectionTree=e},enumerable:!0,configurable:!0}),t.prototype.getDescription=function(){return"Merging similar meshes together"},t.prototype.apply=function(e,i,n){for(var r=e.meshes.slice(0),o=r.length,s=0;s=this._targetFrameRate)return this._isRunning=!1,void this.onSuccessObservable.notifyObservers(this);for(var n=!0,r=!0,o=0;o0){o.animationGroups=[];for(var h=0;h0)for(o.reflectionProbes=[],i=0;i0&&setTimeout(function(){i.stopRecording()},1e3*t),this._fileName=e,this._recordedChunks=[],this._resolve=null,this._reject=null,this._canvas.isRecording=!0,this._mediaRecorder.start(this._options.recordChunckSize),new Promise(function(e,t){i._resolve=e,i._reject=t})},e.prototype.dispose=function(){this._canvas=null,this._mediaRecorder=null,this._recordedChunks=[],this._fileName=null,this._resolve=null,this._reject=null},e.prototype._handleDataAvailable=function(e){e.data.size>0&&this._recordedChunks.push(e.data)},e.prototype._handleError=function(e){if(this.stopRecording(),!this._reject)throw new e.error;this._reject(e.error)},e.prototype._handleStop=function(){this.stopRecording();var e=new Blob(this._recordedChunks);this._resolve&&this._resolve(e),window.URL.createObjectURL(e),this._fileName&&ye.h.Download(e,this._fileName)},e._defaultOptions={mimeType:"video/webm",fps:25,recordChunckSize:3e3},e}(),th=function(){function e(){}return e.CreateScreenshot=function(e,t,i,n,r){var o,s;if(void 0===r&&(r="image/png"),i.precision)o=Math.round(e.getRenderWidth()*i.precision),s=Math.round(o/e.getAspectRatio(t));else if(i.width&&i.height)o=i.width,s=i.height;else if(i.width&&!i.height)o=i.width,s=Math.round(o/e.getAspectRatio(t));else if(i.height&&!i.width)s=i.height,o=Math.round(s*e.getAspectRatio(t));else{if(isNaN(i))return void p.a.Error("Invalid 'size' parameter !");s=i,o=i}ye.h._ScreenshotCanvas||(ye.h._ScreenshotCanvas=document.createElement("canvas")),ye.h._ScreenshotCanvas.width=o,ye.h._ScreenshotCanvas.height=s;var a=ye.h._ScreenshotCanvas.getContext("2d"),c=e.getRenderWidth()/e.getRenderHeight(),l=o,u=l/c;u>s&&(l=(u=s)*c);var h=Math.max(0,o-l)/2,d=Math.max(0,s-u)/2,f=e.getRenderingCanvas();a&&f&&a.drawImage(f,h,d,l,u),ye.h.EncodeScreenshotCanvasData(n,r)},e.CreateScreenshotUsingRenderTarget=function(e,t,i,n,r,o,s,a){var c,l;if(void 0===r&&(r="image/png"),void 0===o&&(o=1),void 0===s&&(s=!1),i.precision)c=Math.round(e.getRenderWidth()*i.precision),l=Math.round(c/e.getAspectRatio(t)),i={width:c,height:l};else if(i.width&&i.height)c=i.width,l=i.height;else if(i.width&&!i.height)c=i.width,l=Math.round(c/e.getAspectRatio(t)),i={width:c,height:l};else if(i.height&&!i.width)l=i.height,i={width:c=Math.round(l*e.getAspectRatio(t)),height:l};else{if(isNaN(i))return void p.a.Error("Invalid 'size' parameter !");l=i,c=i}var u=t.getScene(),h=null;u.activeCamera!==t&&(h=u.activeCamera,u.activeCamera=t);var d=e.getRenderingCanvas();if(d){var f={width:d.width,height:d.height};e.setSize(c,l),u.render();var m=new _i("screenShot",i,u,!1,!1,_.a.TEXTURETYPE_UNSIGNED_INT,!1,Ge.a.NEAREST_SAMPLINGMODE);m.renderList=null,m.samples=o,s&&m.addPostProcess(new ml("antialiasing",1,u.activeCamera)),m.onAfterRenderObservable.add(function(){ye.h.DumpFramebuffer(c,l,e,n,r,a)}),u.incrementRenderId(),u.resetCachedMaterial(),m.render(!0),m.dispose(),h&&(u.activeCamera=h),e.setSize(f.width,f.height),t.getProjectionMatrix(!0)}else p.a.Error("No rendering canvas found !")},e}();ye.h.CreateScreenshot=th.CreateScreenshot,ye.h.CreateScreenshotUsingRenderTarget=th.CreateScreenshotUsingRenderTarget,function(e){e[e.Checkbox=0]="Checkbox",e[e.Slider=1]="Slider",e[e.Vector3=2]="Vector3",e[e.Quaternion=3]="Quaternion",e[e.Color3=4]="Color3"}(yu||(yu={})),i.d(t,"AbstractScene",function(){return n.a}),i.d(t,"Action",function(){return a}),i.d(t,"ActionEvent",function(){return c.a}),i.d(t,"ActionManager",function(){return C}),i.d(t,"Condition",function(){return u}),i.d(t,"ValueCondition",function(){return h}),i.d(t,"PredicateCondition",function(){return d}),i.d(t,"StateCondition",function(){return f}),i.d(t,"SwitchBooleanAction",function(){return m}),i.d(t,"SetStateAction",function(){return g}),i.d(t,"SetValueAction",function(){return v}),i.d(t,"IncrementValueAction",function(){return y}),i.d(t,"PlayAnimationAction",function(){return b}),i.d(t,"StopAnimationAction",function(){return T}),i.d(t,"DoNothingAction",function(){return E}),i.d(t,"CombineAction",function(){return x}),i.d(t,"ExecuteCodeAction",function(){return A}),i.d(t,"SetParentAction",function(){return P}),i.d(t,"PlaySoundAction",function(){return M}),i.d(t,"StopSoundAction",function(){return O}),i.d(t,"InterpolateValueAction",function(){return U}),i.d(t,"Animatable",function(){return Q}),i.d(t,"_IAnimationState",function(){return N}),i.d(t,"Animation",function(){return B}),i.d(t,"TargetedAnimation",function(){return q}),i.d(t,"AnimationGroup",function(){return Z}),i.d(t,"AnimationPropertiesOverride",function(){return J}),i.d(t,"EasingFunction",function(){return $}),i.d(t,"CircleEase",function(){return ee}),i.d(t,"BackEase",function(){return te}),i.d(t,"BounceEase",function(){return ie}),i.d(t,"CubicEase",function(){return ne}),i.d(t,"ElasticEase",function(){return re}),i.d(t,"ExponentialEase",function(){return oe}),i.d(t,"PowerEase",function(){return se}),i.d(t,"QuadraticEase",function(){return ae}),i.d(t,"QuarticEase",function(){return ce}),i.d(t,"QuinticEase",function(){return le}),i.d(t,"SineEase",function(){return ue}),i.d(t,"BezierCurveEase",function(){return he}),i.d(t,"RuntimeAnimation",function(){return W}),i.d(t,"AnimationEvent",function(){return de}),i.d(t,"AnimationKeyInterpolation",function(){return I}),i.d(t,"AnimationRange",function(){return w}),i.d(t,"KeepAssets",function(){return pe}),i.d(t,"AssetContainer",function(){return _e}),i.d(t,"Analyser",function(){return ge}),i.d(t,"AudioEngine",function(){return ve}),i.d(t,"AudioSceneComponent",function(){return Ae}),i.d(t,"Sound",function(){return Te}),i.d(t,"SoundTrack",function(){return Ee}),i.d(t,"WeightedSound",function(){return Pe}),i.d(t,"AutoRotationBehavior",function(){return Se}),i.d(t,"BouncingBehavior",function(){return Ce}),i.d(t,"FramingBehavior",function(){return Me}),i.d(t,"AttachToBoxBehavior",function(){return Ie}),i.d(t,"FadeInOutBehavior",function(){return De}),i.d(t,"MultiPointerScaleBehavior",function(){return we}),i.d(t,"PointerDragBehavior",function(){return Le.a}),i.d(t,"SixDofDragBehavior",function(){return Ue}),i.d(t,"Bone",function(){return K}),i.d(t,"BoneIKController",function(){return Ve}),i.d(t,"BoneLookController",function(){return ke}),i.d(t,"Skeleton",function(){return We}),i.d(t,"CameraInputTypes",function(){return He}),i.d(t,"CameraInputsManager",function(){return Xe}),i.d(t,"Camera",function(){return Ne.a}),i.d(t,"TargetCamera",function(){return yt}),i.d(t,"FreeCamera",function(){return bt}),i.d(t,"FreeCameraInputsManager",function(){return dt}),i.d(t,"TouchCamera",function(){return Tt}),i.d(t,"ArcRotateCamera",function(){return Et}),i.d(t,"ArcRotateCameraInputsManager",function(){return it}),i.d(t,"DeviceOrientationCamera",function(){return xt}),i.d(t,"FlyCamera",function(){return Pt}),i.d(t,"FlyCameraInputsManager",function(){return At}),i.d(t,"FollowCamera",function(){return Ct}),i.d(t,"ArcFollowCamera",function(){return Mt}),i.d(t,"GamepadCamera",function(){return kt}),i.d(t,"UniversalCamera",function(){return Vt}),i.d(t,"VirtualJoysticksCamera",function(){return ai}),i.d(t,"ArcRotateCameraGamepadInput",function(){return qe}),i.d(t,"ArcRotateCameraKeyboardMoveInput",function(){return Je}),i.d(t,"ArcRotateCameraMouseWheelInput",function(){return $e}),i.d(t,"ArcRotateCameraPointersInput",function(){return tt}),i.d(t,"ArcRotateCameraVRDeviceOrientationInput",function(){return nt}),i.d(t,"FlyCameraKeyboardInput",function(){return rt}),i.d(t,"FlyCameraMouseInput",function(){return ot}),i.d(t,"FollowCameraKeyboardMoveInput",function(){return st}),i.d(t,"FollowCameraMouseWheelInput",function(){return at}),i.d(t,"FollowCameraPointersInput",function(){return ct}),i.d(t,"FreeCameraDeviceOrientationInput",function(){return ft}),i.d(t,"FreeCameraGamepadInput",function(){return pt}),i.d(t,"FreeCameraKeyboardMoveInput",function(){return lt}),i.d(t,"FreeCameraMouseInput",function(){return ut}),i.d(t,"FreeCameraTouchInput",function(){return ht}),i.d(t,"FreeCameraVirtualJoystickInput",function(){return vt}),i.d(t,"AnaglyphArcRotateCamera",function(){return Zt}),i.d(t,"AnaglyphFreeCamera",function(){return Jt}),i.d(t,"AnaglyphGamepadCamera",function(){return $t}),i.d(t,"AnaglyphUniversalCamera",function(){return ei}),i.d(t,"StereoscopicArcRotateCamera",function(){return ni}),i.d(t,"StereoscopicFreeCamera",function(){return ri}),i.d(t,"StereoscopicGamepadCamera",function(){return oi}),i.d(t,"StereoscopicUniversalCamera",function(){return si}),i.d(t,"VRCameraMetrics",function(){return ci}),i.d(t,"VRDeviceOrientationArcRotateCamera",function(){return vi}),i.d(t,"VRDeviceOrientationFreeCamera",function(){return yi}),i.d(t,"VRDeviceOrientationGamepadCamera",function(){return bi}),i.d(t,"OnAfterEnteringVRObservableEvent",function(){return Vi}),i.d(t,"VRExperienceHelper",function(){return ki}),i.d(t,"WebVRFreeCamera",function(){return Ei}),i.d(t,"WebXRCamera",function(){return Gi}),i.d(t,"WebXREnterExitUIButton",function(){return Hi}),i.d(t,"WebXREnterExitUIOptions",function(){return Xi}),i.d(t,"WebXREnterExitUI",function(){return Yi}),i.d(t,"WebXRState",function(){return Li}),i.d(t,"WebXRExperienceHelper",function(){return Wi}),i.d(t,"WebXRController",function(){return Ki}),i.d(t,"WebXRInput",function(){return Qi}),i.d(t,"WebXRManagedOutputCanvas",function(){return qi}),i.d(t,"WebXRSessionManager",function(){return zi}),i.d(t,"Collider",function(){return Ji}),i.d(t,"DefaultCollisionCoordinator",function(){return $i}),i.d(t,"PickingInfo",function(){return en.a}),i.d(t,"IntersectionInfo",function(){return tn.a}),i.d(t,"_MeshCollisionData",function(){return nn.a}),i.d(t,"BoundingBox",function(){return rn.a}),i.d(t,"BoundingInfo",function(){return on.a}),i.d(t,"BoundingSphere",function(){return sn.a}),i.d(t,"Ray",function(){return It.a}),i.d(t,"Octree",function(){return cn}),i.d(t,"OctreeBlock",function(){return an}),i.d(t,"OctreeSceneComponent",function(){return ln}),i.d(t,"AxesViewer",function(){return un.AxesViewer}),i.d(t,"BoneAxesViewer",function(){return un.BoneAxesViewer}),i.d(t,"DebugLayer",function(){return un.DebugLayer}),i.d(t,"PhysicsViewer",function(){return un.PhysicsViewer}),i.d(t,"RayHelper",function(){return un.RayHelper}),i.d(t,"SkeletonViewer",function(){return un.SkeletonViewer}),i.d(t,"Constants",function(){return _.a}),i.d(t,"InstancingAttributeInfo",function(){return me.d}),i.d(t,"DepthTextureCreationOptions",function(){return me.a}),i.d(t,"EngineCapabilities",function(){return me.c}),i.d(t,"Engine",function(){return me.b}),i.d(t,"EngineStore",function(){return R.a}),i.d(t,"NullEngineOptions",function(){return hn.b}),i.d(t,"NullEngine",function(){return hn.a}),i.d(t,"WebGLPipelineContext",function(){return pn.a}),i.d(t,"WebGL2ShaderProcessor",function(){return _n.a}),i.d(t,"NativeEngineOptions",function(){return In}),i.d(t,"NativeEngine",function(){return Dn}),i.d(t,"_OcclusionDataStorage",function(){return fn}),i.d(t,"_forceTransformFeedbackToBundle",function(){return!0}),i.d(t,"KeyboardEventTypes",function(){return Ze.a}),i.d(t,"KeyboardInfo",function(){return Ze.b}),i.d(t,"KeyboardInfoPre",function(){return Ze.c}),i.d(t,"PointerEventTypes",function(){return Re.a}),i.d(t,"PointerInfoBase",function(){return Re.c}),i.d(t,"PointerInfoPre",function(){return Re.d}),i.d(t,"PointerInfo",function(){return Re.b}),i.d(t,"ClipboardEventTypes",function(){return Ln}),i.d(t,"ClipboardInfo",function(){return wn}),i.d(t,"StickValues",function(){return Ye}),i.d(t,"Gamepad",function(){return Ke}),i.d(t,"GenericPad",function(){return Qe}),i.d(t,"GamepadManager",function(){return Bt}),i.d(t,"GamepadSystemSceneComponent",function(){return Ut}),i.d(t,"Xbox360Button",function(){return Dt}),i.d(t,"Xbox360Dpad",function(){return Lt}),i.d(t,"Xbox360Pad",function(){return Nt}),i.d(t,"DaydreamController",function(){return Vn}),i.d(t,"GearVRController",function(){return kn}),i.d(t,"GenericController",function(){return Gn}),i.d(t,"OculusTouchController",function(){return zn}),i.d(t,"PoseEnabledControllerType",function(){return St}),i.d(t,"PoseEnabledControllerHelper",function(){return wt}),i.d(t,"PoseEnabledController",function(){return Ft}),i.d(t,"ViveController",function(){return jn}),i.d(t,"WebVRController",function(){return xi}),i.d(t,"WindowsMotionController",function(){return Hn}),i.d(t,"AxisDragGizmo",function(){return Xn.a}),i.d(t,"AxisScaleGizmo",function(){return qn}),i.d(t,"BoundingBoxGizmo",function(){return $n}),i.d(t,"Gizmo",function(){return Kn.a}),i.d(t,"GizmoManager",function(){return cr}),i.d(t,"PlaneRotationGizmo",function(){return er}),i.d(t,"PositionGizmo",function(){return or}),i.d(t,"RotationGizmo",function(){return tr}),i.d(t,"ScaleGizmo",function(){return ar}),i.d(t,"LightGizmo",function(){return pr}),i.d(t,"EnvironmentHelper",function(){return Lr}),i.d(t,"PhotoDome",function(){return wr}),i.d(t,"_forceSceneHelpersToBundle",function(){return!0}),i.d(t,"VideoDome",function(){return vo}),i.d(t,"EngineInstrumentation",function(){return yo}),i.d(t,"SceneInstrumentation",function(){return bo}),i.d(t,"_TimeToken",function(){return dn}),i.d(t,"EffectLayer",function(){return Ao}),i.d(t,"EffectLayerSceneComponent",function(){return Po}),i.d(t,"GlowLayer",function(){return Co}),i.d(t,"HighlightLayer",function(){return Io}),i.d(t,"Layer",function(){return Fo}),i.d(t,"LayerSceneComponent",function(){return Do}),i.d(t,"LensFlare",function(){return No}),i.d(t,"LensFlareSystem",function(){return Vo}),i.d(t,"LensFlareSystemSceneComponent",function(){return ko}),i.d(t,"Light",function(){return lr.a}),i.d(t,"ShadowLight",function(){return ur}),i.d(t,"DirectionalLight",function(){return hr}),i.d(t,"HemisphericLight",function(){return Ti.a}),i.d(t,"PointLight",function(){return Xo}),i.d(t,"SpotLight",function(){return fr}),i.d(t,"ShadowGenerator",function(){return Wo}),i.d(t,"ShadowGeneratorSceneComponent",function(){return Ho}),i.d(t,"DefaultLoadingScreen",function(){return Yo}),i.d(t,"SceneLoaderProgressEvent",function(){return Bn}),i.d(t,"SceneLoader",function(){return Un}),i.d(t,"SceneLoaderFlags",function(){return Nn.a}),i.d(t,"_BabylonLoaderRegistered",function(){return!0}),i.d(t,"ColorCurves",function(){return ms.a}),i.d(t,"EffectFallbacks",function(){return zt.c}),i.d(t,"EffectCreationOptions",function(){return zt.b}),i.d(t,"Effect",function(){return zt.a}),i.d(t,"FresnelParameters",function(){return gs}),i.d(t,"ImageProcessingConfigurationDefines",function(){return Ai.b}),i.d(t,"ImageProcessingConfiguration",function(){return Ai.a}),i.d(t,"Material",function(){return To.a}),i.d(t,"MaterialDefines",function(){return xr.a}),i.d(t,"MaterialHelper",function(){return Er.a}),i.d(t,"MultiMaterial",function(){return Qo.a}),i.d(t,"PBRMaterialDefines",function(){return io}),i.d(t,"PBRBaseMaterial",function(){return no}),i.d(t,"PBRMaterial",function(){return ro}),i.d(t,"PushMaterial",function(){return Ar.a}),i.d(t,"ShaderMaterial",function(){return Ts.a}),i.d(t,"StandardMaterialDefines",function(){return Pi.b}),i.d(t,"StandardMaterial",function(){return Pi.a}),i.d(t,"BaseTexture",function(){return vn.a}),i.d(t,"CubeTexture",function(){return Tr}),i.d(t,"DynamicTexture",function(){return Ri}),i.d(t,"EquiRectangularCubeTexture",function(){return xs}),i.d(t,"HDRCubeTexture",function(){return Jo}),i.d(t,"InternalTexture",function(){return ze.a}),i.d(t,"MirrorTexture",function(){return br}),i.d(t,"MultiRenderTarget",function(){return Rs}),i.d(t,"RenderTargetTexture",function(){return _i}),i.d(t,"Texture",function(){return Ge.a}),i.d(t,"VideoTexture",function(){return go}),i.d(t,"UniformBuffer",function(){return di.a}),i.d(t,"MaterialFlags",function(){return Pr.a}),i.d(t,"BackgroundMaterial",function(){return Dr}),i.d(t,"PBRBaseSimpleMaterial",function(){return vs}),i.d(t,"PBRMetallicRoughnessMaterial",function(){return ys}),i.d(t,"PBRSpecularGlossinessMaterial",function(){return bs}),i.d(t,"ColorGradingTexture",function(){return Es}),i.d(t,"_DDSTextureLoader",function(){return fo}),i.d(t,"_ENVTextureLoader",function(){return po}),i.d(t,"_KTXTextureLoader",function(){return mo}),i.d(t,"ProceduralTexture",function(){return Ms}),i.d(t,"RawCubeTexture",function(){return Us}),i.d(t,"RawTexture",function(){return je}),i.d(t,"RawTexture3D",function(){return Vs}),i.d(t,"RefractionTexture",function(){return ks}),i.d(t,"HtmlElementTexture",function(){return Gs}),i.d(t,"NodeMaterialBlockTargets",function(){return ws}),i.d(t,"NodeMaterialBlockConnectionPointTypes",function(){return Fs}),i.d(t,"NodeMaterialConnectionPoint",function(){return zs}),i.d(t,"NodeMaterialBlock",function(){return js}),i.d(t,"NodeMaterialDefines",function(){return Qs}),i.d(t,"NodeMaterial",function(){return qs}),i.d(t,"NodeMaterialWellKnownValues",function(){return Ns}),i.d(t,"_TGATextureLoader",function(){return Ps}),i.d(t,"CustomProceduralTexture",function(){return Is}),i.d(t,"NoiseProceduralTexture",function(){return Ls}),i.d(t,"ProceduralTextureSceneComponent",function(){return Ss}),i.d(t,"MultiplyBlock",function(){return ca}),i.d(t,"AddBlock",function(){return la}),i.d(t,"ClampBlock",function(){return ua}),i.d(t,"Vector2TransformBlock",function(){return ha}),i.d(t,"Vector3TransformBlock",function(){return da}),i.d(t,"Vector4TransformBlock",function(){return Xs}),i.d(t,"MatrixMultiplicationBlock",function(){return fa}),i.d(t,"NodeMaterialOptimizer",function(){return pa}),i.d(t,"VertexOutputBlock",function(){return Ys}),i.d(t,"BonesBlock",function(){return Zs}),i.d(t,"InstancesBlock",function(){return Js}),i.d(t,"MorphTargetsBlock",function(){return $s}),i.d(t,"FragmentOutputBlock",function(){return Ks}),i.d(t,"AlphaTestBlock",function(){return ea}),i.d(t,"RGBAMergerBlock",function(){return ta}),i.d(t,"RGBMergerBlock",function(){return ia}),i.d(t,"RGBASplitterBlock",function(){return na}),i.d(t,"RGBSplitterBlock",function(){return ra}),i.d(t,"TextureBlock",function(){return oa}),i.d(t,"ImageProcessingBlock",function(){return sa}),i.d(t,"FogBlock",function(){return aa}),i.d(t,"Scalar",function(){return D.a}),i.d(t,"ToGammaSpace",function(){return o.u}),i.d(t,"ToLinearSpace",function(){return o.v}),i.d(t,"Epsilon",function(){return o.h}),i.d(t,"Color3",function(){return o.e}),i.d(t,"Color4",function(){return o.f}),i.d(t,"Vector2",function(){return o.w}),i.d(t,"Vector3",function(){return o.x}),i.d(t,"Vector4",function(){return o.y}),i.d(t,"Size",function(){return o.r}),i.d(t,"Quaternion",function(){return o.q}),i.d(t,"Matrix",function(){return o.j}),i.d(t,"Plane",function(){return o.n}),i.d(t,"Viewport",function(){return o.z}),i.d(t,"Frustum",function(){return o.i}),i.d(t,"Space",function(){return o.s}),i.d(t,"Axis",function(){return o.c}),i.d(t,"BezierCurve",function(){return o.d}),i.d(t,"Orientation",function(){return o.k}),i.d(t,"Angle",function(){return o.a}),i.d(t,"Arc2",function(){return o.b}),i.d(t,"Path2",function(){return o.l}),i.d(t,"Path3D",function(){return o.m}),i.d(t,"Curve3",function(){return o.g}),i.d(t,"PositionNormalVertex",function(){return o.p}),i.d(t,"PositionNormalTextureVertex",function(){return o.o}),i.d(t,"Tmp",function(){return o.t}),i.d(t,"SphericalHarmonics",function(){return gn.a}),i.d(t,"SphericalPolynomial",function(){return gn.b}),i.d(t,"AbstractMesh",function(){return Fe.a}),i.d(t,"Buffer",function(){return Oi.a}),i.d(t,"VertexBuffer",function(){return Oi.b}),i.d(t,"CSG",function(){return Sa}),i.d(t,"Geometry",function(){return Ko.a}),i.d(t,"GroundMesh",function(){return Ii}),i.d(t,"TrailMesh",function(){return Ca}),i.d(t,"InstancedMesh",function(){return Ma.a}),i.d(t,"LinesMesh",function(){return Oa.b}),i.d(t,"InstancedLinesMesh",function(){return Oa.a}),i.d(t,"_CreationDataStorage",function(){return fe.b}),i.d(t,"_InstancesBatch",function(){return fe.c}),i.d(t,"Mesh",function(){return fe.a}),i.d(t,"VertexData",function(){return Mi.a}),i.d(t,"MeshBuilder",function(){return Ha}),i.d(t,"SimplificationSettings",function(){return Xa}),i.d(t,"SimplificationQueue",function(){return Ya}),i.d(t,"SimplificationType",function(){return ja}),i.d(t,"SimplicationQueueSceneComponent",function(){return $a}),i.d(t,"Polygon",function(){return Na}),i.d(t,"PolygonMeshBuilder",function(){return Ba}),i.d(t,"BaseSubMesh",function(){return Ta.a}),i.d(t,"SubMesh",function(){return Ta.b}),i.d(t,"MeshLODLevel",function(){return ec.a}),i.d(t,"TransformNode",function(){return ir.a}),i.d(t,"BoxBuilder",function(){return Yn.a}),i.d(t,"SphereBuilder",function(){return Zn.a}),i.d(t,"CylinderBuilder",function(){return Fi.a}),i.d(t,"TorusBuilder",function(){return wi}),i.d(t,"LinesBuilder",function(){return Jn.a}),i.d(t,"PlaneBuilder",function(){return nr.a}),i.d(t,"GroundBuilder",function(){return Di}),i.d(t,"DataBuffer",function(){return mn.a}),i.d(t,"WebGLDataBuffer",function(){return tc.a}),i.d(t,"DracoCompression",function(){return ba}),i.d(t,"TiledBoxBuilder",function(){return Da}),i.d(t,"DiscBuilder",function(){return Ia}),i.d(t,"RibbonBuilder",function(){return as}),i.d(t,"HemisphereBuilder",function(){return dr}),i.d(t,"TorusKnotBuilder",function(){return La}),i.d(t,"PolygonBuilder",function(){return Ua}),i.d(t,"ShapeBuilder",function(){return cs}),i.d(t,"LatheBuilder",function(){return Va}),i.d(t,"TiledPlaneBuilder",function(){return ka}),i.d(t,"TubeBuilder",function(){return Ga}),i.d(t,"PolyhedronBuilder",function(){return sr}),i.d(t,"IcoSphereBuilder",function(){return za}),i.d(t,"DecalBuilder",function(){return Wa}),i.d(t,"MorphTarget",function(){return $o}),i.d(t,"MorphTargetManager",function(){return es}),i.d(t,"Node",function(){return F.a}),i.d(t,"Database",function(){return nc}),i.d(t,"BaseParticleSystem",function(){return dc}),i.d(t,"GPUParticleSystem",function(){return xc}),i.d(t,"Particle",function(){return fc}),i.d(t,"ParticleHelper",function(){return Pc}),i.d(t,"ParticleSystem",function(){return gc}),i.d(t,"_IDoNeedToBeInTheBuild",function(){return 42}),i.d(t,"ParticleSystemSet",function(){return Ac}),i.d(t,"SolidParticle",function(){return Rc}),i.d(t,"ModelShape",function(){return Sc}),i.d(t,"DepthSortedParticle",function(){return Cc}),i.d(t,"SolidParticleSystem",function(){return Oc}),i.d(t,"SubEmitterType",function(){return ic}),i.d(t,"SubEmitter",function(){return pc}),i.d(t,"BoxParticleEmitter",function(){return rc}),i.d(t,"ConeParticleEmitter",function(){return oc}),i.d(t,"CylinderParticleEmitter",function(){return sc}),i.d(t,"CylinderDirectedParticleEmitter",function(){return ac}),i.d(t,"HemisphericParticleEmitter",function(){return cc}),i.d(t,"PointParticleEmitter",function(){return lc}),i.d(t,"SphereParticleEmitter",function(){return uc}),i.d(t,"SphereDirectedParticleEmitter",function(){return hc}),i.d(t,"PhysicsEngine",function(){return ns}),i.d(t,"PhysicsEngineSceneComponent",function(){return Lc}),i.d(t,"PhysicsHelper",function(){return wc}),i.d(t,"PhysicsRadialExplosionEventOptions",function(){return Vc}),i.d(t,"PhysicsUpdraftEventOptions",function(){return kc}),i.d(t,"PhysicsVortexEventOptions",function(){return Gc}),i.d(t,"PhysicsRadialImpulseFalloff",function(){return Ic}),i.d(t,"PhysicsUpdraftMode",function(){return Dc}),i.d(t,"PhysicsImpostor",function(){return ts.a}),i.d(t,"PhysicsJoint",function(){return is.e}),i.d(t,"DistanceJoint",function(){return is.a}),i.d(t,"MotorEnabledJoint",function(){return is.d}),i.d(t,"HingeJoint",function(){return is.c}),i.d(t,"Hinge2Joint",function(){return is.b}),i.d(t,"CannonJSPlugin",function(){return os}),i.d(t,"AmmoJSPlugin",function(){return ls}),i.d(t,"OimoJSPlugin",function(){return ss}),i.d(t,"AnaglyphPostProcess",function(){return qt}),i.d(t,"BlackAndWhitePostProcess",function(){return jc}),i.d(t,"BloomEffect",function(){return Qc}),i.d(t,"BloomMergePostProcess",function(){return Kc}),i.d(t,"BlurPostProcess",function(){return yr}),i.d(t,"ChromaticAberrationPostProcess",function(){return Zc}),i.d(t,"CircleOfConfusionPostProcess",function(){return $c}),i.d(t,"ColorCorrectionPostProcess",function(){return tl}),i.d(t,"ConvolutionPostProcess",function(){return nl}),i.d(t,"DepthOfFieldBlurPostProcess",function(){return rl}),i.d(t,"DepthOfFieldEffectBlurLevel",function(){return sl}),i.d(t,"DepthOfFieldEffect",function(){return ll}),i.d(t,"DepthOfFieldMergePostProcessOptions",function(){return al}),i.d(t,"DepthOfFieldMergePostProcess",function(){return cl}),i.d(t,"DisplayPassPostProcess",function(){return hl}),i.d(t,"ExtractHighlightsPostProcess",function(){return Xc}),i.d(t,"FilterPostProcess",function(){return fl}),i.d(t,"FxaaPostProcess",function(){return ml}),i.d(t,"GrainPostProcess",function(){return vl}),i.d(t,"HighlightsPostProcess",function(){return bl}),i.d(t,"ImageProcessingPostProcess",function(){return Ci}),i.d(t,"MotionBlurPostProcess",function(){return Rl}),i.d(t,"PassPostProcess",function(){return Yt}),i.d(t,"PassCubePostProcess",function(){return Kt}),i.d(t,"PostProcess",function(){return Wt}),i.d(t,"PostProcessManager",function(){return fi.a}),i.d(t,"RefractionPostProcess",function(){return Cl}),i.d(t,"SharpenPostProcess",function(){return Ol}),i.d(t,"StereoscopicInterlacePostProcess",function(){return ii}),i.d(t,"TonemappingOperator",function(){return Xl}),i.d(t,"TonemapPostProcess",function(){return Yl}),i.d(t,"VolumetricLightScatteringPostProcess",function(){return Zl}),i.d(t,"VRDistortionCorrectionPostProcess",function(){return ui}),i.d(t,"VRMultiviewToSingleviewPostProcess",function(){return gi}),i.d(t,"PostProcessRenderEffect",function(){return Wc}),i.d(t,"PostProcessRenderPipeline",function(){return Il}),i.d(t,"PostProcessRenderPipelineManager",function(){return Dl}),i.d(t,"PostProcessRenderPipelineManagerSceneComponent",function(){return Ll}),i.d(t,"DefaultRenderingPipeline",function(){return wl}),i.d(t,"LensRenderingPipeline",function(){return Bl}),i.d(t,"SSAO2RenderingPipeline",function(){return kl}),i.d(t,"SSAORenderingPipeline",function(){return zl}),i.d(t,"StandardRenderingPipeline",function(){return Wl}),i.d(t,"ReflectionProbe",function(){return us}),i.d(t,"BoundingBoxRenderer",function(){return Jl}),i.d(t,"DepthRenderer",function(){return eu}),i.d(t,"DepthRendererSceneComponent",function(){return tu}),i.d(t,"EdgesRenderer",function(){return ou}),i.d(t,"LineEdgesRenderer",function(){return su}),i.d(t,"GeometryBufferRenderer",function(){return xl}),i.d(t,"GeometryBufferRendererSceneComponent",function(){return Al}),i.d(t,"OutlineRenderer",function(){return lu}),i.d(t,"RenderingGroup",function(){return uu.a}),i.d(t,"RenderingGroupInfo",function(){return pi.a}),i.d(t,"RenderingManager",function(){return pi.b}),i.d(t,"UtilityLayerRenderer",function(){return Qn.a}),i.d(t,"Scene",function(){return H.a}),i.d(t,"SceneComponentConstants",function(){return xe.a}),i.d(t,"Stage",function(){return xe.b}),i.d(t,"Sprite",function(){return hu}),i.d(t,"SpriteManager",function(){return mu}),i.d(t,"SpriteSceneComponent",function(){return du}),i.d(t,"_AlphaState",function(){return gu.a}),i.d(t,"_DepthCullingState",function(){return gu.b}),i.d(t,"_StencilState",function(){return gu.c}),i.d(t,"AndOrNotEvaluator",function(){return vu.a}),i.d(t,"AssetTaskState",function(){return _u}),i.d(t,"AbstractAssetTask",function(){return bu}),i.d(t,"AssetsProgressEvent",function(){return Tu}),i.d(t,"MeshAssetTask",function(){return Eu}),i.d(t,"TextFileAssetTask",function(){return xu}),i.d(t,"BinaryFileAssetTask",function(){return Au}),i.d(t,"ImageAssetTask",function(){return Pu}),i.d(t,"TextureAssetTask",function(){return Ru}),i.d(t,"CubeTextureAssetTask",function(){return Su}),i.d(t,"HDRCubeTextureAssetTask",function(){return Cu}),i.d(t,"EquiRectangularCubeTextureAssetTask",function(){return Mu}),i.d(t,"AssetsManager",function(){return Ou}),i.d(t,"DDSTools",function(){return ho}),i.d(t,"expandToProperty",function(){return L.b}),i.d(t,"serialize",function(){return L.c}),i.d(t,"serializeAsTexture",function(){return L.m}),i.d(t,"serializeAsColor3",function(){return L.e}),i.d(t,"serializeAsFresnelParameters",function(){return L.h}),i.d(t,"serializeAsVector2",function(){return L.n}),i.d(t,"serializeAsVector3",function(){return L.o}),i.d(t,"serializeAsMeshReference",function(){return L.k}),i.d(t,"serializeAsColorCurves",function(){return L.g}),i.d(t,"serializeAsColor4",function(){return L.f}),i.d(t,"serializeAsImageProcessingConfiguration",function(){return L.i}),i.d(t,"serializeAsQuaternion",function(){return L.l}),i.d(t,"serializeAsMatrix",function(){return L.j}),i.d(t,"serializeAsCameraReference",function(){return L.d}),i.d(t,"SerializationHelper",function(){return L.a}),i.d(t,"Deferred",function(){return Iu}),i.d(t,"EnvironmentTextureTools",function(){return Tn}),i.d(t,"MeshExploder",function(){return Du}),i.d(t,"FilesInput",function(){return Lu}),i.d(t,"CubeMapToSphericalPolynomialTools",function(){return oo.a}),i.d(t,"KhronosTextureContainer",function(){return _o}),i.d(t,"EventState",function(){return r.a}),i.d(t,"Observer",function(){return r.d}),i.d(t,"MultiObserver",function(){return r.b}),i.d(t,"Observable",function(){return r.c}),i.d(t,"PerformanceMonitor",function(){return wu.a}),i.d(t,"RollingAverage",function(){return wu.b}),i.d(t,"PromisePolyfill",function(){return Fu.a}),i.d(t,"SceneOptimization",function(){return Nu}),i.d(t,"TextureOptimization",function(){return Bu}),i.d(t,"HardwareScalingOptimization",function(){return Uu}),i.d(t,"ShadowsOptimization",function(){return Vu}),i.d(t,"PostProcessesOptimization",function(){return ku}),i.d(t,"LensFlaresOptimization",function(){return Gu}),i.d(t,"CustomOptimization",function(){return zu}),i.d(t,"ParticlesOptimization",function(){return ju}),i.d(t,"RenderTargetsOptimization",function(){return Wu}),i.d(t,"MergeMeshesOptimization",function(){return Hu}),i.d(t,"SceneOptimizerOptions",function(){return Xu}),i.d(t,"SceneOptimizer",function(){return Yu}),i.d(t,"SceneSerializer",function(){return Zu}),i.d(t,"SmartArray",function(){return Gt.a}),i.d(t,"SmartArrayNoDuplicate",function(){return Gt.b}),i.d(t,"StringDictionary",function(){return mt.a}),i.d(t,"Tags",function(){return Ju.a}),i.d(t,"TextureTools",function(){return $u}),i.d(t,"TGATools",function(){return As}),i.d(t,"ColorGradient",function(){return ye.c}),i.d(t,"Color3Gradient",function(){return ye.b}),i.d(t,"FactorGradient",function(){return ye.d}),i.d(t,"LoadFileError",function(){return ye.e}),i.d(t,"RetryStrategy",function(){return ye.g}),i.d(t,"Tools",function(){return ye.h}),i.d(t,"PerfCounter",function(){return ye.f}),i.d(t,"className",function(){return ye.i}),i.d(t,"AsyncLoop",function(){return ye.a}),i.d(t,"VideoRecorder",function(){return eh}),i.d(t,"JoystickAxis",function(){return _t}),i.d(t,"VirtualJoystick",function(){return gt}),i.d(t,"WorkerPool",function(){return _a}),i.d(t,"Logger",function(){return p.a}),i.d(t,"_TypeStore",function(){return s.a}),i.d(t,"FilesInputStore",function(){return Fn.a}),i.d(t,"DeepCopier",function(){return S.a}),i.d(t,"PivotTools",function(){return Be.a}),i.d(t,"PrecisionDate",function(){return X.a}),i.d(t,"ScreenshotTools",function(){return th}),i.d(t,"WebRequest",function(){return Os.a}),i.d(t,"InspectableType",function(){return yu}),i.d(t,"BRDFTextureTools",function(){return Fr}),i.d(t,"HDRTools",function(){return Zo}),i.d(t,"PanoramaToCubeMapTools",function(){return qo})},function(e,t,i){"use strict";var n="fogFragmentDeclaration",r="#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif";i(6).a.IncludesShadersStore[n]=r},function(e,t,i){"use strict";var n="#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif";i(6).a.IncludesShadersStore.fogFragment=n},function(e,t,i){"use strict";var n="fogVertexDeclaration",r="#ifdef FOG\nvarying vec3 vFogDistance;\n#endif";i(6).a.IncludesShadersStore[n]=r},function(e,t,i){"use strict";var n="morphTargetsVertexGlobalDeclaration",r="#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif";i(6).a.IncludesShadersStore[n]=r},function(e,t,i){"use strict";var n="morphTargetsVertexDeclaration",r="#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif";i(6).a.IncludesShadersStore[n]=r},function(e,t,i){"use strict";var n="morphTargetsVertex",r="#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif";i(6).a.IncludesShadersStore[n]=r},function(e,t,i){"use strict";i.d(t,"a",function(){return n});var n=function(){function e(){}return e.Eval=function(t,i){return"true"===(t=t.match(/\([^\(\)]*\)/g)?t.replace(/\([^\(\)]*\)/g,function(t){return t=t.slice(1,t.length-1),e._HandleParenthesisContent(t,i)}):e._HandleParenthesisContent(t,i))||"false"!==t&&e.Eval(t,i)},e._HandleParenthesisContent=function(t,i){var n;i=i||function(e){return"true"===e};var r=t.split("||");for(var o in r)if(r.hasOwnProperty(o)){var s=e._SimplifyNegation(r[o].trim()),a=s.split("&&");if(a.length>1)for(var c=0;c=this._sampleCount||e>=this._samples.length)return 0;var t=this._wrapPosition(this._pos-1);return this._samples[this._wrapPosition(t-e)]},e.prototype.isSaturated=function(){return this._sampleCount>=this._samples.length},e.prototype.reset=function(){this.average=0,this.variance=0,this._sampleCount=0,this._pos=0,this._m2=0},e.prototype._wrapPosition=function(e){var t=this._samples.length;return(e%t+t)%t},e}()},function(e,t,i){"use strict";i.d(t,"a",function(){return a});var n,r=i(11);!function(e){e[e.Pending=0]="Pending",e[e.Fulfilled=1]="Fulfilled",e[e.Rejected=2]="Rejected"}(n||(n={}));var o=function(){return function(){this.count=0,this.target=0,this.results=[]}}(),s=function(){function e(e){var t=this;if(this._state=n.Pending,this._children=new Array,this._rejectWasConsumed=!1,e)try{e(function(e){t._resolve(e)},function(e){t._reject(e)})}catch(e){this._reject(e)}}return Object.defineProperty(e.prototype,"_result",{get:function(){return this._resultValue},set:function(e){this._resultValue=e,this._parent&&void 0===this._parent._result&&(this._parent._result=e)},enumerable:!0,configurable:!0}),e.prototype.catch=function(e){return this.then(void 0,e)},e.prototype.then=function(t,i){var o=this,s=new e;return s._onFulfilled=t,s._onRejected=i,this._children.push(s),s._parent=this,this._state!==n.Pending&&r.h.SetImmediate(function(){if(o._state===n.Fulfilled||o._rejectWasConsumed){var e=s._resolve(o._result);if(null!=e)if(void 0!==e._state){var t=e;s._children.push(t),t._parent=s,s=t}else s._result=e}else s._reject(o._reason)}),s},e.prototype._moveChildren=function(e){var t,i=this;if((t=this._children).push.apply(t,e.splice(0,e.length)),this._children.forEach(function(e){e._parent=i}),this._state===n.Fulfilled)for(var r=0,o=this._children;ri._alphaIndex?1:t._alphaIndext._distanceToCamera?-1:0},e.frontToBackSortCompare=function(e,t){return e._distanceToCamerat._distanceToCamera?1:0},e.prototype.prepare=function(){this._opaqueSubMeshes.reset(),this._transparentSubMeshes.reset(),this._alphaTestSubMeshes.reset(),this._depthOnlySubMeshes.reset(),this._particleSystems.reset(),this._spriteManagers.reset(),this._edgesRenderers.reset()},e.prototype.dispose=function(){this._opaqueSubMeshes.dispose(),this._transparentSubMeshes.dispose(),this._alphaTestSubMeshes.dispose(),this._depthOnlySubMeshes.dispose(),this._particleSystems.dispose(),this._spriteManagers.dispose(),this._edgesRenderers.dispose()},e.prototype.dispatch=function(e,t,i){void 0===t&&(t=e.getMesh()),void 0===i&&(i=e.getMaterial()),null!=i&&(i.needAlphaBlendingForMesh(t)?this._transparentSubMeshes.push(e):i.needAlphaTesting()?(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._alphaTestSubMeshes.push(e)):(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._opaqueSubMeshes.push(e)),t._renderingGroup=this,t._edgesRenderer&&t._edgesRenderer.isEnabled&&this._edgesRenderers.push(t._edgesRenderer))},e.prototype.dispatchSprites=function(e){this._spriteManagers.push(e)},e.prototype.dispatchParticles=function(e){this._particleSystems.push(e)},e.prototype._renderParticles=function(e){if(0!==this._particleSystems.length){var t=this._scene.activeCamera;this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);for(var i=0;i\nvoid main(void) {\n#include\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}";n.a.ShadersStore[r]=o},function(e,t,i){"use strict";var n=i(6),r=(i(69),i(97),i(70),i(71),i(72),i(91),"colorVertexShader"),o="\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n\n#include\nuniform mat4 viewProjection;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\n#include\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}";n.a.ShadersStore[r]=o},function(e,t,i){"use strict";(function(e){i.d(t,"b",function(){return u}),i.d(t,"a",function(){return h});var n=i(1),r=i(7),o=i(10),s=i(79),a=i(26),c=i(3),l=i(67),u=function(){return function(){this.renderWidth=512,this.renderHeight=256,this.textureSize=512,this.deterministicLockstep=!1,this.lockstepMaxSteps=4}}(),h=function(t){function i(i){void 0===i&&(i=new u);var n=t.call(this,null)||this;void 0===i.deterministicLockstep&&(i.deterministicLockstep=!1),void 0===i.lockstepMaxSteps&&(i.lockstepMaxSteps=4),n._options=i,n._caps=new o.c,n._caps.maxTexturesImageUnits=16,n._caps.maxVertexTextureImageUnits=16,n._caps.maxTextureSize=512,n._caps.maxCubemapTextureSize=512,n._caps.maxRenderTextureSize=512,n._caps.maxVertexAttribs=16,n._caps.maxVaryingVectors=16,n._caps.maxFragmentUniformVectors=16,n._caps.maxVertexUniformVectors=16,n._caps.standardDerivatives=!1,n._caps.astc=null,n._caps.s3tc=null,n._caps.pvrtc=null,n._caps.etc1=null,n._caps.etc2=null,n._caps.textureAnisotropicFilterExtension=null,n._caps.maxAnisotropy=0,n._caps.uintIndices=!1,n._caps.fragmentDepthSupported=!1,n._caps.highPrecisionShaderSupported=!0,n._caps.colorBufferFloat=!1,n._caps.textureFloat=!1,n._caps.textureFloatLinearFiltering=!1,n._caps.textureFloatRender=!1,n._caps.textureHalfFloat=!1,n._caps.textureHalfFloatLinearFiltering=!1,n._caps.textureHalfFloatRender=!1,n._caps.textureLOD=!1,n._caps.drawBuffersExtension=!1,n._caps.depthTextureExtension=!1,n._caps.vertexArrayObject=!1,n._caps.instancedArrays=!1,r.a.Log("Babylon.js v"+o.b.Version+" - Null engine");var s="undefined"!=typeof self?self:void 0!==e?e:window;return"undefined"==typeof URL&&(s.URL={createObjectURL:function(){},revokeObjectURL:function(){}}),"undefined"==typeof Blob&&(s.Blob=function(){}),n}return n.d(i,t),i.prototype.isDeterministicLockStep=function(){return this._options.deterministicLockstep},i.prototype.getLockstepMaxSteps=function(){return this._options.lockstepMaxSteps},i.prototype.getHardwareScalingLevel=function(){return 1},i.prototype.createVertexBuffer=function(e){var t=new l.a;return t.references=1,t},i.prototype.createIndexBuffer=function(e){var t=new l.a;return t.references=1,t},i.prototype.clear=function(e,t,i,n){void 0===n&&(n=!1)},i.prototype.getRenderWidth=function(e){return void 0===e&&(e=!1),!e&&this._currentRenderTarget?this._currentRenderTarget.width:this._options.renderWidth},i.prototype.getRenderHeight=function(e){return void 0===e&&(e=!1),!e&&this._currentRenderTarget?this._currentRenderTarget.height:this._options.renderHeight},i.prototype.setViewport=function(e,t,i){this._cachedViewport=e},i.prototype.createShaderProgram=function(e,t,i,n,r){return{__SPECTOR_rebuildProgram:null}},i.prototype.getUniforms=function(e,t){return[]},i.prototype.getAttributes=function(e,t){return[]},i.prototype.bindSamplers=function(e){this._currentEffect=null},i.prototype.enableEffect=function(e){this._currentEffect=e,e.onBind&&e.onBind(e),e._onBindObservable&&e._onBindObservable.notifyObservers(e)},i.prototype.setState=function(e,t,i,n){void 0===t&&(t=0),void 0===n&&(n=!1)},i.prototype.setIntArray=function(e,t){},i.prototype.setIntArray2=function(e,t){},i.prototype.setIntArray3=function(e,t){},i.prototype.setIntArray4=function(e,t){},i.prototype.setFloatArray=function(e,t){},i.prototype.setFloatArray2=function(e,t){},i.prototype.setFloatArray3=function(e,t){},i.prototype.setFloatArray4=function(e,t){},i.prototype.setArray=function(e,t){},i.prototype.setArray2=function(e,t){},i.prototype.setArray3=function(e,t){},i.prototype.setArray4=function(e,t){},i.prototype.setMatrices=function(e,t){},i.prototype.setMatrix=function(e,t){},i.prototype.setMatrix3x3=function(e,t){},i.prototype.setMatrix2x2=function(e,t){},i.prototype.setFloat=function(e,t){},i.prototype.setFloat2=function(e,t,i){},i.prototype.setFloat3=function(e,t,i,n){},i.prototype.setBool=function(e,t){},i.prototype.setFloat4=function(e,t,i,n,r){},i.prototype.setColor3=function(e,t){},i.prototype.setColor4=function(e,t,i){},i.prototype.setAlphaMode=function(e,t){void 0===t&&(t=!1),this._alphaMode!==e&&(this._alphaState.alphaBlend=e!==c.a.ALPHA_DISABLE,t||this.setDepthWrite(e===c.a.ALPHA_DISABLE),this._alphaMode=e)},i.prototype.bindBuffers=function(e,t,i){},i.prototype.wipeCaches=function(e){this.preventCacheWipeBetweenFrames||(this.resetTextureCache(),this._currentEffect=null,e&&(this._currentProgram=null,this._stencilState.reset(),this._depthCullingState.reset(),this._alphaState.reset()),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null)},i.prototype.draw=function(e,t,i,n){},i.prototype.drawElementsType=function(e,t,i,n){},i.prototype.drawArraysType=function(e,t,i,n){},i.prototype._createTexture=function(){return{}},i.prototype._releaseTexture=function(e){},i.prototype.createTexture=function(e,t,i,n,r,o,s,l,u,h){void 0===r&&(r=c.a.TEXTURE_TRILINEAR_SAMPLINGMODE),void 0===o&&(o=null),void 0===s&&(s=null),void 0===l&&(l=null);var d=new a.a(this,a.a.DATASOURCE_URL),f=String(e);return d.url=f,d.generateMipMaps=!t,d.samplingMode=r,d.invertY=i,d.baseWidth=this._options.textureSize,d.baseHeight=this._options.textureSize,d.width=this._options.textureSize,d.height=this._options.textureSize,h&&(d.format=h),d.isReady=!0,o&&o(),this._internalTexturesCache.push(d),d},i.prototype.createRenderTargetTexture=function(e,t){var i=new s.a;void 0!==t&&"object"==typeof t?(i.generateMipMaps=t.generateMipMaps,i.generateDepthBuffer=void 0===t.generateDepthBuffer||t.generateDepthBuffer,i.generateStencilBuffer=i.generateDepthBuffer&&t.generateStencilBuffer,i.type=void 0===t.type?c.a.TEXTURETYPE_UNSIGNED_INT:t.type,i.samplingMode=void 0===t.samplingMode?c.a.TEXTURE_TRILINEAR_SAMPLINGMODE:t.samplingMode):(i.generateMipMaps=t,i.generateDepthBuffer=!0,i.generateStencilBuffer=!1,i.type=c.a.TEXTURETYPE_UNSIGNED_INT,i.samplingMode=c.a.TEXTURE_TRILINEAR_SAMPLINGMODE);var n=new a.a(this,a.a.DATASOURCE_RENDERTARGET),r=e.width||e,o=e.height||e;return n._depthStencilBuffer={},n._framebuffer={},n.baseWidth=r,n.baseHeight=o,n.width=r,n.height=o,n.isReady=!0,n.samples=1,n.generateMipMaps=!!i.generateMipMaps,n.samplingMode=i.samplingMode,n.type=i.type,n._generateDepthBuffer=i.generateDepthBuffer,n._generateStencilBuffer=!!i.generateStencilBuffer,this._internalTexturesCache.push(n),n},i.prototype.updateTextureSamplingMode=function(e,t){t.samplingMode=e},i.prototype.bindFramebuffer=function(e,t,i,n,r){this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,this._currentFramebuffer=e._MSAAFramebuffer?e._MSAAFramebuffer:e._framebuffer,this._cachedViewport&&!r&&this.setViewport(this._cachedViewport,i,n)},i.prototype.unBindFramebuffer=function(e,t,i){void 0===t&&(t=!1),this._currentRenderTarget=null,i&&(e._MSAAFramebuffer&&(this._currentFramebuffer=e._framebuffer),i()),this._currentFramebuffer=null},i.prototype.createDynamicVertexBuffer=function(e){var t=new l.a;return t.references=1,t.capacity=1,t},i.prototype.updateDynamicTexture=function(e,t,i,n,r){void 0===n&&(n=!1)},i.prototype.areAllEffectsReady=function(){return!0},i.prototype.getError=function(){return 0},i.prototype._getUnpackAlignement=function(){return 1},i.prototype._unpackFlipY=function(e){},i.prototype.updateDynamicIndexBuffer=function(e,t,i){void 0===i&&(i=0)},i.prototype.updateDynamicVertexBuffer=function(e,t,i,n){},i.prototype._bindTextureDirectly=function(e,t){return this._boundTexturesCache[this._activeChannel]!==t&&(this._boundTexturesCache[this._activeChannel]=t,!0)},i.prototype._bindTexture=function(e,t){e<0||this._bindTextureDirectly(0,t)},i.prototype._deleteBuffer=function(e){},i.prototype.releaseEffects=function(){},i.prototype.displayLoadingUI=function(){},i.prototype.hideLoadingUI=function(){},i.prototype._uploadCompressedDataToTextureDirectly=function(e,t,i,n,r,o,s){void 0===o&&(o=0),void 0===s&&(s=0)},i.prototype._uploadDataToTextureDirectly=function(e,t,i,n){void 0===i&&(i=0),void 0===n&&(n=0)},i.prototype._uploadArrayBufferViewToTexture=function(e,t,i,n){void 0===i&&(i=0),void 0===n&&(n=0)},i.prototype._uploadImageToTexture=function(e,t,i,n){void 0===i&&(i=0),void 0===n&&(n=0)},i}(o.b)}).call(this,i(120))},function(e,t,i){"use strict";i.r(t),function(e){i.d(t,"Debug",function(){return l});var n=i(98),r=i(77);i.d(t,"AbstractScene",function(){return n.AbstractScene}),i.d(t,"KeepAssets",function(){return n.KeepAssets}),i.d(t,"AssetContainer",function(){return n.AssetContainer}),i.d(t,"Node",function(){return n.Node}),i.d(t,"Scene",function(){return n.Scene}),i.d(t,"SceneComponentConstants",function(){return n.SceneComponentConstants}),i.d(t,"Stage",function(){return n.Stage}),i.d(t,"Action",function(){return n.Action}),i.d(t,"ActionEvent",function(){return n.ActionEvent}),i.d(t,"ActionManager",function(){return n.ActionManager}),i.d(t,"Condition",function(){return n.Condition}),i.d(t,"ValueCondition",function(){return n.ValueCondition}),i.d(t,"PredicateCondition",function(){return n.PredicateCondition}),i.d(t,"StateCondition",function(){return n.StateCondition}),i.d(t,"SwitchBooleanAction",function(){return n.SwitchBooleanAction}),i.d(t,"SetStateAction",function(){return n.SetStateAction}),i.d(t,"SetValueAction",function(){return n.SetValueAction}),i.d(t,"IncrementValueAction",function(){return n.IncrementValueAction}),i.d(t,"PlayAnimationAction",function(){return n.PlayAnimationAction}),i.d(t,"StopAnimationAction",function(){return n.StopAnimationAction}),i.d(t,"DoNothingAction",function(){return n.DoNothingAction}),i.d(t,"CombineAction",function(){return n.CombineAction}),i.d(t,"ExecuteCodeAction",function(){return n.ExecuteCodeAction}),i.d(t,"SetParentAction",function(){return n.SetParentAction}),i.d(t,"PlaySoundAction",function(){return n.PlaySoundAction}),i.d(t,"StopSoundAction",function(){return n.StopSoundAction}),i.d(t,"InterpolateValueAction",function(){return n.InterpolateValueAction}),i.d(t,"Animatable",function(){return n.Animatable}),i.d(t,"_IAnimationState",function(){return n._IAnimationState}),i.d(t,"Animation",function(){return n.Animation}),i.d(t,"TargetedAnimation",function(){return n.TargetedAnimation}),i.d(t,"AnimationGroup",function(){return n.AnimationGroup}),i.d(t,"AnimationPropertiesOverride",function(){return n.AnimationPropertiesOverride}),i.d(t,"EasingFunction",function(){return n.EasingFunction}),i.d(t,"CircleEase",function(){return n.CircleEase}),i.d(t,"BackEase",function(){return n.BackEase}),i.d(t,"BounceEase",function(){return n.BounceEase}),i.d(t,"CubicEase",function(){return n.CubicEase}),i.d(t,"ElasticEase",function(){return n.ElasticEase}),i.d(t,"ExponentialEase",function(){return n.ExponentialEase}),i.d(t,"PowerEase",function(){return n.PowerEase}),i.d(t,"QuadraticEase",function(){return n.QuadraticEase}),i.d(t,"QuarticEase",function(){return n.QuarticEase}),i.d(t,"QuinticEase",function(){return n.QuinticEase}),i.d(t,"SineEase",function(){return n.SineEase}),i.d(t,"BezierCurveEase",function(){return n.BezierCurveEase}),i.d(t,"RuntimeAnimation",function(){return n.RuntimeAnimation}),i.d(t,"AnimationEvent",function(){return n.AnimationEvent}),i.d(t,"AnimationKeyInterpolation",function(){return n.AnimationKeyInterpolation}),i.d(t,"AnimationRange",function(){return n.AnimationRange}),i.d(t,"Analyser",function(){return n.Analyser}),i.d(t,"AudioEngine",function(){return n.AudioEngine}),i.d(t,"AudioSceneComponent",function(){return n.AudioSceneComponent}),i.d(t,"Sound",function(){return n.Sound}),i.d(t,"SoundTrack",function(){return n.SoundTrack}),i.d(t,"WeightedSound",function(){return n.WeightedSound}),i.d(t,"Bone",function(){return n.Bone}),i.d(t,"BoneIKController",function(){return n.BoneIKController}),i.d(t,"BoneLookController",function(){return n.BoneLookController}),i.d(t,"Skeleton",function(){return n.Skeleton}),i.d(t,"CameraInputTypes",function(){return n.CameraInputTypes}),i.d(t,"CameraInputsManager",function(){return n.CameraInputsManager}),i.d(t,"Camera",function(){return n.Camera}),i.d(t,"TargetCamera",function(){return n.TargetCamera}),i.d(t,"FreeCamera",function(){return n.FreeCamera}),i.d(t,"FreeCameraInputsManager",function(){return n.FreeCameraInputsManager}),i.d(t,"TouchCamera",function(){return n.TouchCamera}),i.d(t,"ArcRotateCamera",function(){return n.ArcRotateCamera}),i.d(t,"ArcRotateCameraInputsManager",function(){return n.ArcRotateCameraInputsManager}),i.d(t,"DeviceOrientationCamera",function(){return n.DeviceOrientationCamera}),i.d(t,"FlyCamera",function(){return n.FlyCamera}),i.d(t,"FlyCameraInputsManager",function(){return n.FlyCameraInputsManager}),i.d(t,"FollowCamera",function(){return n.FollowCamera}),i.d(t,"ArcFollowCamera",function(){return n.ArcFollowCamera}),i.d(t,"GamepadCamera",function(){return n.GamepadCamera}),i.d(t,"UniversalCamera",function(){return n.UniversalCamera}),i.d(t,"VirtualJoysticksCamera",function(){return n.VirtualJoysticksCamera}),i.d(t,"Collider",function(){return n.Collider}),i.d(t,"DefaultCollisionCoordinator",function(){return n.DefaultCollisionCoordinator}),i.d(t,"PickingInfo",function(){return n.PickingInfo}),i.d(t,"IntersectionInfo",function(){return n.IntersectionInfo}),i.d(t,"_MeshCollisionData",function(){return n._MeshCollisionData}),i.d(t,"BoundingBox",function(){return n.BoundingBox}),i.d(t,"BoundingInfo",function(){return n.BoundingInfo}),i.d(t,"BoundingSphere",function(){return n.BoundingSphere}),i.d(t,"Ray",function(){return n.Ray}),i.d(t,"AxesViewer",function(){return n.AxesViewer}),i.d(t,"BoneAxesViewer",function(){return n.BoneAxesViewer}),i.d(t,"DebugLayer",function(){return n.DebugLayer}),i.d(t,"PhysicsViewer",function(){return n.PhysicsViewer}),i.d(t,"RayHelper",function(){return n.RayHelper}),i.d(t,"SkeletonViewer",function(){return n.SkeletonViewer}),i.d(t,"Constants",function(){return n.Constants}),i.d(t,"InstancingAttributeInfo",function(){return n.InstancingAttributeInfo}),i.d(t,"DepthTextureCreationOptions",function(){return n.DepthTextureCreationOptions}),i.d(t,"EngineCapabilities",function(){return n.EngineCapabilities}),i.d(t,"Engine",function(){return n.Engine}),i.d(t,"EngineStore",function(){return n.EngineStore}),i.d(t,"NullEngineOptions",function(){return n.NullEngineOptions}),i.d(t,"NullEngine",function(){return n.NullEngine}),i.d(t,"WebGLPipelineContext",function(){return n.WebGLPipelineContext}),i.d(t,"WebGL2ShaderProcessor",function(){return n.WebGL2ShaderProcessor}),i.d(t,"NativeEngineOptions",function(){return n.NativeEngineOptions}),i.d(t,"NativeEngine",function(){return n.NativeEngine}),i.d(t,"KeyboardEventTypes",function(){return n.KeyboardEventTypes}),i.d(t,"KeyboardInfo",function(){return n.KeyboardInfo}),i.d(t,"KeyboardInfoPre",function(){return n.KeyboardInfoPre}),i.d(t,"PointerEventTypes",function(){return n.PointerEventTypes}),i.d(t,"PointerInfoBase",function(){return n.PointerInfoBase}),i.d(t,"PointerInfoPre",function(){return n.PointerInfoPre}),i.d(t,"PointerInfo",function(){return n.PointerInfo}),i.d(t,"ClipboardEventTypes",function(){return n.ClipboardEventTypes}),i.d(t,"ClipboardInfo",function(){return n.ClipboardInfo}),i.d(t,"StickValues",function(){return n.StickValues}),i.d(t,"Gamepad",function(){return n.Gamepad}),i.d(t,"GenericPad",function(){return n.GenericPad}),i.d(t,"GamepadManager",function(){return n.GamepadManager}),i.d(t,"GamepadSystemSceneComponent",function(){return n.GamepadSystemSceneComponent}),i.d(t,"Xbox360Button",function(){return n.Xbox360Button}),i.d(t,"Xbox360Dpad",function(){return n.Xbox360Dpad}),i.d(t,"Xbox360Pad",function(){return n.Xbox360Pad}),i.d(t,"AxisDragGizmo",function(){return n.AxisDragGizmo}),i.d(t,"AxisScaleGizmo",function(){return n.AxisScaleGizmo}),i.d(t,"BoundingBoxGizmo",function(){return n.BoundingBoxGizmo}),i.d(t,"Gizmo",function(){return n.Gizmo}),i.d(t,"GizmoManager",function(){return n.GizmoManager}),i.d(t,"PlaneRotationGizmo",function(){return n.PlaneRotationGizmo}),i.d(t,"PositionGizmo",function(){return n.PositionGizmo}),i.d(t,"RotationGizmo",function(){return n.RotationGizmo}),i.d(t,"ScaleGizmo",function(){return n.ScaleGizmo}),i.d(t,"LightGizmo",function(){return n.LightGizmo}),i.d(t,"EnvironmentHelper",function(){return n.EnvironmentHelper}),i.d(t,"PhotoDome",function(){return n.PhotoDome}),i.d(t,"_forceSceneHelpersToBundle",function(){return n._forceSceneHelpersToBundle}),i.d(t,"VideoDome",function(){return n.VideoDome}),i.d(t,"EngineInstrumentation",function(){return n.EngineInstrumentation}),i.d(t,"SceneInstrumentation",function(){return n.SceneInstrumentation}),i.d(t,"_TimeToken",function(){return n._TimeToken}),i.d(t,"EffectLayer",function(){return n.EffectLayer}),i.d(t,"EffectLayerSceneComponent",function(){return n.EffectLayerSceneComponent}),i.d(t,"GlowLayer",function(){return n.GlowLayer}),i.d(t,"HighlightLayer",function(){return n.HighlightLayer}),i.d(t,"Layer",function(){return n.Layer}),i.d(t,"LayerSceneComponent",function(){return n.LayerSceneComponent}),i.d(t,"LensFlare",function(){return n.LensFlare}),i.d(t,"LensFlareSystem",function(){return n.LensFlareSystem}),i.d(t,"LensFlareSystemSceneComponent",function(){return n.LensFlareSystemSceneComponent}),i.d(t,"Light",function(){return n.Light}),i.d(t,"ShadowLight",function(){return n.ShadowLight}),i.d(t,"DirectionalLight",function(){return n.DirectionalLight}),i.d(t,"HemisphericLight",function(){return n.HemisphericLight}),i.d(t,"PointLight",function(){return n.PointLight}),i.d(t,"SpotLight",function(){return n.SpotLight}),i.d(t,"DefaultLoadingScreen",function(){return n.DefaultLoadingScreen}),i.d(t,"SceneLoaderProgressEvent",function(){return n.SceneLoaderProgressEvent}),i.d(t,"SceneLoader",function(){return n.SceneLoader}),i.d(t,"SceneLoaderFlags",function(){return n.SceneLoaderFlags}),i.d(t,"ColorCurves",function(){return n.ColorCurves}),i.d(t,"EffectFallbacks",function(){return n.EffectFallbacks}),i.d(t,"EffectCreationOptions",function(){return n.EffectCreationOptions}),i.d(t,"Effect",function(){return n.Effect}),i.d(t,"FresnelParameters",function(){return n.FresnelParameters}),i.d(t,"ImageProcessingConfigurationDefines",function(){return n.ImageProcessingConfigurationDefines}),i.d(t,"ImageProcessingConfiguration",function(){return n.ImageProcessingConfiguration}),i.d(t,"Material",function(){return n.Material}),i.d(t,"MaterialDefines",function(){return n.MaterialDefines}),i.d(t,"MaterialHelper",function(){return n.MaterialHelper}),i.d(t,"MultiMaterial",function(){return n.MultiMaterial}),i.d(t,"PBRMaterialDefines",function(){return n.PBRMaterialDefines}),i.d(t,"PBRBaseMaterial",function(){return n.PBRBaseMaterial}),i.d(t,"PBRMaterial",function(){return n.PBRMaterial}),i.d(t,"PushMaterial",function(){return n.PushMaterial}),i.d(t,"ShaderMaterial",function(){return n.ShaderMaterial}),i.d(t,"StandardMaterialDefines",function(){return n.StandardMaterialDefines}),i.d(t,"StandardMaterial",function(){return n.StandardMaterial}),i.d(t,"BaseTexture",function(){return n.BaseTexture}),i.d(t,"CubeTexture",function(){return n.CubeTexture}),i.d(t,"DynamicTexture",function(){return n.DynamicTexture}),i.d(t,"EquiRectangularCubeTexture",function(){return n.EquiRectangularCubeTexture}),i.d(t,"HDRCubeTexture",function(){return n.HDRCubeTexture}),i.d(t,"InternalTexture",function(){return n.InternalTexture}),i.d(t,"MirrorTexture",function(){return n.MirrorTexture}),i.d(t,"MultiRenderTarget",function(){return n.MultiRenderTarget}),i.d(t,"RenderTargetTexture",function(){return n.RenderTargetTexture}),i.d(t,"Texture",function(){return n.Texture}),i.d(t,"VideoTexture",function(){return n.VideoTexture}),i.d(t,"UniformBuffer",function(){return n.UniformBuffer}),i.d(t,"MaterialFlags",function(){return n.MaterialFlags}),i.d(t,"Scalar",function(){return n.Scalar}),i.d(t,"ToGammaSpace",function(){return n.ToGammaSpace}),i.d(t,"ToLinearSpace",function(){return n.ToLinearSpace}),i.d(t,"Epsilon",function(){return n.Epsilon}),i.d(t,"Color3",function(){return n.Color3}),i.d(t,"Color4",function(){return n.Color4}),i.d(t,"Vector2",function(){return n.Vector2}),i.d(t,"Vector3",function(){return n.Vector3}),i.d(t,"Vector4",function(){return n.Vector4}),i.d(t,"Size",function(){return n.Size}),i.d(t,"Quaternion",function(){return n.Quaternion}),i.d(t,"Matrix",function(){return n.Matrix}),i.d(t,"Plane",function(){return n.Plane}),i.d(t,"Viewport",function(){return n.Viewport}),i.d(t,"Frustum",function(){return n.Frustum}),i.d(t,"Space",function(){return n.Space}),i.d(t,"Axis",function(){return n.Axis}),i.d(t,"BezierCurve",function(){return n.BezierCurve}),i.d(t,"Orientation",function(){return n.Orientation}),i.d(t,"Angle",function(){return n.Angle}),i.d(t,"Arc2",function(){return n.Arc2}),i.d(t,"Path2",function(){return n.Path2}),i.d(t,"Path3D",function(){return n.Path3D}),i.d(t,"Curve3",function(){return n.Curve3}),i.d(t,"PositionNormalVertex",function(){return n.PositionNormalVertex}),i.d(t,"PositionNormalTextureVertex",function(){return n.PositionNormalTextureVertex}),i.d(t,"Tmp",function(){return n.Tmp}),i.d(t,"SphericalHarmonics",function(){return n.SphericalHarmonics}),i.d(t,"SphericalPolynomial",function(){return n.SphericalPolynomial}),i.d(t,"AbstractMesh",function(){return n.AbstractMesh}),i.d(t,"Buffer",function(){return n.Buffer}),i.d(t,"VertexBuffer",function(){return n.VertexBuffer}),i.d(t,"CSG",function(){return n.CSG}),i.d(t,"Geometry",function(){return n.Geometry}),i.d(t,"GroundMesh",function(){return n.GroundMesh}),i.d(t,"TrailMesh",function(){return n.TrailMesh}),i.d(t,"InstancedMesh",function(){return n.InstancedMesh}),i.d(t,"LinesMesh",function(){return n.LinesMesh}),i.d(t,"InstancedLinesMesh",function(){return n.InstancedLinesMesh}),i.d(t,"_CreationDataStorage",function(){return n._CreationDataStorage}),i.d(t,"_InstancesBatch",function(){return n._InstancesBatch}),i.d(t,"Mesh",function(){return n.Mesh}),i.d(t,"VertexData",function(){return n.VertexData}),i.d(t,"MeshBuilder",function(){return n.MeshBuilder}),i.d(t,"SimplificationSettings",function(){return n.SimplificationSettings}),i.d(t,"SimplificationQueue",function(){return n.SimplificationQueue}),i.d(t,"SimplificationType",function(){return n.SimplificationType}),i.d(t,"SimplicationQueueSceneComponent",function(){return n.SimplicationQueueSceneComponent}),i.d(t,"Polygon",function(){return n.Polygon}),i.d(t,"PolygonMeshBuilder",function(){return n.PolygonMeshBuilder}),i.d(t,"BaseSubMesh",function(){return n.BaseSubMesh}),i.d(t,"SubMesh",function(){return n.SubMesh}),i.d(t,"MeshLODLevel",function(){return n.MeshLODLevel}),i.d(t,"TransformNode",function(){return n.TransformNode}),i.d(t,"BoxBuilder",function(){return n.BoxBuilder}),i.d(t,"SphereBuilder",function(){return n.SphereBuilder}),i.d(t,"CylinderBuilder",function(){return n.CylinderBuilder}),i.d(t,"TorusBuilder",function(){return n.TorusBuilder}),i.d(t,"LinesBuilder",function(){return n.LinesBuilder}),i.d(t,"PlaneBuilder",function(){return n.PlaneBuilder}),i.d(t,"GroundBuilder",function(){return n.GroundBuilder}),i.d(t,"DataBuffer",function(){return n.DataBuffer}),i.d(t,"WebGLDataBuffer",function(){return n.WebGLDataBuffer}),i.d(t,"MorphTarget",function(){return n.MorphTarget}),i.d(t,"MorphTargetManager",function(){return n.MorphTargetManager}),i.d(t,"Database",function(){return n.Database}),i.d(t,"BaseParticleSystem",function(){return n.BaseParticleSystem}),i.d(t,"GPUParticleSystem",function(){return n.GPUParticleSystem}),i.d(t,"Particle",function(){return n.Particle}),i.d(t,"ParticleHelper",function(){return n.ParticleHelper}),i.d(t,"ParticleSystem",function(){return n.ParticleSystem}),i.d(t,"_IDoNeedToBeInTheBuild",function(){return n._IDoNeedToBeInTheBuild}),i.d(t,"ParticleSystemSet",function(){return n.ParticleSystemSet}),i.d(t,"SolidParticle",function(){return n.SolidParticle}),i.d(t,"ModelShape",function(){return n.ModelShape}),i.d(t,"DepthSortedParticle",function(){return n.DepthSortedParticle}),i.d(t,"SolidParticleSystem",function(){return n.SolidParticleSystem}),i.d(t,"SubEmitterType",function(){return n.SubEmitterType}),i.d(t,"SubEmitter",function(){return n.SubEmitter}),i.d(t,"PhysicsEngine",function(){return n.PhysicsEngine}),i.d(t,"PhysicsEngineSceneComponent",function(){return n.PhysicsEngineSceneComponent}),i.d(t,"PhysicsHelper",function(){return n.PhysicsHelper}),i.d(t,"PhysicsRadialExplosionEventOptions",function(){return n.PhysicsRadialExplosionEventOptions}),i.d(t,"PhysicsUpdraftEventOptions",function(){return n.PhysicsUpdraftEventOptions}),i.d(t,"PhysicsVortexEventOptions",function(){return n.PhysicsVortexEventOptions}),i.d(t,"PhysicsRadialImpulseFalloff",function(){return n.PhysicsRadialImpulseFalloff}),i.d(t,"PhysicsUpdraftMode",function(){return n.PhysicsUpdraftMode}),i.d(t,"PhysicsImpostor",function(){return n.PhysicsImpostor}),i.d(t,"PhysicsJoint",function(){return n.PhysicsJoint}),i.d(t,"DistanceJoint",function(){return n.DistanceJoint}),i.d(t,"MotorEnabledJoint",function(){return n.MotorEnabledJoint}),i.d(t,"HingeJoint",function(){return n.HingeJoint}),i.d(t,"Hinge2Joint",function(){return n.Hinge2Joint}),i.d(t,"AnaglyphPostProcess",function(){return n.AnaglyphPostProcess}),i.d(t,"BlackAndWhitePostProcess",function(){return n.BlackAndWhitePostProcess}),i.d(t,"BloomEffect",function(){return n.BloomEffect}),i.d(t,"BloomMergePostProcess",function(){return n.BloomMergePostProcess}),i.d(t,"BlurPostProcess",function(){return n.BlurPostProcess}),i.d(t,"ChromaticAberrationPostProcess",function(){return n.ChromaticAberrationPostProcess}),i.d(t,"CircleOfConfusionPostProcess",function(){return n.CircleOfConfusionPostProcess}),i.d(t,"ColorCorrectionPostProcess",function(){return n.ColorCorrectionPostProcess}),i.d(t,"ConvolutionPostProcess",function(){return n.ConvolutionPostProcess}),i.d(t,"DepthOfFieldBlurPostProcess",function(){return n.DepthOfFieldBlurPostProcess}),i.d(t,"DepthOfFieldEffectBlurLevel",function(){return n.DepthOfFieldEffectBlurLevel}),i.d(t,"DepthOfFieldEffect",function(){return n.DepthOfFieldEffect}),i.d(t,"DepthOfFieldMergePostProcessOptions",function(){return n.DepthOfFieldMergePostProcessOptions}),i.d(t,"DepthOfFieldMergePostProcess",function(){return n.DepthOfFieldMergePostProcess}),i.d(t,"DisplayPassPostProcess",function(){return n.DisplayPassPostProcess}),i.d(t,"ExtractHighlightsPostProcess",function(){return n.ExtractHighlightsPostProcess}),i.d(t,"FilterPostProcess",function(){return n.FilterPostProcess}),i.d(t,"FxaaPostProcess",function(){return n.FxaaPostProcess}),i.d(t,"GrainPostProcess",function(){return n.GrainPostProcess}),i.d(t,"HighlightsPostProcess",function(){return n.HighlightsPostProcess}),i.d(t,"ImageProcessingPostProcess",function(){return n.ImageProcessingPostProcess}),i.d(t,"MotionBlurPostProcess",function(){return n.MotionBlurPostProcess}),i.d(t,"PassPostProcess",function(){return n.PassPostProcess}),i.d(t,"PassCubePostProcess",function(){return n.PassCubePostProcess}),i.d(t,"PostProcess",function(){return n.PostProcess}),i.d(t,"PostProcessManager",function(){return n.PostProcessManager}),i.d(t,"RefractionPostProcess",function(){return n.RefractionPostProcess}),i.d(t,"SharpenPostProcess",function(){return n.SharpenPostProcess}),i.d(t,"StereoscopicInterlacePostProcess",function(){return n.StereoscopicInterlacePostProcess}),i.d(t,"TonemappingOperator",function(){return n.TonemappingOperator}),i.d(t,"TonemapPostProcess",function(){return n.TonemapPostProcess}),i.d(t,"VolumetricLightScatteringPostProcess",function(){return n.VolumetricLightScatteringPostProcess}),i.d(t,"VRDistortionCorrectionPostProcess",function(){return n.VRDistortionCorrectionPostProcess}),i.d(t,"VRMultiviewToSingleviewPostProcess",function(){return n.VRMultiviewToSingleviewPostProcess}),i.d(t,"ReflectionProbe",function(){return n.ReflectionProbe}),i.d(t,"BoundingBoxRenderer",function(){return n.BoundingBoxRenderer}),i.d(t,"DepthRenderer",function(){return n.DepthRenderer}),i.d(t,"DepthRendererSceneComponent",function(){return n.DepthRendererSceneComponent}),i.d(t,"EdgesRenderer",function(){return n.EdgesRenderer}),i.d(t,"LineEdgesRenderer",function(){return n.LineEdgesRenderer}),i.d(t,"GeometryBufferRenderer",function(){return n.GeometryBufferRenderer}),i.d(t,"GeometryBufferRendererSceneComponent",function(){return n.GeometryBufferRendererSceneComponent}),i.d(t,"OutlineRenderer",function(){return n.OutlineRenderer}),i.d(t,"RenderingGroup",function(){return n.RenderingGroup}),i.d(t,"RenderingGroupInfo",function(){return n.RenderingGroupInfo}),i.d(t,"RenderingManager",function(){return n.RenderingManager}),i.d(t,"UtilityLayerRenderer",function(){return n.UtilityLayerRenderer}),i.d(t,"Sprite",function(){return n.Sprite}),i.d(t,"SpriteManager",function(){return n.SpriteManager}),i.d(t,"SpriteSceneComponent",function(){return n.SpriteSceneComponent}),i.d(t,"_AlphaState",function(){return n._AlphaState}),i.d(t,"_DepthCullingState",function(){return n._DepthCullingState}),i.d(t,"_StencilState",function(){return n._StencilState}),i.d(t,"AndOrNotEvaluator",function(){return n.AndOrNotEvaluator}),i.d(t,"AssetTaskState",function(){return n.AssetTaskState}),i.d(t,"AbstractAssetTask",function(){return n.AbstractAssetTask}),i.d(t,"AssetsProgressEvent",function(){return n.AssetsProgressEvent}),i.d(t,"MeshAssetTask",function(){return n.MeshAssetTask}),i.d(t,"TextFileAssetTask",function(){return n.TextFileAssetTask}),i.d(t,"BinaryFileAssetTask",function(){return n.BinaryFileAssetTask}),i.d(t,"ImageAssetTask",function(){return n.ImageAssetTask}),i.d(t,"TextureAssetTask",function(){return n.TextureAssetTask}),i.d(t,"CubeTextureAssetTask",function(){return n.CubeTextureAssetTask}),i.d(t,"HDRCubeTextureAssetTask",function(){return n.HDRCubeTextureAssetTask}),i.d(t,"EquiRectangularCubeTextureAssetTask",function(){return n.EquiRectangularCubeTextureAssetTask}),i.d(t,"AssetsManager",function(){return n.AssetsManager}),i.d(t,"DDSTools",function(){return n.DDSTools}),i.d(t,"expandToProperty",function(){return n.expandToProperty}),i.d(t,"serialize",function(){return n.serialize}),i.d(t,"serializeAsTexture",function(){return n.serializeAsTexture}),i.d(t,"serializeAsColor3",function(){return n.serializeAsColor3}),i.d(t,"serializeAsFresnelParameters",function(){return n.serializeAsFresnelParameters}),i.d(t,"serializeAsVector2",function(){return n.serializeAsVector2}),i.d(t,"serializeAsVector3",function(){return n.serializeAsVector3}),i.d(t,"serializeAsMeshReference",function(){return n.serializeAsMeshReference}),i.d(t,"serializeAsColorCurves",function(){return n.serializeAsColorCurves}),i.d(t,"serializeAsColor4",function(){return n.serializeAsColor4}),i.d(t,"serializeAsImageProcessingConfiguration",function(){return n.serializeAsImageProcessingConfiguration}),i.d(t,"serializeAsQuaternion",function(){return n.serializeAsQuaternion}),i.d(t,"serializeAsMatrix",function(){return n.serializeAsMatrix}),i.d(t,"serializeAsCameraReference",function(){return n.serializeAsCameraReference}),i.d(t,"SerializationHelper",function(){return n.SerializationHelper}),i.d(t,"Deferred",function(){return n.Deferred}),i.d(t,"EnvironmentTextureTools",function(){return n.EnvironmentTextureTools}),i.d(t,"MeshExploder",function(){return n.MeshExploder}),i.d(t,"FilesInput",function(){return n.FilesInput}),i.d(t,"CubeMapToSphericalPolynomialTools",function(){return n.CubeMapToSphericalPolynomialTools}),i.d(t,"KhronosTextureContainer",function(){return n.KhronosTextureContainer}),i.d(t,"EventState",function(){return n.EventState}),i.d(t,"Observer",function(){return n.Observer}),i.d(t,"MultiObserver",function(){return n.MultiObserver}),i.d(t,"Observable",function(){return n.Observable}),i.d(t,"PerformanceMonitor",function(){return n.PerformanceMonitor}),i.d(t,"RollingAverage",function(){return n.RollingAverage}),i.d(t,"PromisePolyfill",function(){return n.PromisePolyfill}),i.d(t,"SceneOptimization",function(){return n.SceneOptimization}),i.d(t,"TextureOptimization",function(){return n.TextureOptimization}),i.d(t,"HardwareScalingOptimization",function(){return n.HardwareScalingOptimization}),i.d(t,"ShadowsOptimization",function(){return n.ShadowsOptimization}),i.d(t,"PostProcessesOptimization",function(){return n.PostProcessesOptimization}),i.d(t,"LensFlaresOptimization",function(){return n.LensFlaresOptimization}),i.d(t,"CustomOptimization",function(){return n.CustomOptimization}),i.d(t,"ParticlesOptimization",function(){return n.ParticlesOptimization}),i.d(t,"RenderTargetsOptimization",function(){return n.RenderTargetsOptimization}),i.d(t,"MergeMeshesOptimization",function(){return n.MergeMeshesOptimization}),i.d(t,"SceneOptimizerOptions",function(){return n.SceneOptimizerOptions}),i.d(t,"SceneOptimizer",function(){return n.SceneOptimizer}),i.d(t,"SceneSerializer",function(){return n.SceneSerializer}),i.d(t,"SmartArray",function(){return n.SmartArray}),i.d(t,"SmartArrayNoDuplicate",function(){return n.SmartArrayNoDuplicate}),i.d(t,"StringDictionary",function(){return n.StringDictionary}),i.d(t,"Tags",function(){return n.Tags}),i.d(t,"TextureTools",function(){return n.TextureTools}),i.d(t,"TGATools",function(){return n.TGATools}),i.d(t,"ColorGradient",function(){return n.ColorGradient}),i.d(t,"Color3Gradient",function(){return n.Color3Gradient}),i.d(t,"FactorGradient",function(){return n.FactorGradient}),i.d(t,"LoadFileError",function(){return n.LoadFileError}),i.d(t,"RetryStrategy",function(){return n.RetryStrategy}),i.d(t,"Tools",function(){return n.Tools}),i.d(t,"PerfCounter",function(){return n.PerfCounter}),i.d(t,"className",function(){return n.className}),i.d(t,"AsyncLoop",function(){return n.AsyncLoop}),i.d(t,"VideoRecorder",function(){return n.VideoRecorder}),i.d(t,"JoystickAxis",function(){return n.JoystickAxis}),i.d(t,"VirtualJoystick",function(){return n.VirtualJoystick}),i.d(t,"WorkerPool",function(){return n.WorkerPool}),i.d(t,"Logger",function(){return n.Logger}),i.d(t,"_TypeStore",function(){return n._TypeStore}),i.d(t,"FilesInputStore",function(){return n.FilesInputStore}),i.d(t,"DeepCopier",function(){return n.DeepCopier}),i.d(t,"PivotTools",function(){return n.PivotTools}),i.d(t,"PrecisionDate",function(){return n.PrecisionDate}),i.d(t,"ScreenshotTools",function(){return n.ScreenshotTools}),i.d(t,"WebRequest",function(){return n.WebRequest}),i.d(t,"InspectableType",function(){return n.InspectableType}),i.d(t,"BRDFTextureTools",function(){return n.BRDFTextureTools}),i.d(t,"AutoRotationBehavior",function(){return n.AutoRotationBehavior}),i.d(t,"BouncingBehavior",function(){return n.BouncingBehavior}),i.d(t,"FramingBehavior",function(){return n.FramingBehavior}),i.d(t,"AttachToBoxBehavior",function(){return n.AttachToBoxBehavior}),i.d(t,"FadeInOutBehavior",function(){return n.FadeInOutBehavior}),i.d(t,"MultiPointerScaleBehavior",function(){return n.MultiPointerScaleBehavior}),i.d(t,"PointerDragBehavior",function(){return n.PointerDragBehavior}),i.d(t,"SixDofDragBehavior",function(){return n.SixDofDragBehavior}),i.d(t,"ArcRotateCameraGamepadInput",function(){return n.ArcRotateCameraGamepadInput}),i.d(t,"ArcRotateCameraKeyboardMoveInput",function(){return n.ArcRotateCameraKeyboardMoveInput}),i.d(t,"ArcRotateCameraMouseWheelInput",function(){return n.ArcRotateCameraMouseWheelInput}),i.d(t,"ArcRotateCameraPointersInput",function(){return n.ArcRotateCameraPointersInput}),i.d(t,"ArcRotateCameraVRDeviceOrientationInput",function(){return n.ArcRotateCameraVRDeviceOrientationInput}),i.d(t,"FlyCameraKeyboardInput",function(){return n.FlyCameraKeyboardInput}),i.d(t,"FlyCameraMouseInput",function(){return n.FlyCameraMouseInput}),i.d(t,"FollowCameraKeyboardMoveInput",function(){return n.FollowCameraKeyboardMoveInput}),i.d(t,"FollowCameraMouseWheelInput",function(){return n.FollowCameraMouseWheelInput}),i.d(t,"FollowCameraPointersInput",function(){return n.FollowCameraPointersInput}),i.d(t,"FreeCameraDeviceOrientationInput",function(){return n.FreeCameraDeviceOrientationInput}),i.d(t,"FreeCameraGamepadInput",function(){return n.FreeCameraGamepadInput}),i.d(t,"FreeCameraKeyboardMoveInput",function(){return n.FreeCameraKeyboardMoveInput}),i.d(t,"FreeCameraMouseInput",function(){return n.FreeCameraMouseInput}),i.d(t,"FreeCameraTouchInput",function(){return n.FreeCameraTouchInput}),i.d(t,"FreeCameraVirtualJoystickInput",function(){return n.FreeCameraVirtualJoystickInput}),i.d(t,"AnaglyphArcRotateCamera",function(){return n.AnaglyphArcRotateCamera}),i.d(t,"AnaglyphFreeCamera",function(){return n.AnaglyphFreeCamera}),i.d(t,"AnaglyphGamepadCamera",function(){return n.AnaglyphGamepadCamera}),i.d(t,"AnaglyphUniversalCamera",function(){return n.AnaglyphUniversalCamera}),i.d(t,"StereoscopicArcRotateCamera",function(){return n.StereoscopicArcRotateCamera}),i.d(t,"StereoscopicFreeCamera",function(){return n.StereoscopicFreeCamera}),i.d(t,"StereoscopicGamepadCamera",function(){return n.StereoscopicGamepadCamera}),i.d(t,"StereoscopicUniversalCamera",function(){return n.StereoscopicUniversalCamera}),i.d(t,"VRCameraMetrics",function(){return n.VRCameraMetrics}),i.d(t,"VRDeviceOrientationArcRotateCamera",function(){return n.VRDeviceOrientationArcRotateCamera}),i.d(t,"VRDeviceOrientationFreeCamera",function(){return n.VRDeviceOrientationFreeCamera}),i.d(t,"VRDeviceOrientationGamepadCamera",function(){return n.VRDeviceOrientationGamepadCamera}),i.d(t,"OnAfterEnteringVRObservableEvent",function(){return n.OnAfterEnteringVRObservableEvent}),i.d(t,"VRExperienceHelper",function(){return n.VRExperienceHelper}),i.d(t,"WebVRFreeCamera",function(){return n.WebVRFreeCamera}),i.d(t,"WebXRCamera",function(){return n.WebXRCamera}),i.d(t,"WebXREnterExitUIButton",function(){return n.WebXREnterExitUIButton}),i.d(t,"WebXREnterExitUIOptions",function(){return n.WebXREnterExitUIOptions}),i.d(t,"WebXREnterExitUI",function(){return n.WebXREnterExitUI}),i.d(t,"WebXRState",function(){return n.WebXRState}),i.d(t,"WebXRExperienceHelper",function(){return n.WebXRExperienceHelper}),i.d(t,"WebXRController",function(){return n.WebXRController}),i.d(t,"WebXRInput",function(){return n.WebXRInput}),i.d(t,"WebXRManagedOutputCanvas",function(){return n.WebXRManagedOutputCanvas}),i.d(t,"WebXRSessionManager",function(){return n.WebXRSessionManager}),i.d(t,"Octree",function(){return n.Octree}),i.d(t,"OctreeBlock",function(){return n.OctreeBlock}),i.d(t,"OctreeSceneComponent",function(){return n.OctreeSceneComponent}),i.d(t,"_OcclusionDataStorage",function(){return n._OcclusionDataStorage}),i.d(t,"_forceTransformFeedbackToBundle",function(){return n._forceTransformFeedbackToBundle}),i.d(t,"DaydreamController",function(){return n.DaydreamController}),i.d(t,"GearVRController",function(){return n.GearVRController}),i.d(t,"GenericController",function(){return n.GenericController}),i.d(t,"OculusTouchController",function(){return n.OculusTouchController}),i.d(t,"PoseEnabledControllerType",function(){return n.PoseEnabledControllerType}),i.d(t,"PoseEnabledControllerHelper",function(){return n.PoseEnabledControllerHelper}),i.d(t,"PoseEnabledController",function(){return n.PoseEnabledController}),i.d(t,"ViveController",function(){return n.ViveController}),i.d(t,"WebVRController",function(){return n.WebVRController}),i.d(t,"WindowsMotionController",function(){return n.WindowsMotionController}),i.d(t,"ShadowGenerator",function(){return n.ShadowGenerator}),i.d(t,"ShadowGeneratorSceneComponent",function(){return n.ShadowGeneratorSceneComponent}),i.d(t,"_BabylonLoaderRegistered",function(){return n._BabylonLoaderRegistered}),i.d(t,"BackgroundMaterial",function(){return n.BackgroundMaterial}),i.d(t,"PBRBaseSimpleMaterial",function(){return n.PBRBaseSimpleMaterial}),i.d(t,"PBRMetallicRoughnessMaterial",function(){return n.PBRMetallicRoughnessMaterial}),i.d(t,"PBRSpecularGlossinessMaterial",function(){return n.PBRSpecularGlossinessMaterial}),i.d(t,"ColorGradingTexture",function(){return n.ColorGradingTexture}),i.d(t,"_DDSTextureLoader",function(){return n._DDSTextureLoader}),i.d(t,"_ENVTextureLoader",function(){return n._ENVTextureLoader}),i.d(t,"_KTXTextureLoader",function(){return n._KTXTextureLoader}),i.d(t,"ProceduralTexture",function(){return n.ProceduralTexture}),i.d(t,"RawCubeTexture",function(){return n.RawCubeTexture}),i.d(t,"RawTexture",function(){return n.RawTexture}),i.d(t,"RawTexture3D",function(){return n.RawTexture3D}),i.d(t,"RefractionTexture",function(){return n.RefractionTexture}),i.d(t,"HtmlElementTexture",function(){return n.HtmlElementTexture}),i.d(t,"NodeMaterialBlockTargets",function(){return n.NodeMaterialBlockTargets}),i.d(t,"NodeMaterialBlockConnectionPointTypes",function(){return n.NodeMaterialBlockConnectionPointTypes}),i.d(t,"NodeMaterialConnectionPoint",function(){return n.NodeMaterialConnectionPoint}),i.d(t,"NodeMaterialBlock",function(){return n.NodeMaterialBlock}),i.d(t,"NodeMaterialDefines",function(){return n.NodeMaterialDefines}),i.d(t,"NodeMaterial",function(){return n.NodeMaterial}),i.d(t,"NodeMaterialWellKnownValues",function(){return n.NodeMaterialWellKnownValues}),i.d(t,"DracoCompression",function(){return n.DracoCompression}),i.d(t,"TiledBoxBuilder",function(){return n.TiledBoxBuilder}),i.d(t,"DiscBuilder",function(){return n.DiscBuilder}),i.d(t,"RibbonBuilder",function(){return n.RibbonBuilder}),i.d(t,"HemisphereBuilder",function(){return n.HemisphereBuilder}),i.d(t,"TorusKnotBuilder",function(){return n.TorusKnotBuilder}),i.d(t,"PolygonBuilder",function(){return n.PolygonBuilder}),i.d(t,"ShapeBuilder",function(){return n.ShapeBuilder}),i.d(t,"LatheBuilder",function(){return n.LatheBuilder}),i.d(t,"TiledPlaneBuilder",function(){return n.TiledPlaneBuilder}),i.d(t,"TubeBuilder",function(){return n.TubeBuilder}),i.d(t,"PolyhedronBuilder",function(){return n.PolyhedronBuilder}),i.d(t,"IcoSphereBuilder",function(){return n.IcoSphereBuilder}),i.d(t,"DecalBuilder",function(){return n.DecalBuilder}),i.d(t,"BoxParticleEmitter",function(){return n.BoxParticleEmitter}),i.d(t,"ConeParticleEmitter",function(){return n.ConeParticleEmitter}),i.d(t,"CylinderParticleEmitter",function(){return n.CylinderParticleEmitter}),i.d(t,"CylinderDirectedParticleEmitter",function(){return n.CylinderDirectedParticleEmitter}),i.d(t,"HemisphericParticleEmitter",function(){return n.HemisphericParticleEmitter}),i.d(t,"PointParticleEmitter",function(){return n.PointParticleEmitter}),i.d(t,"SphereParticleEmitter",function(){return n.SphereParticleEmitter}),i.d(t,"SphereDirectedParticleEmitter",function(){return n.SphereDirectedParticleEmitter}),i.d(t,"CannonJSPlugin",function(){return n.CannonJSPlugin}),i.d(t,"AmmoJSPlugin",function(){return n.AmmoJSPlugin}),i.d(t,"OimoJSPlugin",function(){return n.OimoJSPlugin}),i.d(t,"PostProcessRenderEffect",function(){return n.PostProcessRenderEffect}),i.d(t,"PostProcessRenderPipeline",function(){return n.PostProcessRenderPipeline}),i.d(t,"PostProcessRenderPipelineManager",function(){return n.PostProcessRenderPipelineManager}),i.d(t,"PostProcessRenderPipelineManagerSceneComponent",function(){return n.PostProcessRenderPipelineManagerSceneComponent}),i.d(t,"HDRTools",function(){return n.HDRTools}),i.d(t,"PanoramaToCubeMapTools",function(){return n.PanoramaToCubeMapTools}),i.d(t,"_TGATextureLoader",function(){return n._TGATextureLoader}),i.d(t,"CustomProceduralTexture",function(){return n.CustomProceduralTexture}),i.d(t,"NoiseProceduralTexture",function(){return n.NoiseProceduralTexture}),i.d(t,"ProceduralTextureSceneComponent",function(){return n.ProceduralTextureSceneComponent}),i.d(t,"MultiplyBlock",function(){return n.MultiplyBlock}),i.d(t,"AddBlock",function(){return n.AddBlock}),i.d(t,"ClampBlock",function(){return n.ClampBlock}),i.d(t,"Vector2TransformBlock",function(){return n.Vector2TransformBlock}),i.d(t,"Vector3TransformBlock",function(){return n.Vector3TransformBlock}),i.d(t,"Vector4TransformBlock",function(){return n.Vector4TransformBlock}),i.d(t,"MatrixMultiplicationBlock",function(){return n.MatrixMultiplicationBlock}),i.d(t,"NodeMaterialOptimizer",function(){return n.NodeMaterialOptimizer}),i.d(t,"DefaultRenderingPipeline",function(){return n.DefaultRenderingPipeline}),i.d(t,"LensRenderingPipeline",function(){return n.LensRenderingPipeline}),i.d(t,"SSAO2RenderingPipeline",function(){return n.SSAO2RenderingPipeline}),i.d(t,"SSAORenderingPipeline",function(){return n.SSAORenderingPipeline}),i.d(t,"StandardRenderingPipeline",function(){return n.StandardRenderingPipeline}),i.d(t,"VertexOutputBlock",function(){return n.VertexOutputBlock}),i.d(t,"BonesBlock",function(){return n.BonesBlock}),i.d(t,"InstancesBlock",function(){return n.InstancesBlock}),i.d(t,"MorphTargetsBlock",function(){return n.MorphTargetsBlock}),i.d(t,"FragmentOutputBlock",function(){return n.FragmentOutputBlock}),i.d(t,"AlphaTestBlock",function(){return n.AlphaTestBlock}),i.d(t,"RGBAMergerBlock",function(){return n.RGBAMergerBlock}),i.d(t,"RGBMergerBlock",function(){return n.RGBMergerBlock}),i.d(t,"RGBASplitterBlock",function(){return n.RGBASplitterBlock}),i.d(t,"RGBSplitterBlock",function(){return n.RGBSplitterBlock}),i.d(t,"TextureBlock",function(){return n.TextureBlock}),i.d(t,"ImageProcessingBlock",function(){return n.ImageProcessingBlock}),i.d(t,"FogBlock",function(){return n.FogBlock});var o=void 0!==e?e:"undefined"!=typeof window?window:void 0;if(void 0!==o){o.BABYLON=s,o.BABYLON=o.BABYLON||{};var s=o.BABYLON;s.Debug=s.Debug||{};var a=[];for(var c in r)s.Debug[c]=r[c],a.push(c);for(var c in n)s[c]=n[c]}var l={AxesViewer:r.AxesViewer,BoneAxesViewer:r.BoneAxesViewer,PhysicsViewer:r.PhysicsViewer,SkeletonViewer:r.SkeletonViewer}}.call(this,i(120))}])}); \ No newline at end of file diff --git a/Source/Scripts/babylon.max.js b/Source/Scripts/babylon.max.js new file mode 100644 index 000000000..57012da1b --- /dev/null +++ b/Source/Scripts/babylon.max.js @@ -0,0 +1,156252 @@ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define("babylonjs", [], factory); + else if(typeof exports === 'object') + exports["babylonjs"] = factory(); + else + root["BABYLON"] = factory(); +})((typeof self !== "undefined" ? self : typeof global !== "undefined" ? global : this), function() { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) { +/******/ return installedModules[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ i: moduleId, +/******/ l: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.l = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // define getter function for harmony exports +/******/ __webpack_require__.d = function(exports, name, getter) { +/******/ if(!__webpack_require__.o(exports, name)) { +/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); +/******/ } +/******/ }; +/******/ +/******/ // define __esModule on exports +/******/ __webpack_require__.r = function(exports) { +/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { +/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); +/******/ } +/******/ Object.defineProperty(exports, '__esModule', { value: true }); +/******/ }; +/******/ +/******/ // create a fake namespace object +/******/ // mode & 1: value is a module id, require it +/******/ // mode & 2: merge all properties of value into the ns +/******/ // mode & 4: return value when already ns object +/******/ // mode & 8|1: behave like require +/******/ __webpack_require__.t = function(value, mode) { +/******/ if(mode & 1) value = __webpack_require__(value); +/******/ if(mode & 8) return value; +/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; +/******/ var ns = Object.create(null); +/******/ __webpack_require__.r(ns); +/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); +/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); +/******/ return ns; +/******/ }; +/******/ +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __webpack_require__.d(getter, 'a', getter); +/******/ return getter; +/******/ }; +/******/ +/******/ // Object.prototype.hasOwnProperty.call +/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; +/******/ +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(__webpack_require__.s = "./Legacy/legacy.ts"); +/******/ }) +/************************************************************************/ +/******/ ({ + +/***/ "../node_modules/tslib/tslib.es6.js": +/*!******************************************!*\ + !*** ../node_modules/tslib/tslib.es6.js ***! + \******************************************/ +/*! exports provided: __extends, __assign, __rest, __decorate, __param, __metadata, __awaiter, __generator, __exportStar, __values, __read, __spread, __await, __asyncGenerator, __asyncDelegator, __asyncValues, __makeTemplateObject, __importStar, __importDefault */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__extends", function() { return __extends; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__assign", function() { return __assign; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__rest", function() { return __rest; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__decorate", function() { return __decorate; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__param", function() { return __param; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__metadata", function() { return __metadata; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__awaiter", function() { return __awaiter; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__generator", function() { return __generator; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__exportStar", function() { return __exportStar; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__values", function() { return __values; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__read", function() { return __read; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__spread", function() { return __spread; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__await", function() { return __await; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncGenerator", function() { return __asyncGenerator; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncDelegator", function() { return __asyncDelegator; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncValues", function() { return __asyncValues; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__makeTemplateObject", function() { return __makeTemplateObject; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__importStar", function() { return __importStar; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__importDefault", function() { return __importDefault; }); +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. 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 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* global Reflect, Promise */ + +var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); +}; + +function __extends(d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} + +var __assign = function() { + __assign = Object.assign || function __assign(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + } + return __assign.apply(this, arguments); +} + +function __rest(s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0) + t[p[i]] = s[p[i]]; + return t; +} + +function __decorate(decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +} + +function __param(paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } +} + +function __metadata(metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); +} + +function __awaiter(thisArg, _arguments, P, generator) { + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} + +function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +} + +function __exportStar(m, exports) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; +} + +function __values(o) { + var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; + if (m) return m.call(o); + return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; +} + +function __read(o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; +} + +function __spread() { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; +} + +function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); +} + +function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } +} + +function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } +} + +function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } +} + +function __makeTemplateObject(cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; +}; + +function __importStar(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result.default = mod; + return result; +} + +function __importDefault(mod) { + return (mod && mod.__esModule) ? mod : { default: mod }; +} + + +/***/ }), + +/***/ "../node_modules/webpack/buildin/global.js": +/*!*************************************************!*\ + !*** ../node_modules/webpack/buildin/global.js ***! + \*************************************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +var g; + +// This works in non-strict mode +g = (function() { + return this; +})(); + +try { + // This works if eval is allowed (see CSP) + g = g || new Function("return this")(); +} catch (e) { + // This works if the window reference is available + if (typeof window === "object") g = window; +} + +// g can still be undefined, but nothing to do about it... +// We return undefined, instead of nothing here, so it's +// easier to handle this case. if(!global) { ...} + +module.exports = g; + + +/***/ }), + +/***/ "./Actions/abstractActionManager.ts": +/*!******************************************!*\ + !*** ./Actions/abstractActionManager.ts ***! + \******************************************/ +/*! exports provided: AbstractActionManager */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AbstractActionManager", function() { return AbstractActionManager; }); +/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts"); + +/** + * Abstract class used to decouple action Manager from scene and meshes. + * Do not instantiate. + * @see http://doc.babylonjs.com/how_to/how_to_use_actions + */ +var AbstractActionManager = /** @class */ (function () { + function AbstractActionManager() { + /** Gets the cursor to use when hovering items */ + this.hoverCursor = ''; + /** Gets the list of actions */ + this.actions = new Array(); + /** + * Gets or sets a boolean indicating that the manager is recursive meaning that it can trigger action from children + */ + this.isRecursive = false; + } + Object.defineProperty(AbstractActionManager, "HasTriggers", { + /** + * Does exist one action manager with at least one trigger + **/ + get: function () { + for (var t in AbstractActionManager.Triggers) { + if (AbstractActionManager.Triggers.hasOwnProperty(t)) { + return true; + } + } + return false; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(AbstractActionManager, "HasPickTriggers", { + /** + * Does exist one action manager with at least one pick trigger + **/ + get: function () { + for (var t in AbstractActionManager.Triggers) { + if (AbstractActionManager.Triggers.hasOwnProperty(t)) { + var t_int = parseInt(t); + if (t_int >= _Engines_constants__WEBPACK_IMPORTED_MODULE_0__["Constants"].ACTION_OnPickTrigger && t_int <= _Engines_constants__WEBPACK_IMPORTED_MODULE_0__["Constants"].ACTION_OnPickUpTrigger) { + return true; + } + } + } + return false; + }, + enumerable: true, + configurable: true + }); + /** + * Does exist one action manager that handles actions of a given trigger + * @param trigger defines the trigger to be tested + * @return a boolean indicating whether the trigger is handeled by at least one action manager + **/ + AbstractActionManager.HasSpecificTrigger = function (trigger) { + for (var t in AbstractActionManager.Triggers) { + if (AbstractActionManager.Triggers.hasOwnProperty(t)) { + var t_int = parseInt(t); + if (t_int === trigger) { + return true; + } + } + } + return false; + }; + /** Gets the list of active triggers */ + AbstractActionManager.Triggers = {}; + return AbstractActionManager; +}()); + + + +/***/ }), + +/***/ "./Actions/action.ts": +/*!***************************!*\ + !*** ./Actions/action.ts ***! + \***************************/ +/*! exports provided: Action */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Action", function() { return Action; }); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/typeStore */ "./Misc/typeStore.ts"); + + + +/** + * The action to be carried out following a trigger + * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions + */ +var Action = /** @class */ (function () { + /** + * Creates a new Action + * @param triggerOptions the trigger, with or without parameters, for the action + * @param condition an optional determinant of action + */ + function Action( + /** the trigger, with or without parameters, for the action */ + triggerOptions, condition) { + this.triggerOptions = triggerOptions; + /** + * An event triggered prior to action being executed. + */ + this.onBeforeExecuteObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](); + if (triggerOptions.parameter) { + this.trigger = triggerOptions.trigger; + this._triggerParameter = triggerOptions.parameter; + } + else if (triggerOptions.trigger) { + this.trigger = triggerOptions.trigger; + } + else { + this.trigger = triggerOptions; + } + this._nextActiveAction = this; + this._condition = condition; + } + /** + * Internal only + * @hidden + */ + Action.prototype._prepare = function () { + }; + /** + * Gets the trigger parameters + * @returns the trigger parameters + */ + Action.prototype.getTriggerParameter = function () { + return this._triggerParameter; + }; + /** + * Internal only - executes current action event + * @hidden + */ + Action.prototype._executeCurrent = function (evt) { + if (this._nextActiveAction._condition) { + var condition = this._nextActiveAction._condition; + var currentRenderId = this._actionManager.getScene().getRenderId(); + // We cache the current evaluation for the current frame + if (condition._evaluationId === currentRenderId) { + if (!condition._currentResult) { + return; + } + } + else { + condition._evaluationId = currentRenderId; + if (!condition.isValid()) { + condition._currentResult = false; + return; + } + condition._currentResult = true; + } + } + this.onBeforeExecuteObservable.notifyObservers(this); + this._nextActiveAction.execute(evt); + this.skipToNextActiveAction(); + }; + /** + * Execute placeholder for child classes + * @param evt optional action event + */ + Action.prototype.execute = function (evt) { + }; + /** + * Skips to next active action + */ + Action.prototype.skipToNextActiveAction = function () { + if (this._nextActiveAction._child) { + if (!this._nextActiveAction._child._actionManager) { + this._nextActiveAction._child._actionManager = this._actionManager; + } + this._nextActiveAction = this._nextActiveAction._child; + } + else { + this._nextActiveAction = this; + } + }; + /** + * Adds action to chain of actions, may be a DoNothingAction + * @param action defines the next action to execute + * @returns The action passed in + * @see https://www.babylonjs-playground.com/#1T30HR#0 + */ + Action.prototype.then = function (action) { + this._child = action; + action._actionManager = this._actionManager; + action._prepare(); + return action; + }; + /** + * Internal only + * @hidden + */ + Action.prototype._getProperty = function (propertyPath) { + return this._actionManager._getProperty(propertyPath); + }; + /** + * Internal only + * @hidden + */ + Action.prototype._getEffectiveTarget = function (target, propertyPath) { + return this._actionManager._getEffectiveTarget(target, propertyPath); + }; + /** + * Serialize placeholder for child classes + * @param parent of child + * @returns the serialized object + */ + Action.prototype.serialize = function (parent) { + }; + /** + * Internal only called by serialize + * @hidden + */ + Action.prototype._serialize = function (serializedAction, parent) { + var serializationObject = { + type: 1, + children: [], + name: serializedAction.name, + properties: serializedAction.properties || [] + }; + // Serialize child + if (this._child) { + this._child.serialize(serializationObject); + } + // Check if "this" has a condition + if (this._condition) { + var serializedCondition = this._condition.serialize(); + serializedCondition.children.push(serializationObject); + if (parent) { + parent.children.push(serializedCondition); + } + return serializedCondition; + } + if (parent) { + parent.children.push(serializationObject); + } + return serializationObject; + }; + /** + * Internal only + * @hidden + */ + Action._SerializeValueAsString = function (value) { + if (typeof value === "number") { + return value.toString(); + } + if (typeof value === "boolean") { + return value ? "true" : "false"; + } + if (value instanceof _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector2"]) { + return value.x + ", " + value.y; + } + if (value instanceof _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"]) { + return value.x + ", " + value.y + ", " + value.z; + } + if (value instanceof _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Color3"]) { + return value.r + ", " + value.g + ", " + value.b; + } + if (value instanceof _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Color4"]) { + return value.r + ", " + value.g + ", " + value.b + ", " + value.a; + } + return value; // string + }; + /** + * Internal only + * @hidden + */ + Action._GetTargetProperty = function (target) { + return { + name: "target", + targetType: target._isMesh ? "MeshProperties" + : target._isLight ? "LightProperties" + : target._isCamera ? "CameraProperties" + : "SceneProperties", + value: target._isScene ? "Scene" : target.name + }; + }; + return Action; +}()); + +_Misc_typeStore__WEBPACK_IMPORTED_MODULE_2__["_TypeStore"].RegisteredTypes["BABYLON.Action"] = Action; + + +/***/ }), + +/***/ "./Actions/actionEvent.ts": +/*!********************************!*\ + !*** ./Actions/actionEvent.ts ***! + \********************************/ +/*! exports provided: ActionEvent */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ActionEvent", function() { return ActionEvent; }); +/** + * ActionEvent is the event being sent when an action is triggered. + */ +var ActionEvent = /** @class */ (function () { + /** + * Creates a new ActionEvent + * @param source The mesh or sprite that triggered the action + * @param pointerX The X mouse cursor position at the time of the event + * @param pointerY The Y mouse cursor position at the time of the event + * @param meshUnderPointer The mesh that is currently pointed at (can be null) + * @param sourceEvent the original (browser) event that triggered the ActionEvent + * @param additionalData additional data for the event + */ + function ActionEvent( + /** The mesh or sprite that triggered the action */ + source, + /** The X mouse cursor position at the time of the event */ + pointerX, + /** The Y mouse cursor position at the time of the event */ + pointerY, + /** The mesh that is currently pointed at (can be null) */ + meshUnderPointer, + /** the original (browser) event that triggered the ActionEvent */ + sourceEvent, + /** additional data for the event */ + additionalData) { + this.source = source; + this.pointerX = pointerX; + this.pointerY = pointerY; + this.meshUnderPointer = meshUnderPointer; + this.sourceEvent = sourceEvent; + this.additionalData = additionalData; + } + /** + * Helper function to auto-create an ActionEvent from a source mesh. + * @param source The source mesh that triggered the event + * @param evt The original (browser) event + * @param additionalData additional data for the event + * @returns the new ActionEvent + */ + ActionEvent.CreateNew = function (source, evt, additionalData) { + var scene = source.getScene(); + return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer || source, evt, additionalData); + }; + /** + * Helper function to auto-create an ActionEvent from a source sprite + * @param source The source sprite that triggered the event + * @param scene Scene associated with the sprite + * @param evt The original (browser) event + * @param additionalData additional data for the event + * @returns the new ActionEvent + */ + ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) { + return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData); + }; + /** + * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew + * @param scene the scene where the event occurred + * @param evt The original (browser) event + * @returns the new ActionEvent + */ + ActionEvent.CreateNewFromScene = function (scene, evt) { + return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt); + }; + /** + * Helper function to auto-create an ActionEvent from a primitive + * @param prim defines the target primitive + * @param pointerPos defines the pointer position + * @param evt The original (browser) event + * @param additionalData additional data for the event + * @returns the new ActionEvent + */ + ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) { + return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData); + }; + return ActionEvent; +}()); + + + +/***/ }), + +/***/ "./Actions/actionManager.ts": +/*!**********************************!*\ + !*** ./Actions/actionManager.ts ***! + \**********************************/ +/*! exports provided: ActionManager */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ActionManager", function() { return ActionManager; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _condition__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./condition */ "./Actions/condition.ts"); +/* harmony import */ var _action__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./action */ "./Actions/action.ts"); +/* harmony import */ var _directActions__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./directActions */ "./Actions/directActions.ts"); +/* harmony import */ var _Engines_engineStore__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Engines/engineStore */ "./Engines/engineStore.ts"); +/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts"); +/* harmony import */ var _Misc_deepCopier__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Misc/deepCopier */ "./Misc/deepCopier.ts"); +/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Misc/typeStore */ "./Misc/typeStore.ts"); +/* harmony import */ var _abstractActionManager__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./abstractActionManager */ "./Actions/abstractActionManager.ts"); +/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts"); + + + + + + + + + + + +/** + * Action Manager manages all events to be triggered on a given mesh or the global scene. + * A single scene can have many Action Managers to handle predefined actions on specific meshes. + * @see http://doc.babylonjs.com/how_to/how_to_use_actions + */ +var ActionManager = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ActionManager, _super); + /** + * Creates a new action manager + * @param scene defines the hosting scene + */ + function ActionManager(scene) { + var _this = _super.call(this) || this; + _this._scene = scene || _Engines_engineStore__WEBPACK_IMPORTED_MODULE_5__["EngineStore"].LastCreatedScene; + scene.actionManagers.push(_this); + return _this; + } + // Methods + /** + * Releases all associated resources + */ + ActionManager.prototype.dispose = function () { + var index = this._scene.actionManagers.indexOf(this); + for (var i = 0; i < this.actions.length; i++) { + var action = this.actions[i]; + ActionManager.Triggers[action.trigger]--; + if (ActionManager.Triggers[action.trigger] === 0) { + delete ActionManager.Triggers[action.trigger]; + } + } + if (index > -1) { + this._scene.actionManagers.splice(index, 1); + } + }; + /** + * Gets hosting scene + * @returns the hosting scene + */ + ActionManager.prototype.getScene = function () { + return this._scene; + }; + /** + * Does this action manager handles actions of any of the given triggers + * @param triggers defines the triggers to be tested + * @return a boolean indicating whether one (or more) of the triggers is handled + */ + ActionManager.prototype.hasSpecificTriggers = function (triggers) { + for (var index = 0; index < this.actions.length; index++) { + var action = this.actions[index]; + if (triggers.indexOf(action.trigger) > -1) { + return true; + } + } + return false; + }; + /** + * Does this action manager handles actions of any of the given triggers. This function takes two arguments for + * speed. + * @param triggerA defines the trigger to be tested + * @param triggerB defines the trigger to be tested + * @return a boolean indicating whether one (or more) of the triggers is handled + */ + ActionManager.prototype.hasSpecificTriggers2 = function (triggerA, triggerB) { + for (var index = 0; index < this.actions.length; index++) { + var action = this.actions[index]; + if (triggerA == action.trigger || triggerB == action.trigger) { + return true; + } + } + return false; + }; + /** + * Does this action manager handles actions of a given trigger + * @param trigger defines the trigger to be tested + * @param parameterPredicate defines an optional predicate to filter triggers by parameter + * @return whether the trigger is handled + */ + ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) { + for (var index = 0; index < this.actions.length; index++) { + var action = this.actions[index]; + if (action.trigger === trigger) { + if (parameterPredicate) { + if (parameterPredicate(action.getTriggerParameter())) { + return true; + } + } + else { + return true; + } + } + } + return false; + }; + Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", { + /** + * Does this action manager has pointer triggers + */ + get: function () { + for (var index = 0; index < this.actions.length; index++) { + var action = this.actions[index]; + if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPointerOutTrigger) { + return true; + } + } + return false; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ActionManager.prototype, "hasPickTriggers", { + /** + * Does this action manager has pick triggers + */ + get: function () { + for (var index = 0; index < this.actions.length; index++) { + var action = this.actions[index]; + if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPickUpTrigger) { + return true; + } + } + return false; + }, + enumerable: true, + configurable: true + }); + /** + * Registers an action to this action manager + * @param action defines the action to be registered + * @return the action amended (prepared) after registration + */ + ActionManager.prototype.registerAction = function (action) { + if (action.trigger === ActionManager.OnEveryFrameTrigger) { + if (this.getScene().actionManager !== this) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_6__["Logger"].Warn("OnEveryFrameTrigger can only be used with scene.actionManager"); + return null; + } + } + this.actions.push(action); + if (ActionManager.Triggers[action.trigger]) { + ActionManager.Triggers[action.trigger]++; + } + else { + ActionManager.Triggers[action.trigger] = 1; + } + action._actionManager = this; + action._prepare(); + return action; + }; + /** + * Unregisters an action to this action manager + * @param action defines the action to be unregistered + * @return a boolean indicating whether the action has been unregistered + */ + ActionManager.prototype.unregisterAction = function (action) { + var index = this.actions.indexOf(action); + if (index !== -1) { + this.actions.splice(index, 1); + ActionManager.Triggers[action.trigger] -= 1; + if (ActionManager.Triggers[action.trigger] === 0) { + delete ActionManager.Triggers[action.trigger]; + } + delete action._actionManager; + return true; + } + return false; + }; + /** + * Process a specific trigger + * @param trigger defines the trigger to process + * @param evt defines the event details to be processed + */ + ActionManager.prototype.processTrigger = function (trigger, evt) { + for (var index = 0; index < this.actions.length; index++) { + var action = this.actions[index]; + if (action.trigger === trigger) { + if (evt) { + if (trigger === ActionManager.OnKeyUpTrigger + || trigger === ActionManager.OnKeyDownTrigger) { + var parameter = action.getTriggerParameter(); + if (parameter && parameter !== evt.sourceEvent.keyCode) { + if (!parameter.toLowerCase) { + continue; + } + var lowerCase = parameter.toLowerCase(); + if (lowerCase !== evt.sourceEvent.key) { + var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode; + var actualkey = String.fromCharCode(unicode).toLowerCase(); + if (actualkey !== lowerCase) { + continue; + } + } + } + } + } + action._executeCurrent(evt); + } + } + }; + /** @hidden */ + ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) { + var properties = propertyPath.split("."); + for (var index = 0; index < properties.length - 1; index++) { + target = target[properties[index]]; + } + return target; + }; + /** @hidden */ + ActionManager.prototype._getProperty = function (propertyPath) { + var properties = propertyPath.split("."); + return properties[properties.length - 1]; + }; + /** + * Serialize this manager to a JSON object + * @param name defines the property name to store this manager + * @returns a JSON representation of this manager + */ + ActionManager.prototype.serialize = function (name) { + var root = { + children: new Array(), + name: name, + type: 3, + properties: new Array() // Empty for root but required + }; + for (var i = 0; i < this.actions.length; i++) { + var triggerObject = { + type: 0, + children: new Array(), + name: ActionManager.GetTriggerName(this.actions[i].trigger), + properties: new Array() + }; + var triggerOptions = this.actions[i].triggerOptions; + if (triggerOptions && typeof triggerOptions !== "number") { + if (triggerOptions.parameter instanceof Node) { + triggerObject.properties.push(_action__WEBPACK_IMPORTED_MODULE_3__["Action"]._GetTargetProperty(triggerOptions.parameter)); + } + else { + var parameter = {}; + _Misc_deepCopier__WEBPACK_IMPORTED_MODULE_7__["DeepCopier"].DeepCopy(triggerOptions.parameter, parameter, ["mesh"]); + if (triggerOptions.parameter && triggerOptions.parameter.mesh) { + parameter._meshId = triggerOptions.parameter.mesh.id; + } + triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter }); + } + } + // Serialize child action, recursively + this.actions[i].serialize(triggerObject); + // Add serialized trigger + root.children.push(triggerObject); + } + return root; + }; + /** + * Creates a new ActionManager from a JSON data + * @param parsedActions defines the JSON data to read from + * @param object defines the hosting mesh + * @param scene defines the hosting scene + */ + ActionManager.Parse = function (parsedActions, object, scene) { + var actionManager = new ActionManager(scene); + if (object === null) { + scene.actionManager = actionManager; + } + else { + object.actionManager = actionManager; + } + // instanciate a new object + var instanciate = function (name, params) { + var internalClassType = _Misc_typeStore__WEBPACK_IMPORTED_MODULE_8__["_TypeStore"].GetClass("BABYLON." + name); + if (internalClassType) { + var newInstance = Object.create(internalClassType.prototype); + newInstance.constructor.apply(newInstance, params); + return newInstance; + } + }; + var parseParameter = function (name, value, target, propertyPath) { + if (propertyPath === null) { + // String, boolean or float + var floatValue = parseFloat(value); + if (value === "true" || value === "false") { + return value === "true"; + } + else { + return isNaN(floatValue) ? value : floatValue; + } + } + var effectiveTarget = propertyPath.split("."); + var values = value.split(","); + // Get effective Target + for (var i = 0; i < effectiveTarget.length; i++) { + target = target[effectiveTarget[i]]; + } + // Return appropriate value with its type + if (typeof (target) === "boolean") { + return values[0] === "true"; + } + if (typeof (target) === "string") { + return values[0]; + } + // Parameters with multiple values such as Vector3 etc. + var split = new Array(); + for (var i = 0; i < values.length; i++) { + split.push(parseFloat(values[i])); + } + if (target instanceof _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"]) { + return _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].FromArray(split); + } + if (target instanceof _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector4"]) { + return _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector4"].FromArray(split); + } + if (target instanceof _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Color3"]) { + return _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Color3"].FromArray(split); + } + if (target instanceof _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Color4"]) { + return _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Color4"].FromArray(split); + } + return parseFloat(values[0]); + }; + // traverse graph per trigger + var traverse = function (parsedAction, trigger, condition, action, combineArray) { + if (combineArray === void 0) { combineArray = null; } + if (parsedAction.detached) { + return; + } + var parameters = new Array(); + var target = null; + var propertyPath = null; + var combine = parsedAction.combine && parsedAction.combine.length > 0; + // Parameters + if (parsedAction.type === 2) { + parameters.push(actionManager); + } + else { + parameters.push(trigger); + } + if (combine) { + var actions = new Array(); + for (var j = 0; j < parsedAction.combine.length; j++) { + traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions); + } + parameters.push(actions); + } + else { + for (var i = 0; i < parsedAction.properties.length; i++) { + var value = parsedAction.properties[i].value; + var name = parsedAction.properties[i].name; + var targetType = parsedAction.properties[i].targetType; + if (name === "target") { + if (targetType !== null && targetType === "SceneProperties") { + value = target = scene; + } + else { + value = target = scene.getNodeByName(value); + } + } + else if (name === "parent") { + value = scene.getNodeByName(value); + } + else if (name === "sound") { + // Can not externalize to component, so only checks for the presence off the API. + if (scene.getSoundByName) { + value = scene.getSoundByName(value); + } + } + else if (name !== "propertyPath") { + if (parsedAction.type === 2 && name === "operator") { + value = _condition__WEBPACK_IMPORTED_MODULE_2__["ValueCondition"][value]; + } + else { + value = parseParameter(name, value, target, name === "value" ? propertyPath : null); + } + } + else { + propertyPath = value; + } + parameters.push(value); + } + } + if (combineArray === null) { + parameters.push(condition); + } + else { + parameters.push(null); + } + // If interpolate value action + if (parsedAction.name === "InterpolateValueAction") { + var param = parameters[parameters.length - 2]; + parameters[parameters.length - 1] = param; + parameters[parameters.length - 2] = condition; + } + // Action or condition(s) and not CombineAction + var newAction = instanciate(parsedAction.name, parameters); + if (newAction instanceof _condition__WEBPACK_IMPORTED_MODULE_2__["Condition"] && condition !== null) { + var nothing = new _directActions__WEBPACK_IMPORTED_MODULE_4__["DoNothingAction"](trigger, condition); + if (action) { + action.then(nothing); + } + else { + actionManager.registerAction(nothing); + } + action = nothing; + } + if (combineArray === null) { + if (newAction instanceof _condition__WEBPACK_IMPORTED_MODULE_2__["Condition"]) { + condition = newAction; + newAction = action; + } + else { + condition = null; + if (action) { + action.then(newAction); + } + else { + actionManager.registerAction(newAction); + } + } + } + else { + combineArray.push(newAction); + } + for (var i = 0; i < parsedAction.children.length; i++) { + traverse(parsedAction.children[i], trigger, condition, newAction, null); + } + }; + // triggers + for (var i = 0; i < parsedActions.children.length; i++) { + var triggerParams; + var trigger = parsedActions.children[i]; + if (trigger.properties.length > 0) { + var param = trigger.properties[0].value; + var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param); + if (value._meshId) { + value.mesh = scene.getMeshByID(value._meshId); + } + triggerParams = { trigger: ActionManager[trigger.name], parameter: value }; + } + else { + triggerParams = ActionManager[trigger.name]; + } + for (var j = 0; j < trigger.children.length; j++) { + if (!trigger.detached) { + traverse(trigger.children[j], triggerParams, null, null); + } + } + } + }; + /** + * Get a trigger name by index + * @param trigger defines the trigger index + * @returns a trigger name + */ + ActionManager.GetTriggerName = function (trigger) { + switch (trigger) { + case 0: return "NothingTrigger"; + case 1: return "OnPickTrigger"; + case 2: return "OnLeftPickTrigger"; + case 3: return "OnRightPickTrigger"; + case 4: return "OnCenterPickTrigger"; + case 5: return "OnPickDownTrigger"; + case 6: return "OnPickUpTrigger"; + case 7: return "OnLongPressTrigger"; + case 8: return "OnPointerOverTrigger"; + case 9: return "OnPointerOutTrigger"; + case 10: return "OnEveryFrameTrigger"; + case 11: return "OnIntersectionEnterTrigger"; + case 12: return "OnIntersectionExitTrigger"; + case 13: return "OnKeyDownTrigger"; + case 14: return "OnKeyUpTrigger"; + case 15: return "OnPickOutTrigger"; + default: return ""; + } + }; + /** + * Nothing + * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers + */ + ActionManager.NothingTrigger = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].ACTION_NothingTrigger; + /** + * On pick + * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers + */ + ActionManager.OnPickTrigger = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].ACTION_OnPickTrigger; + /** + * On left pick + * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers + */ + ActionManager.OnLeftPickTrigger = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].ACTION_OnLeftPickTrigger; + /** + * On right pick + * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers + */ + ActionManager.OnRightPickTrigger = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].ACTION_OnRightPickTrigger; + /** + * On center pick + * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers + */ + ActionManager.OnCenterPickTrigger = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].ACTION_OnCenterPickTrigger; + /** + * On pick down + * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers + */ + ActionManager.OnPickDownTrigger = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].ACTION_OnPickDownTrigger; + /** + * On double pick + * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers + */ + ActionManager.OnDoublePickTrigger = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].ACTION_OnDoublePickTrigger; + /** + * On pick up + * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers + */ + ActionManager.OnPickUpTrigger = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].ACTION_OnPickUpTrigger; + /** + * On pick out. + * This trigger will only be raised if you also declared a OnPickDown + * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers + */ + ActionManager.OnPickOutTrigger = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].ACTION_OnPickOutTrigger; + /** + * On long press + * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers + */ + ActionManager.OnLongPressTrigger = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].ACTION_OnLongPressTrigger; + /** + * On pointer over + * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers + */ + ActionManager.OnPointerOverTrigger = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].ACTION_OnPointerOverTrigger; + /** + * On pointer out + * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers + */ + ActionManager.OnPointerOutTrigger = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].ACTION_OnPointerOutTrigger; + /** + * On every frame + * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers + */ + ActionManager.OnEveryFrameTrigger = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].ACTION_OnEveryFrameTrigger; + /** + * On intersection enter + * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers + */ + ActionManager.OnIntersectionEnterTrigger = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].ACTION_OnIntersectionEnterTrigger; + /** + * On intersection exit + * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers + */ + ActionManager.OnIntersectionExitTrigger = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].ACTION_OnIntersectionExitTrigger; + /** + * On key down + * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers + */ + ActionManager.OnKeyDownTrigger = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].ACTION_OnKeyDownTrigger; + /** + * On key up + * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers + */ + ActionManager.OnKeyUpTrigger = 15; + return ActionManager; +}(_abstractActionManager__WEBPACK_IMPORTED_MODULE_9__["AbstractActionManager"])); + + + +/***/ }), + +/***/ "./Actions/condition.ts": +/*!******************************!*\ + !*** ./Actions/condition.ts ***! + \******************************/ +/*! exports provided: Condition, ValueCondition, PredicateCondition, StateCondition */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Condition", function() { return Condition; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ValueCondition", function() { return ValueCondition; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PredicateCondition", function() { return PredicateCondition; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StateCondition", function() { return StateCondition; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _action__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./action */ "./Actions/action.ts"); +/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/typeStore */ "./Misc/typeStore.ts"); + + + +/** + * A Condition applied to an Action + */ +var Condition = /** @class */ (function () { + /** + * Creates a new Condition + * @param actionManager the manager of the action the condition is applied to + */ + function Condition(actionManager) { + this._actionManager = actionManager; + } + /** + * Check if the current condition is valid + * @returns a boolean + */ + Condition.prototype.isValid = function () { + return true; + }; + /** + * Internal only + * @hidden + */ + Condition.prototype._getProperty = function (propertyPath) { + return this._actionManager._getProperty(propertyPath); + }; + /** + * Internal only + * @hidden + */ + Condition.prototype._getEffectiveTarget = function (target, propertyPath) { + return this._actionManager._getEffectiveTarget(target, propertyPath); + }; + /** + * Serialize placeholder for child classes + * @returns the serialized object + */ + Condition.prototype.serialize = function () { + }; + /** + * Internal only + * @hidden + */ + Condition.prototype._serialize = function (serializedCondition) { + return { + type: 2, + children: [], + name: serializedCondition.name, + properties: serializedCondition.properties + }; + }; + return Condition; +}()); + +/** + * Defines specific conditional operators as extensions of Condition + */ +var ValueCondition = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ValueCondition, _super); + /** + * Creates a new ValueCondition + * @param actionManager manager for the action the condition applies to + * @param target for the action + * @param propertyPath path to specify the property of the target the conditional operator uses + * @param value the value compared by the conditional operator against the current value of the property + * @param operator the conditional operator, default ValueCondition.IsEqual + */ + function ValueCondition(actionManager, target, + /** path to specify the property of the target the conditional operator uses */ + propertyPath, + /** the value compared by the conditional operator against the current value of the property */ + value, + /** the conditional operator, default ValueCondition.IsEqual */ + operator) { + if (operator === void 0) { operator = ValueCondition.IsEqual; } + var _this = _super.call(this, actionManager) || this; + _this.propertyPath = propertyPath; + _this.value = value; + _this.operator = operator; + _this._target = target; + _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath); + _this._property = _this._getProperty(_this.propertyPath); + return _this; + } + Object.defineProperty(ValueCondition, "IsEqual", { + /** + * returns the number for IsEqual + */ + get: function () { + return ValueCondition._IsEqual; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ValueCondition, "IsDifferent", { + /** + * Returns the number for IsDifferent + */ + get: function () { + return ValueCondition._IsDifferent; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ValueCondition, "IsGreater", { + /** + * Returns the number for IsGreater + */ + get: function () { + return ValueCondition._IsGreater; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ValueCondition, "IsLesser", { + /** + * Returns the number for IsLesser + */ + get: function () { + return ValueCondition._IsLesser; + }, + enumerable: true, + configurable: true + }); + /** + * Compares the given value with the property value for the specified conditional operator + * @returns the result of the comparison + */ + ValueCondition.prototype.isValid = function () { + switch (this.operator) { + case ValueCondition.IsGreater: + return this._effectiveTarget[this._property] > this.value; + case ValueCondition.IsLesser: + return this._effectiveTarget[this._property] < this.value; + case ValueCondition.IsEqual: + case ValueCondition.IsDifferent: + var check; + if (this.value.equals) { + check = this.value.equals(this._effectiveTarget[this._property]); + } + else { + check = this.value === this._effectiveTarget[this._property]; + } + return this.operator === ValueCondition.IsEqual ? check : !check; + } + return false; + }; + /** + * Serialize the ValueCondition into a JSON compatible object + * @returns serialization object + */ + ValueCondition.prototype.serialize = function () { + return this._serialize({ + name: "ValueCondition", + properties: [ + _action__WEBPACK_IMPORTED_MODULE_1__["Action"]._GetTargetProperty(this._target), + { name: "propertyPath", value: this.propertyPath }, + { name: "value", value: _action__WEBPACK_IMPORTED_MODULE_1__["Action"]._SerializeValueAsString(this.value) }, + { name: "operator", value: ValueCondition.GetOperatorName(this.operator) } + ] + }); + }; + /** + * Gets the name of the conditional operator for the ValueCondition + * @param operator the conditional operator + * @returns the name + */ + ValueCondition.GetOperatorName = function (operator) { + switch (operator) { + case ValueCondition._IsEqual: return "IsEqual"; + case ValueCondition._IsDifferent: return "IsDifferent"; + case ValueCondition._IsGreater: return "IsGreater"; + case ValueCondition._IsLesser: return "IsLesser"; + default: return ""; + } + }; + /** + * Internal only + * @hidden + */ + ValueCondition._IsEqual = 0; + /** + * Internal only + * @hidden + */ + ValueCondition._IsDifferent = 1; + /** + * Internal only + * @hidden + */ + ValueCondition._IsGreater = 2; + /** + * Internal only + * @hidden + */ + ValueCondition._IsLesser = 3; + return ValueCondition; +}(Condition)); + +/** + * Defines a predicate condition as an extension of Condition + */ +var PredicateCondition = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PredicateCondition, _super); + /** + * Creates a new PredicateCondition + * @param actionManager manager for the action the condition applies to + * @param predicate defines the predicate function used to validate the condition + */ + function PredicateCondition(actionManager, + /** defines the predicate function used to validate the condition */ + predicate) { + var _this = _super.call(this, actionManager) || this; + _this.predicate = predicate; + return _this; + } + /** + * @returns the validity of the predicate condition + */ + PredicateCondition.prototype.isValid = function () { + return this.predicate(); + }; + return PredicateCondition; +}(Condition)); + +/** + * Defines a state condition as an extension of Condition + */ +var StateCondition = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](StateCondition, _super); + /** + * Creates a new StateCondition + * @param actionManager manager for the action the condition applies to + * @param target of the condition + * @param value to compare with target state + */ + function StateCondition(actionManager, target, + /** Value to compare with target state */ + value) { + var _this = _super.call(this, actionManager) || this; + _this.value = value; + _this._target = target; + return _this; + } + /** + * Gets a boolean indicating if the current condition is met + * @returns the validity of the state + */ + StateCondition.prototype.isValid = function () { + return this._target.state === this.value; + }; + /** + * Serialize the StateCondition into a JSON compatible object + * @returns serialization object + */ + StateCondition.prototype.serialize = function () { + return this._serialize({ + name: "StateCondition", + properties: [ + _action__WEBPACK_IMPORTED_MODULE_1__["Action"]._GetTargetProperty(this._target), + { name: "value", value: this.value } + ] + }); + }; + return StateCondition; +}(Condition)); + +_Misc_typeStore__WEBPACK_IMPORTED_MODULE_2__["_TypeStore"].RegisteredTypes["BABYLON.ValueCondition"] = ValueCondition; +_Misc_typeStore__WEBPACK_IMPORTED_MODULE_2__["_TypeStore"].RegisteredTypes["BABYLON.PredicateCondition"] = PredicateCondition; +_Misc_typeStore__WEBPACK_IMPORTED_MODULE_2__["_TypeStore"].RegisteredTypes["BABYLON.StateCondition"] = StateCondition; + + +/***/ }), + +/***/ "./Actions/directActions.ts": +/*!**********************************!*\ + !*** ./Actions/directActions.ts ***! + \**********************************/ +/*! exports provided: SwitchBooleanAction, SetStateAction, SetValueAction, IncrementValueAction, PlayAnimationAction, StopAnimationAction, DoNothingAction, CombineAction, ExecuteCodeAction, SetParentAction */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SwitchBooleanAction", function() { return SwitchBooleanAction; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SetStateAction", function() { return SetStateAction; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SetValueAction", function() { return SetValueAction; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "IncrementValueAction", function() { return IncrementValueAction; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PlayAnimationAction", function() { return PlayAnimationAction; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StopAnimationAction", function() { return StopAnimationAction; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DoNothingAction", function() { return DoNothingAction; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CombineAction", function() { return CombineAction; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ExecuteCodeAction", function() { return ExecuteCodeAction; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SetParentAction", function() { return SetParentAction; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _action__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./action */ "./Actions/action.ts"); +/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts"); +/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Misc/typeStore */ "./Misc/typeStore.ts"); + + + + + + +/** + * This defines an action responsible to toggle a boolean once triggered. + * @see http://doc.babylonjs.com/how_to/how_to_use_actions + */ +var SwitchBooleanAction = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SwitchBooleanAction, _super); + /** + * Instantiate the action + * @param triggerOptions defines the trigger options + * @param target defines the object containing the boolean + * @param propertyPath defines the path to the boolean property in the target object + * @param condition defines the trigger related conditions + */ + function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) { + var _this = _super.call(this, triggerOptions, condition) || this; + _this.propertyPath = propertyPath; + _this._target = _this._effectiveTarget = target; + return _this; + } + /** @hidden */ + SwitchBooleanAction.prototype._prepare = function () { + this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath); + this._property = this._getProperty(this.propertyPath); + }; + /** + * Execute the action toggle the boolean value. + */ + SwitchBooleanAction.prototype.execute = function () { + this._effectiveTarget[this._property] = !this._effectiveTarget[this._property]; + }; + /** + * Serializes the actions and its related information. + * @param parent defines the object to serialize in + * @returns the serialized object + */ + SwitchBooleanAction.prototype.serialize = function (parent) { + return _super.prototype._serialize.call(this, { + name: "SwitchBooleanAction", + properties: [ + _action__WEBPACK_IMPORTED_MODULE_3__["Action"]._GetTargetProperty(this._target), + { name: "propertyPath", value: this.propertyPath } + ] + }, parent); + }; + return SwitchBooleanAction; +}(_action__WEBPACK_IMPORTED_MODULE_3__["Action"])); + +/** + * This defines an action responsible to set a the state field of the target + * to a desired value once triggered. + * @see http://doc.babylonjs.com/how_to/how_to_use_actions + */ +var SetStateAction = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SetStateAction, _super); + /** + * Instantiate the action + * @param triggerOptions defines the trigger options + * @param target defines the object containing the state property + * @param value defines the value to store in the state field + * @param condition defines the trigger related conditions + */ + function SetStateAction(triggerOptions, target, value, condition) { + var _this = _super.call(this, triggerOptions, condition) || this; + _this.value = value; + _this._target = target; + return _this; + } + /** + * Execute the action and store the value on the target state property. + */ + SetStateAction.prototype.execute = function () { + this._target.state = this.value; + }; + /** + * Serializes the actions and its related information. + * @param parent defines the object to serialize in + * @returns the serialized object + */ + SetStateAction.prototype.serialize = function (parent) { + return _super.prototype._serialize.call(this, { + name: "SetStateAction", + properties: [ + _action__WEBPACK_IMPORTED_MODULE_3__["Action"]._GetTargetProperty(this._target), + { name: "value", value: this.value } + ] + }, parent); + }; + return SetStateAction; +}(_action__WEBPACK_IMPORTED_MODULE_3__["Action"])); + +/** + * This defines an action responsible to set a property of the target + * to a desired value once triggered. + * @see http://doc.babylonjs.com/how_to/how_to_use_actions + */ +var SetValueAction = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SetValueAction, _super); + /** + * Instantiate the action + * @param triggerOptions defines the trigger options + * @param target defines the object containing the property + * @param propertyPath defines the path of the property to set in the target + * @param value defines the value to set in the property + * @param condition defines the trigger related conditions + */ + function SetValueAction(triggerOptions, target, propertyPath, value, condition) { + var _this = _super.call(this, triggerOptions, condition) || this; + _this.propertyPath = propertyPath; + _this.value = value; + _this._target = _this._effectiveTarget = target; + return _this; + } + /** @hidden */ + SetValueAction.prototype._prepare = function () { + this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath); + this._property = this._getProperty(this.propertyPath); + }; + /** + * Execute the action and set the targetted property to the desired value. + */ + SetValueAction.prototype.execute = function () { + this._effectiveTarget[this._property] = this.value; + if (this._target.markAsDirty) { + this._target.markAsDirty(this._property); + } + }; + /** + * Serializes the actions and its related information. + * @param parent defines the object to serialize in + * @returns the serialized object + */ + SetValueAction.prototype.serialize = function (parent) { + return _super.prototype._serialize.call(this, { + name: "SetValueAction", + properties: [ + _action__WEBPACK_IMPORTED_MODULE_3__["Action"]._GetTargetProperty(this._target), + { name: "propertyPath", value: this.propertyPath }, + { name: "value", value: _action__WEBPACK_IMPORTED_MODULE_3__["Action"]._SerializeValueAsString(this.value) } + ] + }, parent); + }; + return SetValueAction; +}(_action__WEBPACK_IMPORTED_MODULE_3__["Action"])); + +/** + * This defines an action responsible to increment the target value + * to a desired value once triggered. + * @see http://doc.babylonjs.com/how_to/how_to_use_actions + */ +var IncrementValueAction = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](IncrementValueAction, _super); + /** + * Instantiate the action + * @param triggerOptions defines the trigger options + * @param target defines the object containing the property + * @param propertyPath defines the path of the property to increment in the target + * @param value defines the value value we should increment the property by + * @param condition defines the trigger related conditions + */ + function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) { + var _this = _super.call(this, triggerOptions, condition) || this; + _this.propertyPath = propertyPath; + _this.value = value; + _this._target = _this._effectiveTarget = target; + return _this; + } + /** @hidden */ + IncrementValueAction.prototype._prepare = function () { + this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath); + this._property = this._getProperty(this.propertyPath); + if (typeof this._effectiveTarget[this._property] !== "number") { + _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn("Warning: IncrementValueAction can only be used with number values"); + } + }; + /** + * Execute the action and increment the target of the value amount. + */ + IncrementValueAction.prototype.execute = function () { + this._effectiveTarget[this._property] += this.value; + if (this._target.markAsDirty) { + this._target.markAsDirty(this._property); + } + }; + /** + * Serializes the actions and its related information. + * @param parent defines the object to serialize in + * @returns the serialized object + */ + IncrementValueAction.prototype.serialize = function (parent) { + return _super.prototype._serialize.call(this, { + name: "IncrementValueAction", + properties: [ + _action__WEBPACK_IMPORTED_MODULE_3__["Action"]._GetTargetProperty(this._target), + { name: "propertyPath", value: this.propertyPath }, + { name: "value", value: _action__WEBPACK_IMPORTED_MODULE_3__["Action"]._SerializeValueAsString(this.value) } + ] + }, parent); + }; + return IncrementValueAction; +}(_action__WEBPACK_IMPORTED_MODULE_3__["Action"])); + +/** + * This defines an action responsible to start an animation once triggered. + * @see http://doc.babylonjs.com/how_to/how_to_use_actions + */ +var PlayAnimationAction = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PlayAnimationAction, _super); + /** + * Instantiate the action + * @param triggerOptions defines the trigger options + * @param target defines the target animation or animation name + * @param from defines from where the animation should start (animation frame) + * @param end defines where the animation should stop (animation frame) + * @param loop defines if the animation should loop or stop after the first play + * @param condition defines the trigger related conditions + */ + function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) { + var _this = _super.call(this, triggerOptions, condition) || this; + _this.from = from; + _this.to = to; + _this.loop = loop; + _this._target = target; + return _this; + } + /** @hidden */ + PlayAnimationAction.prototype._prepare = function () { + }; + /** + * Execute the action and play the animation. + */ + PlayAnimationAction.prototype.execute = function () { + var scene = this._actionManager.getScene(); + scene.beginAnimation(this._target, this.from, this.to, this.loop); + }; + /** + * Serializes the actions and its related information. + * @param parent defines the object to serialize in + * @returns the serialized object + */ + PlayAnimationAction.prototype.serialize = function (parent) { + return _super.prototype._serialize.call(this, { + name: "PlayAnimationAction", + properties: [ + _action__WEBPACK_IMPORTED_MODULE_3__["Action"]._GetTargetProperty(this._target), + { name: "from", value: String(this.from) }, + { name: "to", value: String(this.to) }, + { name: "loop", value: _action__WEBPACK_IMPORTED_MODULE_3__["Action"]._SerializeValueAsString(this.loop) || false } + ] + }, parent); + }; + return PlayAnimationAction; +}(_action__WEBPACK_IMPORTED_MODULE_3__["Action"])); + +/** + * This defines an action responsible to stop an animation once triggered. + * @see http://doc.babylonjs.com/how_to/how_to_use_actions + */ +var StopAnimationAction = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](StopAnimationAction, _super); + /** + * Instantiate the action + * @param triggerOptions defines the trigger options + * @param target defines the target animation or animation name + * @param condition defines the trigger related conditions + */ + function StopAnimationAction(triggerOptions, target, condition) { + var _this = _super.call(this, triggerOptions, condition) || this; + _this._target = target; + return _this; + } + /** @hidden */ + StopAnimationAction.prototype._prepare = function () { + }; + /** + * Execute the action and stop the animation. + */ + StopAnimationAction.prototype.execute = function () { + var scene = this._actionManager.getScene(); + scene.stopAnimation(this._target); + }; + /** + * Serializes the actions and its related information. + * @param parent defines the object to serialize in + * @returns the serialized object + */ + StopAnimationAction.prototype.serialize = function (parent) { + return _super.prototype._serialize.call(this, { + name: "StopAnimationAction", + properties: [_action__WEBPACK_IMPORTED_MODULE_3__["Action"]._GetTargetProperty(this._target)] + }, parent); + }; + return StopAnimationAction; +}(_action__WEBPACK_IMPORTED_MODULE_3__["Action"])); + +/** + * This defines an action responsible that does nothing once triggered. + * @see http://doc.babylonjs.com/how_to/how_to_use_actions + */ +var DoNothingAction = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](DoNothingAction, _super); + /** + * Instantiate the action + * @param triggerOptions defines the trigger options + * @param condition defines the trigger related conditions + */ + function DoNothingAction(triggerOptions, condition) { + if (triggerOptions === void 0) { triggerOptions = _Engines_constants__WEBPACK_IMPORTED_MODULE_4__["Constants"].ACTION_NothingTrigger; } + return _super.call(this, triggerOptions, condition) || this; + } + /** + * Execute the action and do nothing. + */ + DoNothingAction.prototype.execute = function () { + }; + /** + * Serializes the actions and its related information. + * @param parent defines the object to serialize in + * @returns the serialized object + */ + DoNothingAction.prototype.serialize = function (parent) { + return _super.prototype._serialize.call(this, { + name: "DoNothingAction", + properties: [] + }, parent); + }; + return DoNothingAction; +}(_action__WEBPACK_IMPORTED_MODULE_3__["Action"])); + +/** + * This defines an action responsible to trigger several actions once triggered. + * @see http://doc.babylonjs.com/how_to/how_to_use_actions + */ +var CombineAction = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](CombineAction, _super); + /** + * Instantiate the action + * @param triggerOptions defines the trigger options + * @param children defines the list of aggregated animations to run + * @param condition defines the trigger related conditions + */ + function CombineAction(triggerOptions, children, condition) { + var _this = _super.call(this, triggerOptions, condition) || this; + _this.children = children; + return _this; + } + /** @hidden */ + CombineAction.prototype._prepare = function () { + for (var index = 0; index < this.children.length; index++) { + this.children[index]._actionManager = this._actionManager; + this.children[index]._prepare(); + } + }; + /** + * Execute the action and executes all the aggregated actions. + */ + CombineAction.prototype.execute = function (evt) { + for (var index = 0; index < this.children.length; index++) { + this.children[index].execute(evt); + } + }; + /** + * Serializes the actions and its related information. + * @param parent defines the object to serialize in + * @returns the serialized object + */ + CombineAction.prototype.serialize = function (parent) { + var serializationObject = _super.prototype._serialize.call(this, { + name: "CombineAction", + properties: [], + combine: [] + }, parent); + for (var i = 0; i < this.children.length; i++) { + serializationObject.combine.push(this.children[i].serialize(null)); + } + return serializationObject; + }; + return CombineAction; +}(_action__WEBPACK_IMPORTED_MODULE_3__["Action"])); + +/** + * This defines an action responsible to run code (external event) once triggered. + * @see http://doc.babylonjs.com/how_to/how_to_use_actions + */ +var ExecuteCodeAction = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ExecuteCodeAction, _super); + /** + * Instantiate the action + * @param triggerOptions defines the trigger options + * @param func defines the callback function to run + * @param condition defines the trigger related conditions + */ + function ExecuteCodeAction(triggerOptions, func, condition) { + var _this = _super.call(this, triggerOptions, condition) || this; + _this.func = func; + return _this; + } + /** + * Execute the action and run the attached code. + */ + ExecuteCodeAction.prototype.execute = function (evt) { + this.func(evt); + }; + return ExecuteCodeAction; +}(_action__WEBPACK_IMPORTED_MODULE_3__["Action"])); + +/** + * This defines an action responsible to set the parent property of the target once triggered. + * @see http://doc.babylonjs.com/how_to/how_to_use_actions + */ +var SetParentAction = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SetParentAction, _super); + /** + * Instantiate the action + * @param triggerOptions defines the trigger options + * @param target defines the target containing the parent property + * @param parent defines from where the animation should start (animation frame) + * @param condition defines the trigger related conditions + */ + function SetParentAction(triggerOptions, target, parent, condition) { + var _this = _super.call(this, triggerOptions, condition) || this; + _this._target = target; + _this._parent = parent; + return _this; + } + /** @hidden */ + SetParentAction.prototype._prepare = function () { + }; + /** + * Execute the action and set the parent property. + */ + SetParentAction.prototype.execute = function () { + if (this._target.parent === this._parent) { + return; + } + var invertParentWorldMatrix = this._parent.getWorldMatrix().clone(); + invertParentWorldMatrix.invert(); + this._target.position = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].TransformCoordinates(this._target.position, invertParentWorldMatrix); + this._target.parent = this._parent; + }; + /** + * Serializes the actions and its related information. + * @param parent defines the object to serialize in + * @returns the serialized object + */ + SetParentAction.prototype.serialize = function (parent) { + return _super.prototype._serialize.call(this, { + name: "SetParentAction", + properties: [ + _action__WEBPACK_IMPORTED_MODULE_3__["Action"]._GetTargetProperty(this._target), + _action__WEBPACK_IMPORTED_MODULE_3__["Action"]._GetTargetProperty(this._parent), + ] + }, parent); + }; + return SetParentAction; +}(_action__WEBPACK_IMPORTED_MODULE_3__["Action"])); + +_Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__["_TypeStore"].RegisteredTypes["BABYLON.SetParentAction"] = SetParentAction; +_Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__["_TypeStore"].RegisteredTypes["BABYLON.ExecuteCodeAction"] = ExecuteCodeAction; +_Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__["_TypeStore"].RegisteredTypes["BABYLON.DoNothingAction"] = DoNothingAction; +_Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__["_TypeStore"].RegisteredTypes["BABYLON.StopAnimationAction"] = StopAnimationAction; +_Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__["_TypeStore"].RegisteredTypes["BABYLON.PlayAnimationAction"] = PlayAnimationAction; +_Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__["_TypeStore"].RegisteredTypes["BABYLON.IncrementValueAction"] = IncrementValueAction; +_Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__["_TypeStore"].RegisteredTypes["BABYLON.SetValueAction"] = SetValueAction; +_Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__["_TypeStore"].RegisteredTypes["BABYLON.SetStateAction"] = SetStateAction; +_Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__["_TypeStore"].RegisteredTypes["BABYLON.SetParentAction"] = SetParentAction; + + +/***/ }), + +/***/ "./Actions/directAudioActions.ts": +/*!***************************************!*\ + !*** ./Actions/directAudioActions.ts ***! + \***************************************/ +/*! exports provided: PlaySoundAction, StopSoundAction */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PlaySoundAction", function() { return PlaySoundAction; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StopSoundAction", function() { return StopSoundAction; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _action__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./action */ "./Actions/action.ts"); +/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/typeStore */ "./Misc/typeStore.ts"); + + + +/** + * This defines an action helpful to play a defined sound on a triggered action. + */ +var PlaySoundAction = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PlaySoundAction, _super); + /** + * Instantiate the action + * @param triggerOptions defines the trigger options + * @param sound defines the sound to play + * @param condition defines the trigger related conditions + */ + function PlaySoundAction(triggerOptions, sound, condition) { + var _this = _super.call(this, triggerOptions, condition) || this; + _this._sound = sound; + return _this; + } + /** @hidden */ + PlaySoundAction.prototype._prepare = function () { + }; + /** + * Execute the action and play the sound. + */ + PlaySoundAction.prototype.execute = function () { + if (this._sound !== undefined) { + this._sound.play(); + } + }; + /** + * Serializes the actions and its related information. + * @param parent defines the object to serialize in + * @returns the serialized object + */ + PlaySoundAction.prototype.serialize = function (parent) { + return _super.prototype._serialize.call(this, { + name: "PlaySoundAction", + properties: [{ name: "sound", value: this._sound.name }] + }, parent); + }; + return PlaySoundAction; +}(_action__WEBPACK_IMPORTED_MODULE_1__["Action"])); + +/** + * This defines an action helpful to stop a defined sound on a triggered action. + */ +var StopSoundAction = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](StopSoundAction, _super); + /** + * Instantiate the action + * @param triggerOptions defines the trigger options + * @param sound defines the sound to stop + * @param condition defines the trigger related conditions + */ + function StopSoundAction(triggerOptions, sound, condition) { + var _this = _super.call(this, triggerOptions, condition) || this; + _this._sound = sound; + return _this; + } + /** @hidden */ + StopSoundAction.prototype._prepare = function () { + }; + /** + * Execute the action and stop the sound. + */ + StopSoundAction.prototype.execute = function () { + if (this._sound !== undefined) { + this._sound.stop(); + } + }; + /** + * Serializes the actions and its related information. + * @param parent defines the object to serialize in + * @returns the serialized object + */ + StopSoundAction.prototype.serialize = function (parent) { + return _super.prototype._serialize.call(this, { + name: "StopSoundAction", + properties: [{ name: "sound", value: this._sound.name }] + }, parent); + }; + return StopSoundAction; +}(_action__WEBPACK_IMPORTED_MODULE_1__["Action"])); + +_Misc_typeStore__WEBPACK_IMPORTED_MODULE_2__["_TypeStore"].RegisteredTypes["BABYLON.PlaySoundAction"] = StopSoundAction; +_Misc_typeStore__WEBPACK_IMPORTED_MODULE_2__["_TypeStore"].RegisteredTypes["BABYLON.StopSoundAction"] = StopSoundAction; + + +/***/ }), + +/***/ "./Actions/index.ts": +/*!**************************!*\ + !*** ./Actions/index.ts ***! + \**************************/ +/*! exports provided: Action, ActionEvent, ActionManager, Condition, ValueCondition, PredicateCondition, StateCondition, SwitchBooleanAction, SetStateAction, SetValueAction, IncrementValueAction, PlayAnimationAction, StopAnimationAction, DoNothingAction, CombineAction, ExecuteCodeAction, SetParentAction, PlaySoundAction, StopSoundAction, InterpolateValueAction */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _action__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./action */ "./Actions/action.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Action", function() { return _action__WEBPACK_IMPORTED_MODULE_0__["Action"]; }); + +/* harmony import */ var _actionEvent__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./actionEvent */ "./Actions/actionEvent.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ActionEvent", function() { return _actionEvent__WEBPACK_IMPORTED_MODULE_1__["ActionEvent"]; }); + +/* harmony import */ var _actionManager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./actionManager */ "./Actions/actionManager.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ActionManager", function() { return _actionManager__WEBPACK_IMPORTED_MODULE_2__["ActionManager"]; }); + +/* harmony import */ var _condition__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./condition */ "./Actions/condition.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Condition", function() { return _condition__WEBPACK_IMPORTED_MODULE_3__["Condition"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ValueCondition", function() { return _condition__WEBPACK_IMPORTED_MODULE_3__["ValueCondition"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PredicateCondition", function() { return _condition__WEBPACK_IMPORTED_MODULE_3__["PredicateCondition"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StateCondition", function() { return _condition__WEBPACK_IMPORTED_MODULE_3__["StateCondition"]; }); + +/* harmony import */ var _directActions__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./directActions */ "./Actions/directActions.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SwitchBooleanAction", function() { return _directActions__WEBPACK_IMPORTED_MODULE_4__["SwitchBooleanAction"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SetStateAction", function() { return _directActions__WEBPACK_IMPORTED_MODULE_4__["SetStateAction"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SetValueAction", function() { return _directActions__WEBPACK_IMPORTED_MODULE_4__["SetValueAction"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "IncrementValueAction", function() { return _directActions__WEBPACK_IMPORTED_MODULE_4__["IncrementValueAction"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PlayAnimationAction", function() { return _directActions__WEBPACK_IMPORTED_MODULE_4__["PlayAnimationAction"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StopAnimationAction", function() { return _directActions__WEBPACK_IMPORTED_MODULE_4__["StopAnimationAction"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DoNothingAction", function() { return _directActions__WEBPACK_IMPORTED_MODULE_4__["DoNothingAction"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CombineAction", function() { return _directActions__WEBPACK_IMPORTED_MODULE_4__["CombineAction"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ExecuteCodeAction", function() { return _directActions__WEBPACK_IMPORTED_MODULE_4__["ExecuteCodeAction"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SetParentAction", function() { return _directActions__WEBPACK_IMPORTED_MODULE_4__["SetParentAction"]; }); + +/* harmony import */ var _directAudioActions__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./directAudioActions */ "./Actions/directAudioActions.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PlaySoundAction", function() { return _directAudioActions__WEBPACK_IMPORTED_MODULE_5__["PlaySoundAction"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StopSoundAction", function() { return _directAudioActions__WEBPACK_IMPORTED_MODULE_5__["StopSoundAction"]; }); + +/* harmony import */ var _interpolateValueAction__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./interpolateValueAction */ "./Actions/interpolateValueAction.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InterpolateValueAction", function() { return _interpolateValueAction__WEBPACK_IMPORTED_MODULE_6__["InterpolateValueAction"]; }); + + + + + + + + + + +/***/ }), + +/***/ "./Actions/interpolateValueAction.ts": +/*!*******************************************!*\ + !*** ./Actions/interpolateValueAction.ts ***! + \*******************************************/ +/*! exports provided: InterpolateValueAction */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InterpolateValueAction", function() { return InterpolateValueAction; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _action__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./action */ "./Actions/action.ts"); +/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts"); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Animations_animation__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Animations/animation */ "./Animations/animation.ts"); +/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Misc/typeStore */ "./Misc/typeStore.ts"); + + + + + + + +/** + * This defines an action responsible to change the value of a property + * by interpolating between its current value and the newly set one once triggered. + * @see http://doc.babylonjs.com/how_to/how_to_use_actions + */ +var InterpolateValueAction = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](InterpolateValueAction, _super); + /** + * Instantiate the action + * @param triggerOptions defines the trigger options + * @param target defines the object containing the value to interpolate + * @param propertyPath defines the path to the property in the target object + * @param value defines the target value at the end of the interpolation + * @param duration deines the time it will take for the property to interpolate to the value. + * @param condition defines the trigger related conditions + * @param stopOtherAnimations defines if the other scene animations should be stopped when the action has been triggered + * @param onInterpolationDone defines a callback raised once the interpolation animation has been done + */ + function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) { + if (duration === void 0) { duration = 1000; } + var _this = _super.call(this, triggerOptions, condition) || this; + /** + * Defines the time it will take for the property to interpolate to the value. + */ + _this.duration = 1000; + /** + * Observable triggered once the interpolation animation has been done. + */ + _this.onInterpolationDoneObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_3__["Observable"](); + _this.propertyPath = propertyPath; + _this.value = value; + _this.duration = duration; + _this.stopOtherAnimations = stopOtherAnimations; + _this.onInterpolationDone = onInterpolationDone; + _this._target = _this._effectiveTarget = target; + return _this; + } + /** @hidden */ + InterpolateValueAction.prototype._prepare = function () { + this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath); + this._property = this._getProperty(this.propertyPath); + }; + /** + * Execute the action starts the value interpolation. + */ + InterpolateValueAction.prototype.execute = function () { + var _this = this; + var scene = this._actionManager.getScene(); + var keys = [ + { + frame: 0, + value: this._effectiveTarget[this._property] + }, { + frame: 100, + value: this.value + } + ]; + var dataType; + if (typeof this.value === "number") { + dataType = _Animations_animation__WEBPACK_IMPORTED_MODULE_5__["Animation"].ANIMATIONTYPE_FLOAT; + } + else if (this.value instanceof _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Color3"]) { + dataType = _Animations_animation__WEBPACK_IMPORTED_MODULE_5__["Animation"].ANIMATIONTYPE_COLOR3; + } + else if (this.value instanceof _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"]) { + dataType = _Animations_animation__WEBPACK_IMPORTED_MODULE_5__["Animation"].ANIMATIONTYPE_VECTOR3; + } + else if (this.value instanceof _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"]) { + dataType = _Animations_animation__WEBPACK_IMPORTED_MODULE_5__["Animation"].ANIMATIONTYPE_MATRIX; + } + else if (this.value instanceof _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Quaternion"]) { + dataType = _Animations_animation__WEBPACK_IMPORTED_MODULE_5__["Animation"].ANIMATIONTYPE_QUATERNION; + } + else { + _Misc_logger__WEBPACK_IMPORTED_MODULE_2__["Logger"].Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")"); + return; + } + var animation = new _Animations_animation__WEBPACK_IMPORTED_MODULE_5__["Animation"]("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, _Animations_animation__WEBPACK_IMPORTED_MODULE_5__["Animation"].ANIMATIONLOOPMODE_CONSTANT); + animation.setKeys(keys); + if (this.stopOtherAnimations) { + scene.stopAnimation(this._effectiveTarget); + } + var wrapper = function () { + _this.onInterpolationDoneObservable.notifyObservers(_this); + if (_this.onInterpolationDone) { + _this.onInterpolationDone(); + } + }; + scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper); + }; + /** + * Serializes the actions and its related information. + * @param parent defines the object to serialize in + * @returns the serialized object + */ + InterpolateValueAction.prototype.serialize = function (parent) { + return _super.prototype._serialize.call(this, { + name: "InterpolateValueAction", + properties: [ + _action__WEBPACK_IMPORTED_MODULE_1__["Action"]._GetTargetProperty(this._target), + { name: "propertyPath", value: this.propertyPath }, + { name: "value", value: _action__WEBPACK_IMPORTED_MODULE_1__["Action"]._SerializeValueAsString(this.value) }, + { name: "duration", value: _action__WEBPACK_IMPORTED_MODULE_1__["Action"]._SerializeValueAsString(this.duration) }, + { name: "stopOtherAnimations", value: _action__WEBPACK_IMPORTED_MODULE_1__["Action"]._SerializeValueAsString(this.stopOtherAnimations) || false } + ] + }, parent); + }; + return InterpolateValueAction; +}(_action__WEBPACK_IMPORTED_MODULE_1__["Action"])); + +_Misc_typeStore__WEBPACK_IMPORTED_MODULE_6__["_TypeStore"].RegisteredTypes["BABYLON.InterpolateValueAction"] = InterpolateValueAction; + + +/***/ }), + +/***/ "./Animations/animatable.ts": +/*!**********************************!*\ + !*** ./Animations/animatable.ts ***! + \**********************************/ +/*! exports provided: Animatable */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Animatable", function() { return Animatable; }); +/* harmony import */ var _animation__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./animation */ "./Animations/animation.ts"); +/* harmony import */ var _runtimeAnimation__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./runtimeAnimation */ "./Animations/runtimeAnimation.ts"); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _scene__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../scene */ "./scene.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Misc_precisionDate__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Misc/precisionDate */ "./Misc/precisionDate.ts"); +/* harmony import */ var _Bones_bone__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Bones/bone */ "./Bones/bone.ts"); + + + + + + + +/** + * Class used to store an actual running animation + */ +var Animatable = /** @class */ (function () { + /** + * Creates a new Animatable + * @param scene defines the hosting scene + * @param target defines the target object + * @param fromFrame defines the starting frame number (default is 0) + * @param toFrame defines the ending frame number (default is 100) + * @param loopAnimation defines if the animation must loop (default is false) + * @param speedRatio defines the factor to apply to animation speed (default is 1) + * @param onAnimationEnd defines a callback to call when animation ends if it is not looping + * @param animations defines a group of animation to add to the new Animatable + * @param onAnimationLoop defines a callback to call when animation loops + */ + function Animatable(scene, + /** defines the target object */ + target, + /** defines the starting frame number (default is 0) */ + fromFrame, + /** defines the ending frame number (default is 100) */ + toFrame, + /** defines if the animation must loop (default is false) */ + loopAnimation, speedRatio, + /** defines a callback to call when animation ends if it is not looping */ + onAnimationEnd, animations, + /** defines a callback to call when animation loops */ + onAnimationLoop) { + if (fromFrame === void 0) { fromFrame = 0; } + if (toFrame === void 0) { toFrame = 100; } + if (loopAnimation === void 0) { loopAnimation = false; } + if (speedRatio === void 0) { speedRatio = 1.0; } + this.target = target; + this.fromFrame = fromFrame; + this.toFrame = toFrame; + this.loopAnimation = loopAnimation; + this.onAnimationEnd = onAnimationEnd; + this.onAnimationLoop = onAnimationLoop; + this._localDelayOffset = null; + this._pausedDelay = null; + this._runtimeAnimations = new Array(); + this._paused = false; + this._speedRatio = 1; + this._weight = -1.0; + this._syncRoot = null; + /** + * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation. + * This will only apply for non looping animation (default is true) + */ + this.disposeOnEnd = true; + /** + * Gets a boolean indicating if the animation has started + */ + this.animationStarted = false; + /** + * Observer raised when the animation ends + */ + this.onAnimationEndObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); + /** + * Observer raised when the animation loops + */ + this.onAnimationLoopObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); + this._scene = scene; + if (animations) { + this.appendAnimations(target, animations); + } + this._speedRatio = speedRatio; + scene._activeAnimatables.push(this); + } + Object.defineProperty(Animatable.prototype, "syncRoot", { + /** + * Gets the root Animatable used to synchronize and normalize animations + */ + get: function () { + return this._syncRoot; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Animatable.prototype, "masterFrame", { + /** + * Gets the current frame of the first RuntimeAnimation + * Used to synchronize Animatables + */ + get: function () { + if (this._runtimeAnimations.length === 0) { + return 0; + } + return this._runtimeAnimations[0].currentFrame; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Animatable.prototype, "weight", { + /** + * Gets or sets the animatable weight (-1.0 by default meaning not weighted) + */ + get: function () { + return this._weight; + }, + set: function (value) { + if (value === -1) { // -1 is ok and means no weight + this._weight = -1; + return; + } + // Else weight must be in [0, 1] range + this._weight = Math.min(Math.max(value, 0), 1.0); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Animatable.prototype, "speedRatio", { + /** + * Gets or sets the speed ratio to apply to the animatable (1.0 by default) + */ + get: function () { + return this._speedRatio; + }, + set: function (value) { + for (var index = 0; index < this._runtimeAnimations.length; index++) { + var animation = this._runtimeAnimations[index]; + animation._prepareForSpeedRatioChange(value); + } + this._speedRatio = value; + }, + enumerable: true, + configurable: true + }); + // Methods + /** + * Synchronize and normalize current Animatable with a source Animatable + * This is useful when using animation weights and when animations are not of the same length + * @param root defines the root Animatable to synchronize with + * @returns the current Animatable + */ + Animatable.prototype.syncWith = function (root) { + this._syncRoot = root; + if (root) { + // Make sure this animatable will animate after the root + var index = this._scene._activeAnimatables.indexOf(this); + if (index > -1) { + this._scene._activeAnimatables.splice(index, 1); + this._scene._activeAnimatables.push(this); + } + } + return this; + }; + /** + * Gets the list of runtime animations + * @returns an array of RuntimeAnimation + */ + Animatable.prototype.getAnimations = function () { + return this._runtimeAnimations; + }; + /** + * Adds more animations to the current animatable + * @param target defines the target of the animations + * @param animations defines the new animations to add + */ + Animatable.prototype.appendAnimations = function (target, animations) { + var _this = this; + for (var index = 0; index < animations.length; index++) { + var animation = animations[index]; + var newRuntimeAnimation = new _runtimeAnimation__WEBPACK_IMPORTED_MODULE_1__["RuntimeAnimation"](target, animation, this._scene, this); + newRuntimeAnimation._onLoop = function () { + _this.onAnimationLoopObservable.notifyObservers(_this); + if (_this.onAnimationLoop) { + _this.onAnimationLoop(); + } + }; + this._runtimeAnimations.push(newRuntimeAnimation); + } + }; + /** + * Gets the source animation for a specific property + * @param property defines the propertyu to look for + * @returns null or the source animation for the given property + */ + Animatable.prototype.getAnimationByTargetProperty = function (property) { + var runtimeAnimations = this._runtimeAnimations; + for (var index = 0; index < runtimeAnimations.length; index++) { + if (runtimeAnimations[index].animation.targetProperty === property) { + return runtimeAnimations[index].animation; + } + } + return null; + }; + /** + * Gets the runtime animation for a specific property + * @param property defines the propertyu to look for + * @returns null or the runtime animation for the given property + */ + Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) { + var runtimeAnimations = this._runtimeAnimations; + for (var index = 0; index < runtimeAnimations.length; index++) { + if (runtimeAnimations[index].animation.targetProperty === property) { + return runtimeAnimations[index]; + } + } + return null; + }; + /** + * Resets the animatable to its original state + */ + Animatable.prototype.reset = function () { + var runtimeAnimations = this._runtimeAnimations; + for (var index = 0; index < runtimeAnimations.length; index++) { + runtimeAnimations[index].reset(true); + } + this._localDelayOffset = null; + this._pausedDelay = null; + }; + /** + * Allows the animatable to blend with current running animations + * @see http://doc.babylonjs.com/babylon101/animations#animation-blending + * @param blendingSpeed defines the blending speed to use + */ + Animatable.prototype.enableBlending = function (blendingSpeed) { + var runtimeAnimations = this._runtimeAnimations; + for (var index = 0; index < runtimeAnimations.length; index++) { + runtimeAnimations[index].animation.enableBlending = true; + runtimeAnimations[index].animation.blendingSpeed = blendingSpeed; + } + }; + /** + * Disable animation blending + * @see http://doc.babylonjs.com/babylon101/animations#animation-blending + */ + Animatable.prototype.disableBlending = function () { + var runtimeAnimations = this._runtimeAnimations; + for (var index = 0; index < runtimeAnimations.length; index++) { + runtimeAnimations[index].animation.enableBlending = false; + } + }; + /** + * Jump directly to a given frame + * @param frame defines the frame to jump to + */ + Animatable.prototype.goToFrame = function (frame) { + var runtimeAnimations = this._runtimeAnimations; + if (runtimeAnimations[0]) { + var fps = runtimeAnimations[0].animation.framePerSecond; + var currentFrame = runtimeAnimations[0].currentFrame; + var adjustTime = frame - currentFrame; + var delay = this.speedRatio !== 0 ? adjustTime * 1000 / (fps * this.speedRatio) : 0; + if (this._localDelayOffset === null) { + this._localDelayOffset = 0; + } + this._localDelayOffset -= delay; + } + for (var index = 0; index < runtimeAnimations.length; index++) { + runtimeAnimations[index].goToFrame(frame); + } + }; + /** + * Pause the animation + */ + Animatable.prototype.pause = function () { + if (this._paused) { + return; + } + this._paused = true; + }; + /** + * Restart the animation + */ + Animatable.prototype.restart = function () { + this._paused = false; + }; + Animatable.prototype._raiseOnAnimationEnd = function () { + if (this.onAnimationEnd) { + this.onAnimationEnd(); + } + this.onAnimationEndObservable.notifyObservers(this); + }; + /** + * Stop and delete the current animation + * @param animationName defines a string used to only stop some of the runtime animations instead of all + * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty) + */ + Animatable.prototype.stop = function (animationName, targetMask) { + if (animationName || targetMask) { + var idx = this._scene._activeAnimatables.indexOf(this); + if (idx > -1) { + var runtimeAnimations = this._runtimeAnimations; + for (var index = runtimeAnimations.length - 1; index >= 0; index--) { + var runtimeAnimation = runtimeAnimations[index]; + if (animationName && runtimeAnimation.animation.name != animationName) { + continue; + } + if (targetMask && !targetMask(runtimeAnimation.target)) { + continue; + } + runtimeAnimation.dispose(); + runtimeAnimations.splice(index, 1); + } + if (runtimeAnimations.length == 0) { + this._scene._activeAnimatables.splice(idx, 1); + this._raiseOnAnimationEnd(); + } + } + } + else { + var index = this._scene._activeAnimatables.indexOf(this); + if (index > -1) { + this._scene._activeAnimatables.splice(index, 1); + var runtimeAnimations = this._runtimeAnimations; + for (var index = 0; index < runtimeAnimations.length; index++) { + runtimeAnimations[index].dispose(); + } + this._raiseOnAnimationEnd(); + } + } + }; + /** + * Wait asynchronously for the animation to end + * @returns a promise which will be fullfilled when the animation ends + */ + Animatable.prototype.waitAsync = function () { + var _this = this; + return new Promise(function (resolve, reject) { + _this.onAnimationEndObservable.add(function () { + resolve(_this); + }, undefined, undefined, _this, true); + }); + }; + /** @hidden */ + Animatable.prototype._animate = function (delay) { + if (this._paused) { + this.animationStarted = false; + if (this._pausedDelay === null) { + this._pausedDelay = delay; + } + return true; + } + if (this._localDelayOffset === null) { + this._localDelayOffset = delay; + this._pausedDelay = null; + } + else if (this._pausedDelay !== null) { + this._localDelayOffset += delay - this._pausedDelay; + this._pausedDelay = null; + } + if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused + return true; + } + // Animating + var running = false; + var runtimeAnimations = this._runtimeAnimations; + var index; + for (index = 0; index < runtimeAnimations.length; index++) { + var animation = runtimeAnimations[index]; + var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight); + running = running || isRunning; + } + this.animationStarted = running; + if (!running) { + if (this.disposeOnEnd) { + // Remove from active animatables + index = this._scene._activeAnimatables.indexOf(this); + this._scene._activeAnimatables.splice(index, 1); + // Dispose all runtime animations + for (index = 0; index < runtimeAnimations.length; index++) { + runtimeAnimations[index].dispose(); + } + } + this._raiseOnAnimationEnd(); + if (this.disposeOnEnd) { + this.onAnimationEnd = null; + this.onAnimationLoop = null; + this.onAnimationLoopObservable.clear(); + this.onAnimationEndObservable.clear(); + } + } + return running; + }; + return Animatable; +}()); + +_scene__WEBPACK_IMPORTED_MODULE_3__["Scene"].prototype._animate = function () { + if (!this.animationsEnabled) { + return; + } + var animatables = this._activeAnimatables; + if (animatables.length === 0) { + return; + } + // Getting time + var now = _Misc_precisionDate__WEBPACK_IMPORTED_MODULE_5__["PrecisionDate"].Now; + if (!this._animationTimeLast) { + if (this._pendingData.length > 0) { + return; + } + this._animationTimeLast = now; + } + var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale; + this._animationTime += deltaTime; + var animationTime = this._animationTime; + this._animationTimeLast = now; + for (var index = 0; index < animatables.length; index++) { + var animatable = animatables[index]; + if (!animatable._animate(animationTime) && animatable.disposeOnEnd) { + index--; // Array was updated + } + } + // Late animation bindings + this._processLateAnimationBindings(); +}; +_scene__WEBPACK_IMPORTED_MODULE_3__["Scene"].prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask, onAnimationLoop) { + if (weight === void 0) { weight = 1.0; } + if (speedRatio === void 0) { speedRatio = 1.0; } + var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask, onAnimationLoop); + returnedAnimatable.weight = weight; + return returnedAnimatable; +}; +_scene__WEBPACK_IMPORTED_MODULE_3__["Scene"].prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask, onAnimationLoop) { + if (speedRatio === void 0) { speedRatio = 1.0; } + if (stopCurrent === void 0) { stopCurrent = true; } + if (from > to && speedRatio > 0) { + speedRatio *= -1; + } + if (stopCurrent) { + this.stopAnimation(target, undefined, targetMask); + } + if (!animatable) { + animatable = new Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, undefined, onAnimationLoop); + } + var shouldRunTargetAnimations = targetMask ? targetMask(target) : true; + // Local animations + if (target.animations && shouldRunTargetAnimations) { + animatable.appendAnimations(target, target.animations); + } + // Children animations + if (target.getAnimatables) { + var animatables = target.getAnimatables(); + for (var index = 0; index < animatables.length; index++) { + this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask, onAnimationLoop); + } + } + animatable.reset(); + return animatable; +}; +_scene__WEBPACK_IMPORTED_MODULE_3__["Scene"].prototype.beginHierarchyAnimation = function (target, directDescendantsOnly, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask, onAnimationLoop) { + if (speedRatio === void 0) { speedRatio = 1.0; } + if (stopCurrent === void 0) { stopCurrent = true; } + var children = target.getDescendants(directDescendantsOnly); + var result = []; + result.push(this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask)); + for (var _i = 0, children_1 = children; _i < children_1.length; _i++) { + var child = children_1[_i]; + result.push(this.beginAnimation(child, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask)); + } + return result; +}; +_scene__WEBPACK_IMPORTED_MODULE_3__["Scene"].prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd, onAnimationLoop) { + if (speedRatio === undefined) { + speedRatio = 1.0; + } + var animatable = new Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations, onAnimationLoop); + return animatable; +}; +_scene__WEBPACK_IMPORTED_MODULE_3__["Scene"].prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd, onAnimationLoop) { + var children = target.getDescendants(directDescendantsOnly); + var result = []; + result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd, onAnimationLoop)); + for (var _i = 0, children_2 = children; _i < children_2.length; _i++) { + var child = children_2[_i]; + result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd, onAnimationLoop)); + } + return result; +}; +_scene__WEBPACK_IMPORTED_MODULE_3__["Scene"].prototype.getAnimatableByTarget = function (target) { + for (var index = 0; index < this._activeAnimatables.length; index++) { + if (this._activeAnimatables[index].target === target) { + return this._activeAnimatables[index]; + } + } + return null; +}; +_scene__WEBPACK_IMPORTED_MODULE_3__["Scene"].prototype.getAllAnimatablesByTarget = function (target) { + var result = []; + for (var index = 0; index < this._activeAnimatables.length; index++) { + if (this._activeAnimatables[index].target === target) { + result.push(this._activeAnimatables[index]); + } + } + return result; +}; +/** + * Will stop the animation of the given target + * @param target - the target + * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty) + * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty) + */ +_scene__WEBPACK_IMPORTED_MODULE_3__["Scene"].prototype.stopAnimation = function (target, animationName, targetMask) { + var animatables = this.getAllAnimatablesByTarget(target); + for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) { + var animatable = animatables_1[_i]; + animatable.stop(animationName, targetMask); + } +}; +/** + * Stops and removes all animations that have been applied to the scene + */ +_scene__WEBPACK_IMPORTED_MODULE_3__["Scene"].prototype.stopAllAnimations = function () { + if (this._activeAnimatables) { + for (var i = 0; i < this._activeAnimatables.length; i++) { + this._activeAnimatables[i].stop(); + } + this._activeAnimatables = []; + } + for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) { + var group = _a[_i]; + group.stop(); + } +}; +_scene__WEBPACK_IMPORTED_MODULE_3__["Scene"].prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) { + var target = runtimeAnimation.target; + this._registeredForLateAnimationBindings.pushNoDuplicate(target); + if (!target._lateAnimationHolders) { + target._lateAnimationHolders = {}; + } + if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) { + target._lateAnimationHolders[runtimeAnimation.targetPath] = { + totalWeight: 0, + animations: [], + originalValue: originalValue + }; + } + target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation); + target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight; +}; +_scene__WEBPACK_IMPORTED_MODULE_3__["Scene"].prototype._processLateAnimationBindingsForMatrices = function (holder) { + var normalizer = 1.0; + var finalPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Tmp"].Vector3[0]; + var finalScaling = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Tmp"].Vector3[1]; + var finalQuaternion = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Tmp"].Quaternion[0]; + var startIndex = 0; + var originalAnimation = holder.animations[0]; + var originalValue = holder.originalValue; + var scale = 1; + if (holder.totalWeight < 1.0) { + // We need to mix the original value in + originalValue.decompose(finalScaling, finalQuaternion, finalPosition); + scale = 1.0 - holder.totalWeight; + } + else { + startIndex = 1; + // We need to normalize the weights + normalizer = holder.totalWeight; + originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition); + scale = originalAnimation.weight / normalizer; + if (scale == 1) { + return originalAnimation.currentValue; + } + } + finalScaling.scaleInPlace(scale); + finalPosition.scaleInPlace(scale); + finalQuaternion.scaleInPlace(scale); + for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) { + var runtimeAnimation = holder.animations[animIndex]; + var scale = runtimeAnimation.weight / normalizer; + var currentPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Tmp"].Vector3[2]; + var currentScaling = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Tmp"].Vector3[3]; + var currentQuaternion = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Tmp"].Quaternion[1]; + runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition); + currentScaling.scaleAndAddToRef(scale, finalScaling); + currentQuaternion.scaleAndAddToRef(scale, finalQuaternion); + currentPosition.scaleAndAddToRef(scale, finalPosition); + } + var workValue = originalAnimation._animationState.workValue; + _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"].ComposeToRef(finalScaling, finalQuaternion, finalPosition, workValue); + return workValue; +}; +_scene__WEBPACK_IMPORTED_MODULE_3__["Scene"].prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) { + var originalAnimation = holder.animations[0]; + var originalValue = holder.originalValue; + if (holder.animations.length === 1) { + _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Quaternion"].SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion); + return refQuaternion; + } + var normalizer = 1.0; + var quaternions; + var weights; + if (holder.totalWeight < 1.0) { + var scale = 1.0 - holder.totalWeight; + quaternions = []; + weights = []; + quaternions.push(originalValue); + weights.push(scale); + } + else { + if (holder.animations.length === 2) { // Slerp as soon as we can + _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Quaternion"].SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion); + return refQuaternion; + } + quaternions = []; + weights = []; + normalizer = holder.totalWeight; + } + for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) { + var runtimeAnimation = holder.animations[animIndex]; + quaternions.push(runtimeAnimation.currentValue); + weights.push(runtimeAnimation.weight / normalizer); + } + // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions + var cumulativeAmount = 0; + var cumulativeQuaternion = null; + for (var index = 0; index < quaternions.length;) { + if (!cumulativeQuaternion) { + _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Quaternion"].SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion); + cumulativeQuaternion = refQuaternion; + cumulativeAmount = weights[index] + weights[index + 1]; + index += 2; + continue; + } + cumulativeAmount += weights[index]; + _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Quaternion"].SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion); + index++; + } + return cumulativeQuaternion; +}; +_scene__WEBPACK_IMPORTED_MODULE_3__["Scene"].prototype._processLateAnimationBindings = function () { + if (!this._registeredForLateAnimationBindings.length) { + return; + } + for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) { + var target = this._registeredForLateAnimationBindings.data[index]; + for (var path in target._lateAnimationHolders) { + var holder = target._lateAnimationHolders[path]; + var originalAnimation = holder.animations[0]; + var originalValue = holder.originalValue; + var matrixDecomposeMode = _animation__WEBPACK_IMPORTED_MODULE_0__["Animation"].AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix + var finalValue = target[path]; + if (matrixDecomposeMode) { + finalValue = this._processLateAnimationBindingsForMatrices(holder); + } + else { + var quaternionMode = originalValue.w !== undefined; + if (quaternionMode) { + finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Quaternion"].Identity()); + } + else { + var startIndex = 0; + var normalizer = 1.0; + if (holder.totalWeight < 1.0) { + // We need to mix the original value in + if (originalValue.scale) { + finalValue = originalValue.scale(1.0 - holder.totalWeight); + } + else { + finalValue = originalValue * (1.0 - holder.totalWeight); + } + } + else { + // We need to normalize the weights + normalizer = holder.totalWeight; + var scale_1 = originalAnimation.weight / normalizer; + if (scale_1 !== 1) { + if (originalAnimation.currentValue.scale) { + finalValue = originalAnimation.currentValue.scale(scale_1); + } + else { + finalValue = originalAnimation.currentValue * scale_1; + } + } + else { + finalValue = originalAnimation.currentValue; + } + startIndex = 1; + } + for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) { + var runtimeAnimation = holder.animations[animIndex]; + var scale = runtimeAnimation.weight / normalizer; + if (runtimeAnimation.currentValue.scaleAndAddToRef) { + runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue); + } + else { + finalValue += runtimeAnimation.currentValue * scale; + } + } + } + } + target[path] = finalValue; + } + target._lateAnimationHolders = {}; + } + this._registeredForLateAnimationBindings.reset(); +}; +_Bones_bone__WEBPACK_IMPORTED_MODULE_6__["Bone"].prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) { + if (rescaleAsRequired === void 0) { rescaleAsRequired = false; } + if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; } + // all animation may be coming from a library skeleton, so may need to create animation + if (this.animations.length === 0) { + this.animations.push(new _animation__WEBPACK_IMPORTED_MODULE_0__["Animation"](this.name, "_matrix", source.animations[0].framePerSecond, _animation__WEBPACK_IMPORTED_MODULE_0__["Animation"].ANIMATIONTYPE_MATRIX, 0)); + this.animations[0].setKeys([]); + } + // get animation info / verify there is such a range from the source bone + var sourceRange = source.animations[0].getRange(rangeName); + if (!sourceRange) { + return false; + } + var from = sourceRange.from; + var to = sourceRange.to; + var sourceKeys = source.animations[0].getKeys(); + // rescaling prep + var sourceBoneLength = source.length; + var sourceParent = source.getParent(); + var parent = this.getParent(); + var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length; + var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1; + var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1); + var destKeys = this.animations[0].getKeys(); + // loop vars declaration + var orig; + var origTranslation; + var mat; + for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) { + orig = sourceKeys[key]; + if (orig.frame >= from && orig.frame <= to) { + if (rescaleAsRequired) { + mat = orig.value.clone(); + // scale based on parent ratio, when bone has parent + if (parentScalingReqd) { + origTranslation = mat.getTranslation(); + mat.setTranslation(origTranslation.scaleInPlace(parentRatio)); + // scale based on skeleton dimension ratio when root bone, and value is passed + } + else if (dimensionsScalingReqd && skelDimensionsRatio) { + origTranslation = mat.getTranslation(); + mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio)); + // use original when root bone, and no data for skelDimensionsRatio + } + else { + mat = orig.value; + } + } + else { + mat = orig.value; + } + destKeys.push({ frame: orig.frame + frameOffset, value: mat }); + } + } + this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset); + return true; +}; + + +/***/ }), + +/***/ "./Animations/animation.ts": +/*!*********************************!*\ + !*** ./Animations/animation.ts ***! + \*********************************/ +/*! exports provided: _IAnimationState, Animation */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_IAnimationState", function() { return _IAnimationState; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Animation", function() { return Animation; }); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Maths_math_scalar__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math.scalar */ "./Maths/math.scalar.ts"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Misc/typeStore */ "./Misc/typeStore.ts"); +/* harmony import */ var _animationKey__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./animationKey */ "./Animations/animationKey.ts"); +/* harmony import */ var _animationRange__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./animationRange */ "./Animations/animationRange.ts"); +/* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../node */ "./node.ts"); + + + + + + + +/** + * @hidden + */ +var _IAnimationState = /** @class */ (function () { + function _IAnimationState() { + } + return _IAnimationState; +}()); + +/** + * Class used to store any kind of animation + */ +var Animation = /** @class */ (function () { + /** + * Initializes the animation + * @param name Name of the animation + * @param targetProperty Property to animate + * @param framePerSecond The frames per second of the animation + * @param dataType The data type of the animation + * @param loopMode The loop mode of the animation + * @param enableBlending Specifies if blending should be enabled + */ + function Animation( + /**Name of the animation */ + name, + /**Property to animate */ + targetProperty, + /**The frames per second of the animation */ + framePerSecond, + /**The data type of the animation */ + dataType, + /**The loop mode of the animation */ + loopMode, + /**Specifies if blending should be enabled */ + enableBlending) { + this.name = name; + this.targetProperty = targetProperty; + this.framePerSecond = framePerSecond; + this.dataType = dataType; + this.loopMode = loopMode; + this.enableBlending = enableBlending; + /** + * @hidden Internal use only + */ + this._runtimeAnimations = new Array(); + /** + * The set of event that will be linked to this animation + */ + this._events = new Array(); + /** + * Stores the blending speed of the animation + */ + this.blendingSpeed = 0.01; + /** + * Stores the animation ranges for the animation + */ + this._ranges = {}; + this.targetPropertyPath = targetProperty.split("."); + this.dataType = dataType; + this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode; + } + /** + * @hidden Internal use + */ + Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) { + var dataType = undefined; + if (!isNaN(parseFloat(from)) && isFinite(from)) { + dataType = Animation.ANIMATIONTYPE_FLOAT; + } + else if (from instanceof _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"]) { + dataType = Animation.ANIMATIONTYPE_QUATERNION; + } + else if (from instanceof _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"]) { + dataType = Animation.ANIMATIONTYPE_VECTOR3; + } + else if (from instanceof _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector2"]) { + dataType = Animation.ANIMATIONTYPE_VECTOR2; + } + else if (from instanceof _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Color3"]) { + dataType = Animation.ANIMATIONTYPE_COLOR3; + } + else if (from instanceof _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Size"]) { + dataType = Animation.ANIMATIONTYPE_SIZE; + } + if (dataType == undefined) { + return null; + } + var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode); + var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }]; + animation.setKeys(keys); + if (easingFunction !== undefined) { + animation.setEasingFunction(easingFunction); + } + return animation; + }; + /** + * Sets up an animation + * @param property The property to animate + * @param animationType The animation type to apply + * @param framePerSecond The frames per second of the animation + * @param easingFunction The easing function used in the animation + * @returns The created animation + */ + Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) { + var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT); + animation.setEasingFunction(easingFunction); + return animation; + }; + /** + * Create and start an animation on a node + * @param name defines the name of the global animation that will be run on all nodes + * @param node defines the root node where the animation will take place + * @param targetProperty defines property to animate + * @param framePerSecond defines the number of frame per second yo use + * @param totalFrame defines the number of frames in total + * @param from defines the initial value + * @param to defines the final value + * @param loopMode defines which loop mode you want to use (off by default) + * @param easingFunction defines the easing function to use (linear by default) + * @param onAnimationEnd defines the callback to call when animation end + * @returns the animatable created for this animation + */ + Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) { + var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction); + if (!animation) { + return null; + } + return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd); + }; + /** + * Create and start an animation on a node and its descendants + * @param name defines the name of the global animation that will be run on all nodes + * @param node defines the root node where the animation will take place + * @param directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used + * @param targetProperty defines property to animate + * @param framePerSecond defines the number of frame per second to use + * @param totalFrame defines the number of frames in total + * @param from defines the initial value + * @param to defines the final value + * @param loopMode defines which loop mode you want to use (off by default) + * @param easingFunction defines the easing function to use (linear by default) + * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node) + * @returns the list of animatables created for all nodes + * @example https://www.babylonjs-playground.com/#MH0VLI + */ + Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) { + var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction); + if (!animation) { + return null; + } + var scene = node.getScene(); + return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd); + }; + /** + * Creates a new animation, merges it with the existing animations and starts it + * @param name Name of the animation + * @param node Node which contains the scene that begins the animations + * @param targetProperty Specifies which property to animate + * @param framePerSecond The frames per second of the animation + * @param totalFrame The total number of frames + * @param from The frame at the beginning of the animation + * @param to The frame at the end of the animation + * @param loopMode Specifies the loop mode of the animation + * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations + * @param onAnimationEnd Callback to run once the animation is complete + * @returns Nullable animation + */ + Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) { + var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction); + if (!animation) { + return null; + } + node.animations.push(animation); + return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd); + }; + /** + * Transition property of an host to the target Value + * @param property The property to transition + * @param targetValue The target Value of the property + * @param host The object where the property to animate belongs + * @param scene Scene used to run the animation + * @param frameRate Framerate (in frame/s) to use + * @param transition The transition type we want to use + * @param duration The duration of the animation, in milliseconds + * @param onAnimationEnd Callback trigger at the end of the animation + * @returns Nullable animation + */ + Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) { + if (onAnimationEnd === void 0) { onAnimationEnd = null; } + if (duration <= 0) { + host[property] = targetValue; + if (onAnimationEnd) { + onAnimationEnd(); + } + return null; + } + var endFrame = frameRate * (duration / 1000); + transition.setKeys([{ + frame: 0, + value: host[property].clone ? host[property].clone() : host[property] + }, + { + frame: endFrame, + value: targetValue + }]); + if (!host.animations) { + host.animations = []; + } + host.animations.push(transition); + var animation = scene.beginAnimation(host, 0, endFrame, false); + animation.onAnimationEnd = onAnimationEnd; + return animation; + }; + Object.defineProperty(Animation.prototype, "runtimeAnimations", { + /** + * Return the array of runtime animations currently using this animation + */ + get: function () { + return this._runtimeAnimations; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", { + /** + * Specifies if any of the runtime animations are currently running + */ + get: function () { + for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) { + var runtimeAnimation = _a[_i]; + if (!runtimeAnimation.isStopped) { + return true; + } + } + return false; + }, + enumerable: true, + configurable: true + }); + // Methods + /** + * Converts the animation to a string + * @param fullDetails support for multiple levels of logging within scene loading + * @returns String form of the animation + */ + Animation.prototype.toString = function (fullDetails) { + var ret = "Name: " + this.name + ", property: " + this.targetProperty; + ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType]; + ret += ", nKeys: " + (this._keys ? this._keys.length : "none"); + ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none"); + if (fullDetails) { + ret += ", Ranges: {"; + var first = true; + for (var name in this._ranges) { + if (first) { + ret += ", "; + first = false; + } + ret += name; + } + ret += "}"; + } + return ret; + }; + /** + * Add an event to this animation + * @param event Event to add + */ + Animation.prototype.addEvent = function (event) { + this._events.push(event); + }; + /** + * Remove all events found at the given frame + * @param frame The frame to remove events from + */ + Animation.prototype.removeEvents = function (frame) { + for (var index = 0; index < this._events.length; index++) { + if (this._events[index].frame === frame) { + this._events.splice(index, 1); + index--; + } + } + }; + /** + * Retrieves all the events from the animation + * @returns Events from the animation + */ + Animation.prototype.getEvents = function () { + return this._events; + }; + /** + * Creates an animation range + * @param name Name of the animation range + * @param from Starting frame of the animation range + * @param to Ending frame of the animation + */ + Animation.prototype.createRange = function (name, from, to) { + // check name not already in use; could happen for bones after serialized + if (!this._ranges[name]) { + this._ranges[name] = new _animationRange__WEBPACK_IMPORTED_MODULE_5__["AnimationRange"](name, from, to); + } + }; + /** + * Deletes an animation range by name + * @param name Name of the animation range to delete + * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false) + */ + Animation.prototype.deleteRange = function (name, deleteFrames) { + if (deleteFrames === void 0) { deleteFrames = true; } + var range = this._ranges[name]; + if (!range) { + return; + } + if (deleteFrames) { + var from = range.from; + var to = range.to; + // this loop MUST go high to low for multiple splices to work + for (var key = this._keys.length - 1; key >= 0; key--) { + if (this._keys[key].frame >= from && this._keys[key].frame <= to) { + this._keys.splice(key, 1); + } + } + } + this._ranges[name] = null; // said much faster than 'delete this._range[name]' + }; + /** + * Gets the animation range by name, or null if not defined + * @param name Name of the animation range + * @returns Nullable animation range + */ + Animation.prototype.getRange = function (name) { + return this._ranges[name]; + }; + /** + * Gets the key frames from the animation + * @returns The key frames of the animation + */ + Animation.prototype.getKeys = function () { + return this._keys; + }; + /** + * Gets the highest frame rate of the animation + * @returns Highest frame rate of the animation + */ + Animation.prototype.getHighestFrame = function () { + var ret = 0; + for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) { + if (ret < this._keys[key].frame) { + ret = this._keys[key].frame; + } + } + return ret; + }; + /** + * Gets the easing function of the animation + * @returns Easing function of the animation + */ + Animation.prototype.getEasingFunction = function () { + return this._easingFunction; + }; + /** + * Sets the easing function of the animation + * @param easingFunction A custom mathematical formula for animation + */ + Animation.prototype.setEasingFunction = function (easingFunction) { + this._easingFunction = easingFunction; + }; + /** + * Interpolates a scalar linearly + * @param startValue Start value of the animation curve + * @param endValue End value of the animation curve + * @param gradient Scalar amount to interpolate + * @returns Interpolated scalar value + */ + Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) { + return _Maths_math_scalar__WEBPACK_IMPORTED_MODULE_1__["Scalar"].Lerp(startValue, endValue, gradient); + }; + /** + * Interpolates a scalar cubically + * @param startValue Start value of the animation curve + * @param outTangent End tangent of the animation + * @param endValue End value of the animation curve + * @param inTangent Start tangent of the animation curve + * @param gradient Scalar amount to interpolate + * @returns Interpolated scalar value + */ + Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) { + return _Maths_math_scalar__WEBPACK_IMPORTED_MODULE_1__["Scalar"].Hermite(startValue, outTangent, endValue, inTangent, gradient); + }; + /** + * Interpolates a quaternion using a spherical linear interpolation + * @param startValue Start value of the animation curve + * @param endValue End value of the animation curve + * @param gradient Scalar amount to interpolate + * @returns Interpolated quaternion value + */ + Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) { + return _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].Slerp(startValue, endValue, gradient); + }; + /** + * Interpolates a quaternion cubically + * @param startValue Start value of the animation curve + * @param outTangent End tangent of the animation curve + * @param endValue End value of the animation curve + * @param inTangent Start tangent of the animation curve + * @param gradient Scalar amount to interpolate + * @returns Interpolated quaternion value + */ + Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) { + return _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize(); + }; + /** + * Interpolates a Vector3 linearl + * @param startValue Start value of the animation curve + * @param endValue End value of the animation curve + * @param gradient Scalar amount to interpolate + * @returns Interpolated scalar value + */ + Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) { + return _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Lerp(startValue, endValue, gradient); + }; + /** + * Interpolates a Vector3 cubically + * @param startValue Start value of the animation curve + * @param outTangent End tangent of the animation + * @param endValue End value of the animation curve + * @param inTangent Start tangent of the animation curve + * @param gradient Scalar amount to interpolate + * @returns InterpolatedVector3 value + */ + Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) { + return _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Hermite(startValue, outTangent, endValue, inTangent, gradient); + }; + /** + * Interpolates a Vector2 linearly + * @param startValue Start value of the animation curve + * @param endValue End value of the animation curve + * @param gradient Scalar amount to interpolate + * @returns Interpolated Vector2 value + */ + Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) { + return _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector2"].Lerp(startValue, endValue, gradient); + }; + /** + * Interpolates a Vector2 cubically + * @param startValue Start value of the animation curve + * @param outTangent End tangent of the animation + * @param endValue End value of the animation curve + * @param inTangent Start tangent of the animation curve + * @param gradient Scalar amount to interpolate + * @returns Interpolated Vector2 value + */ + Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) { + return _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector2"].Hermite(startValue, outTangent, endValue, inTangent, gradient); + }; + /** + * Interpolates a size linearly + * @param startValue Start value of the animation curve + * @param endValue End value of the animation curve + * @param gradient Scalar amount to interpolate + * @returns Interpolated Size value + */ + Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) { + return _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Size"].Lerp(startValue, endValue, gradient); + }; + /** + * Interpolates a Color3 linearly + * @param startValue Start value of the animation curve + * @param endValue End value of the animation curve + * @param gradient Scalar amount to interpolate + * @returns Interpolated Color3 value + */ + Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) { + return _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Color3"].Lerp(startValue, endValue, gradient); + }; + /** + * @hidden Internal use only + */ + Animation.prototype._getKeyValue = function (value) { + if (typeof value === "function") { + return value(); + } + return value; + }; + /** + * @hidden Internal use only + */ + Animation.prototype._interpolate = function (currentFrame, state) { + if (state.loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && state.repeatCount > 0) { + return state.highLimitValue.clone ? state.highLimitValue.clone() : state.highLimitValue; + } + var keys = this._keys; + if (keys.length === 1) { + return this._getKeyValue(keys[0].value); + } + var startKeyIndex = state.key; + if (keys[startKeyIndex].frame >= currentFrame) { + while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) { + startKeyIndex--; + } + } + for (var key = startKeyIndex; key < keys.length; key++) { + var endKey = keys[key + 1]; + if (endKey.frame >= currentFrame) { + state.key = key; + var startKey = keys[key]; + var startValue = this._getKeyValue(startKey.value); + if (startKey.interpolation === _animationKey__WEBPACK_IMPORTED_MODULE_4__["AnimationKeyInterpolation"].STEP) { + return startValue; + } + var endValue = this._getKeyValue(endKey.value); + var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined; + var frameDelta = endKey.frame - startKey.frame; + // gradient : percent of currentFrame between the frame inf and the frame sup + var gradient = (currentFrame - startKey.frame) / frameDelta; + // check for easingFunction and correction of gradient + var easingFunction = this.getEasingFunction(); + if (easingFunction != null) { + gradient = easingFunction.ease(gradient); + } + switch (this.dataType) { + // Float + case Animation.ANIMATIONTYPE_FLOAT: + var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient); + switch (state.loopMode) { + case Animation.ANIMATIONLOOPMODE_CYCLE: + case Animation.ANIMATIONLOOPMODE_CONSTANT: + return floatValue; + case Animation.ANIMATIONLOOPMODE_RELATIVE: + return state.offsetValue * state.repeatCount + floatValue; + } + break; + // Quaternion + case Animation.ANIMATIONTYPE_QUATERNION: + var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient); + switch (state.loopMode) { + case Animation.ANIMATIONLOOPMODE_CYCLE: + case Animation.ANIMATIONLOOPMODE_CONSTANT: + return quatValue; + case Animation.ANIMATIONLOOPMODE_RELATIVE: + return quatValue.addInPlace(state.offsetValue.scale(state.repeatCount)); + } + return quatValue; + // Vector3 + case Animation.ANIMATIONTYPE_VECTOR3: + var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient); + switch (state.loopMode) { + case Animation.ANIMATIONLOOPMODE_CYCLE: + case Animation.ANIMATIONLOOPMODE_CONSTANT: + return vec3Value; + case Animation.ANIMATIONLOOPMODE_RELATIVE: + return vec3Value.add(state.offsetValue.scale(state.repeatCount)); + } + // Vector2 + case Animation.ANIMATIONTYPE_VECTOR2: + var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient); + switch (state.loopMode) { + case Animation.ANIMATIONLOOPMODE_CYCLE: + case Animation.ANIMATIONLOOPMODE_CONSTANT: + return vec2Value; + case Animation.ANIMATIONLOOPMODE_RELATIVE: + return vec2Value.add(state.offsetValue.scale(state.repeatCount)); + } + // Size + case Animation.ANIMATIONTYPE_SIZE: + switch (state.loopMode) { + case Animation.ANIMATIONLOOPMODE_CYCLE: + case Animation.ANIMATIONLOOPMODE_CONSTANT: + return this.sizeInterpolateFunction(startValue, endValue, gradient); + case Animation.ANIMATIONLOOPMODE_RELATIVE: + return this.sizeInterpolateFunction(startValue, endValue, gradient).add(state.offsetValue.scale(state.repeatCount)); + } + // Color3 + case Animation.ANIMATIONTYPE_COLOR3: + switch (state.loopMode) { + case Animation.ANIMATIONLOOPMODE_CYCLE: + case Animation.ANIMATIONLOOPMODE_CONSTANT: + return this.color3InterpolateFunction(startValue, endValue, gradient); + case Animation.ANIMATIONLOOPMODE_RELATIVE: + return this.color3InterpolateFunction(startValue, endValue, gradient).add(state.offsetValue.scale(state.repeatCount)); + } + // Matrix + case Animation.ANIMATIONTYPE_MATRIX: + switch (state.loopMode) { + case Animation.ANIMATIONLOOPMODE_CYCLE: + case Animation.ANIMATIONLOOPMODE_CONSTANT: + if (Animation.AllowMatricesInterpolation) { + return this.matrixInterpolateFunction(startValue, endValue, gradient, state.workValue); + } + case Animation.ANIMATIONLOOPMODE_RELATIVE: + return startValue; + } + default: + break; + } + break; + } + } + return this._getKeyValue(keys[keys.length - 1].value); + }; + /** + * Defines the function to use to interpolate matrices + * @param startValue defines the start matrix + * @param endValue defines the end matrix + * @param gradient defines the gradient between both matrices + * @param result defines an optional target matrix where to store the interpolation + * @returns the interpolated matrix + */ + Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) { + if (Animation.AllowMatrixDecomposeForInterpolation) { + if (result) { + _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].DecomposeLerpToRef(startValue, endValue, gradient, result); + return result; + } + return _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].DecomposeLerp(startValue, endValue, gradient); + } + if (result) { + _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].LerpToRef(startValue, endValue, gradient, result); + return result; + } + return _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].Lerp(startValue, endValue, gradient); + }; + /** + * Makes a copy of the animation + * @returns Cloned animation + */ + Animation.prototype.clone = function () { + var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode); + clone.enableBlending = this.enableBlending; + clone.blendingSpeed = this.blendingSpeed; + if (this._keys) { + clone.setKeys(this._keys); + } + if (this._ranges) { + clone._ranges = {}; + for (var name in this._ranges) { + var range = this._ranges[name]; + if (!range) { + continue; + } + clone._ranges[name] = range.clone(); + } + } + return clone; + }; + /** + * Sets the key frames of the animation + * @param values The animation key frames to set + */ + Animation.prototype.setKeys = function (values) { + this._keys = values.slice(0); + }; + /** + * Serializes the animation to an object + * @returns Serialized object + */ + Animation.prototype.serialize = function () { + var serializationObject = {}; + serializationObject.name = this.name; + serializationObject.property = this.targetProperty; + serializationObject.framePerSecond = this.framePerSecond; + serializationObject.dataType = this.dataType; + serializationObject.loopBehavior = this.loopMode; + serializationObject.enableBlending = this.enableBlending; + serializationObject.blendingSpeed = this.blendingSpeed; + var dataType = this.dataType; + serializationObject.keys = []; + var keys = this.getKeys(); + for (var index = 0; index < keys.length; index++) { + var animationKey = keys[index]; + var key = {}; + key.frame = animationKey.frame; + switch (dataType) { + case Animation.ANIMATIONTYPE_FLOAT: + key.values = [animationKey.value]; + break; + case Animation.ANIMATIONTYPE_QUATERNION: + case Animation.ANIMATIONTYPE_MATRIX: + case Animation.ANIMATIONTYPE_VECTOR3: + case Animation.ANIMATIONTYPE_COLOR3: + key.values = animationKey.value.asArray(); + break; + } + serializationObject.keys.push(key); + } + serializationObject.ranges = []; + for (var name in this._ranges) { + var source = this._ranges[name]; + if (!source) { + continue; + } + var range = {}; + range.name = name; + range.from = source.from; + range.to = source.to; + serializationObject.ranges.push(range); + } + return serializationObject; + }; + Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", { + /** + * Get the float animation type + */ + get: function () { + return Animation._ANIMATIONTYPE_FLOAT; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", { + /** + * Get the Vector3 animation type + */ + get: function () { + return Animation._ANIMATIONTYPE_VECTOR3; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", { + /** + * Get the Vector2 animation type + */ + get: function () { + return Animation._ANIMATIONTYPE_VECTOR2; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", { + /** + * Get the Size animation type + */ + get: function () { + return Animation._ANIMATIONTYPE_SIZE; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", { + /** + * Get the Quaternion animation type + */ + get: function () { + return Animation._ANIMATIONTYPE_QUATERNION; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", { + /** + * Get the Matrix animation type + */ + get: function () { + return Animation._ANIMATIONTYPE_MATRIX; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", { + /** + * Get the Color3 animation type + */ + get: function () { + return Animation._ANIMATIONTYPE_COLOR3; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", { + /** + * Get the Relative Loop Mode + */ + get: function () { + return Animation._ANIMATIONLOOPMODE_RELATIVE; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", { + /** + * Get the Cycle Loop Mode + */ + get: function () { + return Animation._ANIMATIONLOOPMODE_CYCLE; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", { + /** + * Get the Constant Loop Mode + */ + get: function () { + return Animation._ANIMATIONLOOPMODE_CONSTANT; + }, + enumerable: true, + configurable: true + }); + /** @hidden */ + Animation._UniversalLerp = function (left, right, amount) { + var constructor = left.constructor; + if (constructor.Lerp) { // Lerp supported + return constructor.Lerp(left, right, amount); + } + else if (constructor.Slerp) { // Slerp supported + return constructor.Slerp(left, right, amount); + } + else if (left.toFixed) { // Number + return left * (1.0 - amount) + amount * right; + } + else { // Blending not supported + return right; + } + }; + /** + * Parses an animation object and creates an animation + * @param parsedAnimation Parsed animation object + * @returns Animation object + */ + Animation.Parse = function (parsedAnimation) { + var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior); + var dataType = parsedAnimation.dataType; + var keys = []; + var data; + var index; + if (parsedAnimation.enableBlending) { + animation.enableBlending = parsedAnimation.enableBlending; + } + if (parsedAnimation.blendingSpeed) { + animation.blendingSpeed = parsedAnimation.blendingSpeed; + } + for (index = 0; index < parsedAnimation.keys.length; index++) { + var key = parsedAnimation.keys[index]; + var inTangent; + var outTangent; + switch (dataType) { + case Animation.ANIMATIONTYPE_FLOAT: + data = key.values[0]; + if (key.values.length >= 1) { + inTangent = key.values[1]; + } + if (key.values.length >= 2) { + outTangent = key.values[2]; + } + break; + case Animation.ANIMATIONTYPE_QUATERNION: + data = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].FromArray(key.values); + if (key.values.length >= 8) { + var _inTangent = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].FromArray(key.values.slice(4, 8)); + if (!_inTangent.equals(_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].Zero())) { + inTangent = _inTangent; + } + } + if (key.values.length >= 12) { + var _outTangent = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].FromArray(key.values.slice(8, 12)); + if (!_outTangent.equals(_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].Zero())) { + outTangent = _outTangent; + } + } + break; + case Animation.ANIMATIONTYPE_MATRIX: + data = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].FromArray(key.values); + break; + case Animation.ANIMATIONTYPE_COLOR3: + data = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Color3"].FromArray(key.values); + break; + case Animation.ANIMATIONTYPE_VECTOR3: + default: + data = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].FromArray(key.values); + break; + } + var keyData = {}; + keyData.frame = key.frame; + keyData.value = data; + if (inTangent != undefined) { + keyData.inTangent = inTangent; + } + if (outTangent != undefined) { + keyData.outTangent = outTangent; + } + keys.push(keyData); + } + animation.setKeys(keys); + if (parsedAnimation.ranges) { + for (index = 0; index < parsedAnimation.ranges.length; index++) { + data = parsedAnimation.ranges[index]; + animation.createRange(data.name, data.from, data.to); + } + } + return animation; + }; + /** + * Appends the serialized animations from the source animations + * @param source Source containing the animations + * @param destination Target to store the animations + */ + Animation.AppendSerializedAnimations = function (source, destination) { + _Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["SerializationHelper"].AppendSerializedAnimations(source, destination); + }; + /** + * Use matrix interpolation instead of using direct key value when animating matrices + */ + Animation.AllowMatricesInterpolation = false; + /** + * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower + */ + Animation.AllowMatrixDecomposeForInterpolation = true; + // Statics + /** + * Float animation type + */ + Animation._ANIMATIONTYPE_FLOAT = 0; + /** + * Vector3 animation type + */ + Animation._ANIMATIONTYPE_VECTOR3 = 1; + /** + * Quaternion animation type + */ + Animation._ANIMATIONTYPE_QUATERNION = 2; + /** + * Matrix animation type + */ + Animation._ANIMATIONTYPE_MATRIX = 3; + /** + * Color3 animation type + */ + Animation._ANIMATIONTYPE_COLOR3 = 4; + /** + * Vector2 animation type + */ + Animation._ANIMATIONTYPE_VECTOR2 = 5; + /** + * Size animation type + */ + Animation._ANIMATIONTYPE_SIZE = 6; + /** + * Relative Loop Mode + */ + Animation._ANIMATIONLOOPMODE_RELATIVE = 0; + /** + * Cycle Loop Mode + */ + Animation._ANIMATIONLOOPMODE_CYCLE = 1; + /** + * Constant Loop Mode + */ + Animation._ANIMATIONLOOPMODE_CONSTANT = 2; + return Animation; +}()); + +_Misc_typeStore__WEBPACK_IMPORTED_MODULE_3__["_TypeStore"].RegisteredTypes["BABYLON.Animation"] = Animation; +_node__WEBPACK_IMPORTED_MODULE_6__["Node"]._AnimationRangeFactory = function (name, from, to) { return new _animationRange__WEBPACK_IMPORTED_MODULE_5__["AnimationRange"](name, from, to); }; + + +/***/ }), + +/***/ "./Animations/animationEvent.ts": +/*!**************************************!*\ + !*** ./Animations/animationEvent.ts ***! + \**************************************/ +/*! exports provided: AnimationEvent */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnimationEvent", function() { return AnimationEvent; }); +/** + * Composed of a frame, and an action function + */ +var AnimationEvent = /** @class */ (function () { + /** + * Initializes the animation event + * @param frame The frame for which the event is triggered + * @param action The event to perform when triggered + * @param onlyOnce Specifies if the event should be triggered only once + */ + function AnimationEvent( + /** The frame for which the event is triggered **/ + frame, + /** The event to perform when triggered **/ + action, + /** Specifies if the event should be triggered only once**/ + onlyOnce) { + this.frame = frame; + this.action = action; + this.onlyOnce = onlyOnce; + /** + * Specifies if the animation event is done + */ + this.isDone = false; + } + /** @hidden */ + AnimationEvent.prototype._clone = function () { + return new AnimationEvent(this.frame, this.action, this.onlyOnce); + }; + return AnimationEvent; +}()); + + + +/***/ }), + +/***/ "./Animations/animationGroup.ts": +/*!**************************************!*\ + !*** ./Animations/animationGroup.ts ***! + \**************************************/ +/*! exports provided: TargetedAnimation, AnimationGroup */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TargetedAnimation", function() { return TargetedAnimation; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnimationGroup", function() { return AnimationGroup; }); +/* harmony import */ var _animation__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./animation */ "./Animations/animation.ts"); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _Engines_engineStore__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Engines/engineStore */ "./Engines/engineStore.ts"); +/* harmony import */ var _animatable__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./animatable */ "./Animations/animatable.ts"); + + + + +/** + * This class defines the direct association between an animation and a target + */ +var TargetedAnimation = /** @class */ (function () { + function TargetedAnimation() { + } + /** + * Serialize the object + * @returns the JSON object representing the current entity + */ + TargetedAnimation.prototype.serialize = function () { + var serializationObject = {}; + serializationObject.animation = this.animation.serialize(); + serializationObject.targetId = this.target.id; + return serializationObject; + }; + return TargetedAnimation; +}()); + +/** + * Use this class to create coordinated animations on multiple targets + */ +var AnimationGroup = /** @class */ (function () { + /** + * Instantiates a new Animation Group. + * This helps managing several animations at once. + * @see http://doc.babylonjs.com/how_to/group + * @param name Defines the name of the group + * @param scene Defines the scene the group belongs to + */ + function AnimationGroup( + /** The name of the animation group */ + name, scene) { + if (scene === void 0) { scene = null; } + this.name = name; + this._targetedAnimations = new Array(); + this._animatables = new Array(); + this._from = Number.MAX_VALUE; + this._to = -Number.MAX_VALUE; + this._speedRatio = 1; + this._loopAnimation = false; + /** + * This observable will notify when one animation have ended + */ + this.onAnimationEndObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + /** + * Observer raised when one animation loops + */ + this.onAnimationLoopObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + /** + * This observable will notify when all animations have ended. + */ + this.onAnimationGroupEndObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + /** + * This observable will notify when all animations have paused. + */ + this.onAnimationGroupPauseObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + /** + * This observable will notify when all animations are playing. + */ + this.onAnimationGroupPlayObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + this._scene = scene || _Engines_engineStore__WEBPACK_IMPORTED_MODULE_2__["EngineStore"].LastCreatedScene; + this.uniqueId = this._scene.getUniqueId(); + this._scene.animationGroups.push(this); + } + Object.defineProperty(AnimationGroup.prototype, "from", { + /** + * Gets the first frame + */ + get: function () { + return this._from; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(AnimationGroup.prototype, "to", { + /** + * Gets the last frame + */ + get: function () { + return this._to; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(AnimationGroup.prototype, "isStarted", { + /** + * Define if the animations are started + */ + get: function () { + return this._isStarted; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(AnimationGroup.prototype, "isPlaying", { + /** + * Gets a value indicating that the current group is playing + */ + get: function () { + return this._isStarted && !this._isPaused; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(AnimationGroup.prototype, "speedRatio", { + /** + * Gets or sets the speed ratio to use for all animations + */ + get: function () { + return this._speedRatio; + }, + /** + * Gets or sets the speed ratio to use for all animations + */ + set: function (value) { + if (this._speedRatio === value) { + return; + } + this._speedRatio = value; + for (var index = 0; index < this._animatables.length; index++) { + var animatable = this._animatables[index]; + animatable.speedRatio = this._speedRatio; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(AnimationGroup.prototype, "loopAnimation", { + /** + * Gets or sets if all animations should loop or not + */ + get: function () { + return this._loopAnimation; + }, + set: function (value) { + if (this._loopAnimation === value) { + return; + } + this._loopAnimation = value; + for (var index = 0; index < this._animatables.length; index++) { + var animatable = this._animatables[index]; + animatable.loopAnimation = this._loopAnimation; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", { + /** + * Gets the targeted animations for this animation group + */ + get: function () { + return this._targetedAnimations; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(AnimationGroup.prototype, "animatables", { + /** + * returning the list of animatables controlled by this animation group. + */ + get: function () { + return this._animatables; + }, + enumerable: true, + configurable: true + }); + /** + * Add an animation (with its target) in the group + * @param animation defines the animation we want to add + * @param target defines the target of the animation + * @returns the TargetedAnimation object + */ + AnimationGroup.prototype.addTargetedAnimation = function (animation, target) { + var targetedAnimation = new TargetedAnimation(); + targetedAnimation.animation = animation; + targetedAnimation.target = target; + var keys = animation.getKeys(); + if (this._from > keys[0].frame) { + this._from = keys[0].frame; + } + if (this._to < keys[keys.length - 1].frame) { + this._to = keys[keys.length - 1].frame; + } + this._targetedAnimations.push(targetedAnimation); + return targetedAnimation; + }; + /** + * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame + * It can add constant keys at begin or end + * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null) + * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null) + * @returns the animation group + */ + AnimationGroup.prototype.normalize = function (beginFrame, endFrame) { + if (beginFrame === void 0) { beginFrame = null; } + if (endFrame === void 0) { endFrame = null; } + if (beginFrame == null) { + beginFrame = this._from; + } + if (endFrame == null) { + endFrame = this._to; + } + for (var index = 0; index < this._targetedAnimations.length; index++) { + var targetedAnimation = this._targetedAnimations[index]; + var keys = targetedAnimation.animation.getKeys(); + var startKey = keys[0]; + var endKey = keys[keys.length - 1]; + if (startKey.frame > beginFrame) { + var newKey = { + frame: beginFrame, + value: startKey.value, + inTangent: startKey.inTangent, + outTangent: startKey.outTangent, + interpolation: startKey.interpolation + }; + keys.splice(0, 0, newKey); + } + if (endKey.frame < endFrame) { + var newKey = { + frame: endFrame, + value: endKey.value, + inTangent: endKey.outTangent, + outTangent: endKey.outTangent, + interpolation: endKey.interpolation + }; + keys.push(newKey); + } + } + this._from = beginFrame; + this._to = endFrame; + return this; + }; + /** + * Start all animations on given targets + * @param loop defines if animations must loop + * @param speedRatio defines the ratio to apply to animation speed (1 by default) + * @param from defines the from key (optional) + * @param to defines the to key (optional) + * @returns the current animation group + */ + AnimationGroup.prototype.start = function (loop, speedRatio, from, to) { + var _this = this; + if (loop === void 0) { loop = false; } + if (speedRatio === void 0) { speedRatio = 1; } + if (this._isStarted || this._targetedAnimations.length === 0) { + return this; + } + this._loopAnimation = loop; + var _loop_1 = function (targetedAnimation) { + var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio); + animatable.onAnimationEnd = function () { + _this.onAnimationEndObservable.notifyObservers(targetedAnimation); + _this._checkAnimationGroupEnded(animatable); + }; + animatable.onAnimationLoop = function () { + _this.onAnimationLoopObservable.notifyObservers(targetedAnimation); + }; + this_1._animatables.push(animatable); + }; + var this_1 = this; + for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) { + var targetedAnimation = _a[_i]; + _loop_1(targetedAnimation); + } + this._speedRatio = speedRatio; + if (from !== undefined && to !== undefined) { + if (from < to && this._speedRatio < 0) { + var temp = to; + to = from; + from = temp; + } + else if (from > to && this._speedRatio > 0) { + this._speedRatio = -speedRatio; + } + } + this._isStarted = true; + this._isPaused = false; + this.onAnimationGroupPlayObservable.notifyObservers(this); + return this; + }; + /** + * Pause all animations + * @returns the animation group + */ + AnimationGroup.prototype.pause = function () { + if (!this._isStarted) { + return this; + } + this._isPaused = true; + for (var index = 0; index < this._animatables.length; index++) { + var animatable = this._animatables[index]; + animatable.pause(); + } + this.onAnimationGroupPauseObservable.notifyObservers(this); + return this; + }; + /** + * Play all animations to initial state + * This function will start() the animations if they were not started or will restart() them if they were paused + * @param loop defines if animations must loop + * @returns the animation group + */ + AnimationGroup.prototype.play = function (loop) { + // only if all animatables are ready and exist + if (this.isStarted && this._animatables.length === this._targetedAnimations.length) { + if (loop !== undefined) { + this.loopAnimation = loop; + } + this.restart(); + } + else { + this.stop(); + this.start(loop, this._speedRatio); + } + this._isPaused = false; + return this; + }; + /** + * Reset all animations to initial state + * @returns the animation group + */ + AnimationGroup.prototype.reset = function () { + if (!this._isStarted) { + return this; + } + for (var index = 0; index < this._animatables.length; index++) { + var animatable = this._animatables[index]; + animatable.reset(); + } + return this; + }; + /** + * Restart animations from key 0 + * @returns the animation group + */ + AnimationGroup.prototype.restart = function () { + if (!this._isStarted) { + return this; + } + for (var index = 0; index < this._animatables.length; index++) { + var animatable = this._animatables[index]; + animatable.restart(); + } + this.onAnimationGroupPlayObservable.notifyObservers(this); + return this; + }; + /** + * Stop all animations + * @returns the animation group + */ + AnimationGroup.prototype.stop = function () { + if (!this._isStarted) { + return this; + } + var list = this._animatables.slice(); + for (var index = 0; index < list.length; index++) { + list[index].stop(); + } + this._isStarted = false; + return this; + }; + /** + * Set animation weight for all animatables + * @param weight defines the weight to use + * @return the animationGroup + * @see http://doc.babylonjs.com/babylon101/animations#animation-weights + */ + AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) { + for (var index = 0; index < this._animatables.length; index++) { + var animatable = this._animatables[index]; + animatable.weight = weight; + } + return this; + }; + /** + * Synchronize and normalize all animatables with a source animatable + * @param root defines the root animatable to synchronize with + * @return the animationGroup + * @see http://doc.babylonjs.com/babylon101/animations#animation-weights + */ + AnimationGroup.prototype.syncAllAnimationsWith = function (root) { + for (var index = 0; index < this._animatables.length; index++) { + var animatable = this._animatables[index]; + animatable.syncWith(root); + } + return this; + }; + /** + * Goes to a specific frame in this animation group + * @param frame the frame number to go to + * @return the animationGroup + */ + AnimationGroup.prototype.goToFrame = function (frame) { + if (!this._isStarted) { + return this; + } + for (var index = 0; index < this._animatables.length; index++) { + var animatable = this._animatables[index]; + animatable.goToFrame(frame); + } + return this; + }; + /** + * Dispose all associated resources + */ + AnimationGroup.prototype.dispose = function () { + this._targetedAnimations = []; + this._animatables = []; + var index = this._scene.animationGroups.indexOf(this); + if (index > -1) { + this._scene.animationGroups.splice(index, 1); + } + this.onAnimationEndObservable.clear(); + this.onAnimationGroupEndObservable.clear(); + this.onAnimationGroupPauseObservable.clear(); + this.onAnimationGroupPlayObservable.clear(); + this.onAnimationLoopObservable.clear(); + }; + AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) { + // animatable should be taken out of the array + var idx = this._animatables.indexOf(animatable); + if (idx > -1) { + this._animatables.splice(idx, 1); + } + // all animatables were removed? animation group ended! + if (this._animatables.length === 0) { + this._isStarted = false; + this.onAnimationGroupEndObservable.notifyObservers(this); + } + }; + /** + * Clone the current animation group and returns a copy + * @param newName defines the name of the new group + * @param targetConverter defines an optional function used to convert current animation targets to new ones + * @returns the new aniamtion group + */ + AnimationGroup.prototype.clone = function (newName, targetConverter) { + var newGroup = new AnimationGroup(newName || this.name, this._scene); + for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) { + var targetAnimation = _a[_i]; + newGroup.addTargetedAnimation(targetAnimation.animation.clone(), targetConverter ? targetConverter(targetAnimation.target) : targetAnimation.target); + } + return newGroup; + }; + /** + * Serializes the animationGroup to an object + * @returns Serialized object + */ + AnimationGroup.prototype.serialize = function () { + var serializationObject = {}; + serializationObject.name = this.name; + serializationObject.from = this.from; + serializationObject.to = this.to; + serializationObject.targetedAnimations = []; + for (var targetedAnimationIndex = 0; targetedAnimationIndex < this.targetedAnimations.length; targetedAnimationIndex++) { + var targetedAnimation = this.targetedAnimations[targetedAnimationIndex]; + serializationObject.targetedAnimations[targetedAnimationIndex] = targetedAnimation.serialize(); + } + return serializationObject; + }; + // Statics + /** + * Returns a new AnimationGroup object parsed from the source provided. + * @param parsedAnimationGroup defines the source + * @param scene defines the scene that will receive the animationGroup + * @returns a new AnimationGroup + */ + AnimationGroup.Parse = function (parsedAnimationGroup, scene) { + var animationGroup = new AnimationGroup(parsedAnimationGroup.name, scene); + for (var i = 0; i < parsedAnimationGroup.targetedAnimations.length; i++) { + var targetedAnimation = parsedAnimationGroup.targetedAnimations[i]; + var animation = _animation__WEBPACK_IMPORTED_MODULE_0__["Animation"].Parse(targetedAnimation.animation); + var id = targetedAnimation.targetId; + if (targetedAnimation.animation.property === "influence") { // morph target animation + var morphTarget = scene.getMorphTargetById(id); + if (morphTarget) { + animationGroup.addTargetedAnimation(animation, morphTarget); + } + } + else { + var targetNode = scene.getNodeByID(id); + if (targetNode != null) { + animationGroup.addTargetedAnimation(animation, targetNode); + } + } + } + if (parsedAnimationGroup.from !== null && parsedAnimationGroup.from !== null) { + animationGroup.normalize(parsedAnimationGroup.from, parsedAnimationGroup.to); + } + return animationGroup; + }; + /** + * Returns the string "AnimationGroup" + * @returns "AnimationGroup" + */ + AnimationGroup.prototype.getClassName = function () { + return "AnimationGroup"; + }; + /** + * Creates a detailled string about the object + * @param fullDetails defines if the output string will support multiple levels of logging within scene loading + * @returns a string representing the object + */ + AnimationGroup.prototype.toString = function (fullDetails) { + var ret = "Name: " + this.name; + ret += ", type: " + this.getClassName(); + if (fullDetails) { + ret += ", from: " + this._from; + ret += ", to: " + this._to; + ret += ", isStarted: " + this._isStarted; + ret += ", speedRatio: " + this._speedRatio; + ret += ", targetedAnimations length: " + this._targetedAnimations.length; + ret += ", animatables length: " + this._animatables; + } + return ret; + }; + return AnimationGroup; +}()); + + + +/***/ }), + +/***/ "./Animations/animationKey.ts": +/*!************************************!*\ + !*** ./Animations/animationKey.ts ***! + \************************************/ +/*! exports provided: AnimationKeyInterpolation */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnimationKeyInterpolation", function() { return AnimationKeyInterpolation; }); +/** + * Enum for the animation key frame interpolation type + */ +var AnimationKeyInterpolation; +(function (AnimationKeyInterpolation) { + /** + * Do not interpolate between keys and use the start key value only. Tangents are ignored + */ + AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP"; +})(AnimationKeyInterpolation || (AnimationKeyInterpolation = {})); + + +/***/ }), + +/***/ "./Animations/animationPropertiesOverride.ts": +/*!***************************************************!*\ + !*** ./Animations/animationPropertiesOverride.ts ***! + \***************************************************/ +/*! exports provided: AnimationPropertiesOverride */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnimationPropertiesOverride", function() { return AnimationPropertiesOverride; }); +/* harmony import */ var _Animations_animation__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Animations/animation */ "./Animations/animation.ts"); + +/** + * Class used to override all child animations of a given target + */ +var AnimationPropertiesOverride = /** @class */ (function () { + function AnimationPropertiesOverride() { + /** + * Gets or sets a value indicating if animation blending must be used + */ + this.enableBlending = false; + /** + * Gets or sets the blending speed to use when enableBlending is true + */ + this.blendingSpeed = 0.01; + /** + * Gets or sets the default loop mode to use + */ + this.loopMode = _Animations_animation__WEBPACK_IMPORTED_MODULE_0__["Animation"].ANIMATIONLOOPMODE_CYCLE; + } + return AnimationPropertiesOverride; +}()); + + + +/***/ }), + +/***/ "./Animations/animationRange.ts": +/*!**************************************!*\ + !*** ./Animations/animationRange.ts ***! + \**************************************/ +/*! exports provided: AnimationRange */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnimationRange", function() { return AnimationRange; }); +/** + * Represents the range of an animation + */ +var AnimationRange = /** @class */ (function () { + /** + * Initializes the range of an animation + * @param name The name of the animation range + * @param from The starting frame of the animation + * @param to The ending frame of the animation + */ + function AnimationRange( + /**The name of the animation range**/ + name, + /**The starting frame of the animation */ + from, + /**The ending frame of the animation*/ + to) { + this.name = name; + this.from = from; + this.to = to; + } + /** + * Makes a copy of the animation range + * @returns A copy of the animation range + */ + AnimationRange.prototype.clone = function () { + return new AnimationRange(this.name, this.from, this.to); + }; + return AnimationRange; +}()); + + + +/***/ }), + +/***/ "./Animations/easing.ts": +/*!******************************!*\ + !*** ./Animations/easing.ts ***! + \******************************/ +/*! exports provided: EasingFunction, CircleEase, BackEase, BounceEase, CubicEase, ElasticEase, ExponentialEase, PowerEase, QuadraticEase, QuarticEase, QuinticEase, SineEase, BezierCurveEase */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EasingFunction", function() { return EasingFunction; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CircleEase", function() { return CircleEase; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BackEase", function() { return BackEase; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BounceEase", function() { return BounceEase; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CubicEase", function() { return CubicEase; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ElasticEase", function() { return ElasticEase; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ExponentialEase", function() { return ExponentialEase; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PowerEase", function() { return PowerEase; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "QuadraticEase", function() { return QuadraticEase; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "QuarticEase", function() { return QuarticEase; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "QuinticEase", function() { return QuinticEase; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SineEase", function() { return SineEase; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BezierCurveEase", function() { return BezierCurveEase; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); + + +/** + * Base class used for every default easing function. + * @see http://doc.babylonjs.com/babylon101/animations#easing-functions + */ +var EasingFunction = /** @class */ (function () { + function EasingFunction() { + this._easingMode = EasingFunction.EASINGMODE_EASEIN; + } + /** + * Sets the easing mode of the current function. + * @param easingMode Defines the willing mode (EASINGMODE_EASEIN, EASINGMODE_EASEOUT or EASINGMODE_EASEINOUT) + */ + EasingFunction.prototype.setEasingMode = function (easingMode) { + var n = Math.min(Math.max(easingMode, 0), 2); + this._easingMode = n; + }; + /** + * Gets the current easing mode. + * @returns the easing mode + */ + EasingFunction.prototype.getEasingMode = function () { + return this._easingMode; + }; + /** + * @hidden + */ + EasingFunction.prototype.easeInCore = function (gradient) { + throw new Error('You must implement this method'); + }; + /** + * Given an input gradient between 0 and 1, this returns the corrseponding value + * of the easing function. + * @param gradient Defines the value between 0 and 1 we want the easing value for + * @returns the corresponding value on the curve defined by the easing function + */ + EasingFunction.prototype.ease = function (gradient) { + switch (this._easingMode) { + case EasingFunction.EASINGMODE_EASEIN: + return this.easeInCore(gradient); + case EasingFunction.EASINGMODE_EASEOUT: + return (1 - this.easeInCore(1 - gradient)); + } + if (gradient >= 0.5) { + return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5); + } + return (this.easeInCore(gradient * 2) * 0.5); + }; + /** + * Interpolation follows the mathematical formula associated with the easing function. + */ + EasingFunction.EASINGMODE_EASEIN = 0; + /** + * Interpolation follows 100% interpolation minus the output of the formula associated with the easing function. + */ + EasingFunction.EASINGMODE_EASEOUT = 1; + /** + * Interpolation uses EaseIn for the first half of the animation and EaseOut for the second half. + */ + EasingFunction.EASINGMODE_EASEINOUT = 2; + return EasingFunction; +}()); + +/** + * Easing function with a circle shape (see link below). + * @see https://easings.net/#easeInCirc + * @see http://doc.babylonjs.com/babylon101/animations#easing-functions + */ +var CircleEase = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](CircleEase, _super); + function CircleEase() { + return _super !== null && _super.apply(this, arguments) || this; + } + /** @hidden */ + CircleEase.prototype.easeInCore = function (gradient) { + gradient = Math.max(0, Math.min(1, gradient)); + return (1.0 - Math.sqrt(1.0 - (gradient * gradient))); + }; + return CircleEase; +}(EasingFunction)); + +/** + * Easing function with a ease back shape (see link below). + * @see https://easings.net/#easeInBack + * @see http://doc.babylonjs.com/babylon101/animations#easing-functions + */ +var BackEase = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](BackEase, _super); + /** + * Instantiates a back ease easing + * @see https://easings.net/#easeInBack + * @param amplitude Defines the amplitude of the function + */ + function BackEase( + /** Defines the amplitude of the function */ + amplitude) { + if (amplitude === void 0) { amplitude = 1; } + var _this = _super.call(this) || this; + _this.amplitude = amplitude; + return _this; + } + /** @hidden */ + BackEase.prototype.easeInCore = function (gradient) { + var num = Math.max(0, this.amplitude); + return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient))); + }; + return BackEase; +}(EasingFunction)); + +/** + * Easing function with a bouncing shape (see link below). + * @see https://easings.net/#easeInBounce + * @see http://doc.babylonjs.com/babylon101/animations#easing-functions + */ +var BounceEase = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](BounceEase, _super); + /** + * Instantiates a bounce easing + * @see https://easings.net/#easeInBounce + * @param bounces Defines the number of bounces + * @param bounciness Defines the amplitude of the bounce + */ + function BounceEase( + /** Defines the number of bounces */ + bounces, + /** Defines the amplitude of the bounce */ + bounciness) { + if (bounces === void 0) { bounces = 3; } + if (bounciness === void 0) { bounciness = 2; } + var _this = _super.call(this) || this; + _this.bounces = bounces; + _this.bounciness = bounciness; + return _this; + } + /** @hidden */ + BounceEase.prototype.easeInCore = function (gradient) { + var y = Math.max(0.0, this.bounces); + var bounciness = this.bounciness; + if (bounciness <= 1.0) { + bounciness = 1.001; + } + var num9 = Math.pow(bounciness, y); + var num5 = 1.0 - bounciness; + var num4 = ((1.0 - num9) / num5) + (num9 * 0.5); + var num15 = gradient * num4; + var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness); + var num3 = Math.floor(num65); + var num13 = num3 + 1.0; + var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4); + var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4); + var num7 = (num8 + num12) * 0.5; + var num6 = gradient - num7; + var num2 = num7 - num8; + return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2)); + }; + return BounceEase; +}(EasingFunction)); + +/** + * Easing function with a power of 3 shape (see link below). + * @see https://easings.net/#easeInCubic + * @see http://doc.babylonjs.com/babylon101/animations#easing-functions + */ +var CubicEase = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](CubicEase, _super); + function CubicEase() { + return _super !== null && _super.apply(this, arguments) || this; + } + /** @hidden */ + CubicEase.prototype.easeInCore = function (gradient) { + return (gradient * gradient * gradient); + }; + return CubicEase; +}(EasingFunction)); + +/** + * Easing function with an elastic shape (see link below). + * @see https://easings.net/#easeInElastic + * @see http://doc.babylonjs.com/babylon101/animations#easing-functions + */ +var ElasticEase = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ElasticEase, _super); + /** + * Instantiates an elastic easing function + * @see https://easings.net/#easeInElastic + * @param oscillations Defines the number of oscillations + * @param springiness Defines the amplitude of the oscillations + */ + function ElasticEase( + /** Defines the number of oscillations*/ + oscillations, + /** Defines the amplitude of the oscillations*/ + springiness) { + if (oscillations === void 0) { oscillations = 3; } + if (springiness === void 0) { springiness = 3; } + var _this = _super.call(this) || this; + _this.oscillations = oscillations; + _this.springiness = springiness; + return _this; + } + /** @hidden */ + ElasticEase.prototype.easeInCore = function (gradient) { + var num2; + var num3 = Math.max(0.0, this.oscillations); + var num = Math.max(0.0, this.springiness); + if (num == 0) { + num2 = gradient; + } + else { + num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0); + } + return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient)); + }; + return ElasticEase; +}(EasingFunction)); + +/** + * Easing function with an exponential shape (see link below). + * @see https://easings.net/#easeInExpo + * @see http://doc.babylonjs.com/babylon101/animations#easing-functions + */ +var ExponentialEase = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ExponentialEase, _super); + /** + * Instantiates an exponential easing function + * @see https://easings.net/#easeInExpo + * @param exponent Defines the exponent of the function + */ + function ExponentialEase( + /** Defines the exponent of the function */ + exponent) { + if (exponent === void 0) { exponent = 2; } + var _this = _super.call(this) || this; + _this.exponent = exponent; + return _this; + } + /** @hidden */ + ExponentialEase.prototype.easeInCore = function (gradient) { + if (this.exponent <= 0) { + return gradient; + } + return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0)); + }; + return ExponentialEase; +}(EasingFunction)); + +/** + * Easing function with a power shape (see link below). + * @see https://easings.net/#easeInQuad + * @see http://doc.babylonjs.com/babylon101/animations#easing-functions + */ +var PowerEase = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PowerEase, _super); + /** + * Instantiates an power base easing function + * @see https://easings.net/#easeInQuad + * @param power Defines the power of the function + */ + function PowerEase( + /** Defines the power of the function */ + power) { + if (power === void 0) { power = 2; } + var _this = _super.call(this) || this; + _this.power = power; + return _this; + } + /** @hidden */ + PowerEase.prototype.easeInCore = function (gradient) { + var y = Math.max(0.0, this.power); + return Math.pow(gradient, y); + }; + return PowerEase; +}(EasingFunction)); + +/** + * Easing function with a power of 2 shape (see link below). + * @see https://easings.net/#easeInQuad + * @see http://doc.babylonjs.com/babylon101/animations#easing-functions + */ +var QuadraticEase = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](QuadraticEase, _super); + function QuadraticEase() { + return _super !== null && _super.apply(this, arguments) || this; + } + /** @hidden */ + QuadraticEase.prototype.easeInCore = function (gradient) { + return (gradient * gradient); + }; + return QuadraticEase; +}(EasingFunction)); + +/** + * Easing function with a power of 4 shape (see link below). + * @see https://easings.net/#easeInQuart + * @see http://doc.babylonjs.com/babylon101/animations#easing-functions + */ +var QuarticEase = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](QuarticEase, _super); + function QuarticEase() { + return _super !== null && _super.apply(this, arguments) || this; + } + /** @hidden */ + QuarticEase.prototype.easeInCore = function (gradient) { + return (gradient * gradient * gradient * gradient); + }; + return QuarticEase; +}(EasingFunction)); + +/** + * Easing function with a power of 5 shape (see link below). + * @see https://easings.net/#easeInQuint + * @see http://doc.babylonjs.com/babylon101/animations#easing-functions + */ +var QuinticEase = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](QuinticEase, _super); + function QuinticEase() { + return _super !== null && _super.apply(this, arguments) || this; + } + /** @hidden */ + QuinticEase.prototype.easeInCore = function (gradient) { + return (gradient * gradient * gradient * gradient * gradient); + }; + return QuinticEase; +}(EasingFunction)); + +/** + * Easing function with a sin shape (see link below). + * @see https://easings.net/#easeInSine + * @see http://doc.babylonjs.com/babylon101/animations#easing-functions + */ +var SineEase = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SineEase, _super); + function SineEase() { + return _super !== null && _super.apply(this, arguments) || this; + } + /** @hidden */ + SineEase.prototype.easeInCore = function (gradient) { + return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient))); + }; + return SineEase; +}(EasingFunction)); + +/** + * Easing function with a bezier shape (see link below). + * @see http://cubic-bezier.com/#.17,.67,.83,.67 + * @see http://doc.babylonjs.com/babylon101/animations#easing-functions + */ +var BezierCurveEase = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](BezierCurveEase, _super); + /** + * Instantiates a bezier function + * @see http://cubic-bezier.com/#.17,.67,.83,.67 + * @param x1 Defines the x component of the start tangent in the bezier curve + * @param y1 Defines the y component of the start tangent in the bezier curve + * @param x2 Defines the x component of the end tangent in the bezier curve + * @param y2 Defines the y component of the end tangent in the bezier curve + */ + function BezierCurveEase( + /** Defines the x component of the start tangent in the bezier curve */ + x1, + /** Defines the y component of the start tangent in the bezier curve */ + y1, + /** Defines the x component of the end tangent in the bezier curve */ + x2, + /** Defines the y component of the end tangent in the bezier curve */ + y2) { + if (x1 === void 0) { x1 = 0; } + if (y1 === void 0) { y1 = 0; } + if (x2 === void 0) { x2 = 1; } + if (y2 === void 0) { y2 = 1; } + var _this = _super.call(this) || this; + _this.x1 = x1; + _this.y1 = y1; + _this.x2 = x2; + _this.y2 = y2; + return _this; + } + /** @hidden */ + BezierCurveEase.prototype.easeInCore = function (gradient) { + return _Maths_math__WEBPACK_IMPORTED_MODULE_1__["BezierCurve"].Interpolate(gradient, this.x1, this.y1, this.x2, this.y2); + }; + return BezierCurveEase; +}(EasingFunction)); + + + +/***/ }), + +/***/ "./Animations/index.ts": +/*!*****************************!*\ + !*** ./Animations/index.ts ***! + \*****************************/ +/*! exports provided: Animatable, _IAnimationState, Animation, TargetedAnimation, AnimationGroup, AnimationPropertiesOverride, EasingFunction, CircleEase, BackEase, BounceEase, CubicEase, ElasticEase, ExponentialEase, PowerEase, QuadraticEase, QuarticEase, QuinticEase, SineEase, BezierCurveEase, RuntimeAnimation, AnimationEvent, AnimationKeyInterpolation, AnimationRange */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _animatable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./animatable */ "./Animations/animatable.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Animatable", function() { return _animatable__WEBPACK_IMPORTED_MODULE_0__["Animatable"]; }); + +/* harmony import */ var _animation__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./animation */ "./Animations/animation.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_IAnimationState", function() { return _animation__WEBPACK_IMPORTED_MODULE_1__["_IAnimationState"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Animation", function() { return _animation__WEBPACK_IMPORTED_MODULE_1__["Animation"]; }); + +/* harmony import */ var _animationGroup__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./animationGroup */ "./Animations/animationGroup.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TargetedAnimation", function() { return _animationGroup__WEBPACK_IMPORTED_MODULE_2__["TargetedAnimation"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnimationGroup", function() { return _animationGroup__WEBPACK_IMPORTED_MODULE_2__["AnimationGroup"]; }); + +/* harmony import */ var _animationPropertiesOverride__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./animationPropertiesOverride */ "./Animations/animationPropertiesOverride.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnimationPropertiesOverride", function() { return _animationPropertiesOverride__WEBPACK_IMPORTED_MODULE_3__["AnimationPropertiesOverride"]; }); + +/* harmony import */ var _easing__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./easing */ "./Animations/easing.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EasingFunction", function() { return _easing__WEBPACK_IMPORTED_MODULE_4__["EasingFunction"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CircleEase", function() { return _easing__WEBPACK_IMPORTED_MODULE_4__["CircleEase"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BackEase", function() { return _easing__WEBPACK_IMPORTED_MODULE_4__["BackEase"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BounceEase", function() { return _easing__WEBPACK_IMPORTED_MODULE_4__["BounceEase"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CubicEase", function() { return _easing__WEBPACK_IMPORTED_MODULE_4__["CubicEase"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ElasticEase", function() { return _easing__WEBPACK_IMPORTED_MODULE_4__["ElasticEase"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ExponentialEase", function() { return _easing__WEBPACK_IMPORTED_MODULE_4__["ExponentialEase"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PowerEase", function() { return _easing__WEBPACK_IMPORTED_MODULE_4__["PowerEase"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "QuadraticEase", function() { return _easing__WEBPACK_IMPORTED_MODULE_4__["QuadraticEase"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "QuarticEase", function() { return _easing__WEBPACK_IMPORTED_MODULE_4__["QuarticEase"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "QuinticEase", function() { return _easing__WEBPACK_IMPORTED_MODULE_4__["QuinticEase"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SineEase", function() { return _easing__WEBPACK_IMPORTED_MODULE_4__["SineEase"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BezierCurveEase", function() { return _easing__WEBPACK_IMPORTED_MODULE_4__["BezierCurveEase"]; }); + +/* harmony import */ var _runtimeAnimation__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./runtimeAnimation */ "./Animations/runtimeAnimation.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RuntimeAnimation", function() { return _runtimeAnimation__WEBPACK_IMPORTED_MODULE_5__["RuntimeAnimation"]; }); + +/* harmony import */ var _animationEvent__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./animationEvent */ "./Animations/animationEvent.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnimationEvent", function() { return _animationEvent__WEBPACK_IMPORTED_MODULE_6__["AnimationEvent"]; }); + +/* empty/unused harmony star reexport *//* harmony import */ var _animationKey__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./animationKey */ "./Animations/animationKey.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnimationKeyInterpolation", function() { return _animationKey__WEBPACK_IMPORTED_MODULE_7__["AnimationKeyInterpolation"]; }); + +/* harmony import */ var _animationRange__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./animationRange */ "./Animations/animationRange.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnimationRange", function() { return _animationRange__WEBPACK_IMPORTED_MODULE_8__["AnimationRange"]; }); + + + + + + + + + + + + + +/***/ }), + +/***/ "./Animations/runtimeAnimation.ts": +/*!****************************************!*\ + !*** ./Animations/runtimeAnimation.ts ***! + \****************************************/ +/*! exports provided: RuntimeAnimation */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RuntimeAnimation", function() { return RuntimeAnimation; }); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _animation__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./animation */ "./Animations/animation.ts"); + + +// Static values to help the garbage collector +// Quaternion +var _staticOffsetValueQuaternion = Object.freeze(new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"](0, 0, 0, 0)); +// Vector3 +var _staticOffsetValueVector3 = Object.freeze(_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero()); +// Vector2 +var _staticOffsetValueVector2 = Object.freeze(_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector2"].Zero()); +// Size +var _staticOffsetValueSize = Object.freeze(_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Size"].Zero()); +// Color3 +var _staticOffsetValueColor3 = Object.freeze(_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Color3"].Black()); +/** + * Defines a runtime animation + */ +var RuntimeAnimation = /** @class */ (function () { + /** + * Create a new RuntimeAnimation object + * @param target defines the target of the animation + * @param animation defines the source animation object + * @param scene defines the hosting scene + * @param host defines the initiating Animatable + */ + function RuntimeAnimation(target, animation, scene, host) { + var _this = this; + this._events = new Array(); + /** + * The current frame of the runtime animation + */ + this._currentFrame = 0; + /** + * The original value of the runtime animation + */ + this._originalValue = new Array(); + /** + * The original blend value of the runtime animation + */ + this._originalBlendValue = null; + /** + * The offsets cache of the runtime animation + */ + this._offsetsCache = {}; + /** + * The high limits cache of the runtime animation + */ + this._highLimitsCache = {}; + /** + * Specifies if the runtime animation has been stopped + */ + this._stopped = false; + /** + * The blending factor of the runtime animation + */ + this._blendingFactor = 0; + /** + * The current value of the runtime animation + */ + this._currentValue = null; + this._currentActiveTarget = null; + this._directTarget = null; + /** + * The target path of the runtime animation + */ + this._targetPath = ""; + /** + * The weight of the runtime animation + */ + this._weight = 1.0; + /** + * The ratio offset of the runtime animation + */ + this._ratioOffset = 0; + /** + * The previous delay of the runtime animation + */ + this._previousDelay = 0; + /** + * The previous ratio of the runtime animation + */ + this._previousRatio = 0; + this._targetIsArray = false; + this._animation = animation; + this._target = target; + this._scene = scene; + this._host = host; + this._activeTargets = []; + animation._runtimeAnimations.push(this); + // State + this._animationState = { + key: 0, + repeatCount: 0, + loopMode: this._getCorrectLoopMode() + }; + if (this._animation.dataType === _animation__WEBPACK_IMPORTED_MODULE_1__["Animation"].ANIMATIONTYPE_MATRIX) { + this._animationState.workValue = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].Zero(); + } + // Limits + this._keys = this._animation.getKeys(); + this._minFrame = this._keys[0].frame; + this._maxFrame = this._keys[this._keys.length - 1].frame; + this._minValue = this._keys[0].value; + this._maxValue = this._keys[this._keys.length - 1].value; + // Add a start key at frame 0 if missing + if (this._minFrame !== 0) { + var newKey = { frame: 0, value: this._minValue }; + this._keys.splice(0, 0, newKey); + } + // Check data + if (this._target instanceof Array) { + var index = 0; + for (var _i = 0, _a = this._target; _i < _a.length; _i++) { + var target_1 = _a[_i]; + this._preparePath(target_1, index); + this._getOriginalValues(index); + index++; + } + this._targetIsArray = true; + } + else { + this._preparePath(this._target); + this._getOriginalValues(); + this._targetIsArray = false; + this._directTarget = this._activeTargets[0]; + } + // Cloning events locally + var events = animation.getEvents(); + if (events && events.length > 0) { + events.forEach(function (e) { + _this._events.push(e._clone()); + }); + } + this._enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending; + } + Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", { + /** + * Gets the current frame of the runtime animation + */ + get: function () { + return this._currentFrame; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(RuntimeAnimation.prototype, "weight", { + /** + * Gets the weight of the runtime animation + */ + get: function () { + return this._weight; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(RuntimeAnimation.prototype, "currentValue", { + /** + * Gets the current value of the runtime animation + */ + get: function () { + return this._currentValue; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(RuntimeAnimation.prototype, "targetPath", { + /** + * Gets the target path of the runtime animation + */ + get: function () { + return this._targetPath; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(RuntimeAnimation.prototype, "target", { + /** + * Gets the actual target of the runtime animation + */ + get: function () { + return this._currentActiveTarget; + }, + enumerable: true, + configurable: true + }); + RuntimeAnimation.prototype._preparePath = function (target, targetIndex) { + if (targetIndex === void 0) { targetIndex = 0; } + var targetPropertyPath = this._animation.targetPropertyPath; + if (targetPropertyPath.length > 1) { + var property = target[targetPropertyPath[0]]; + for (var index = 1; index < targetPropertyPath.length - 1; index++) { + property = property[targetPropertyPath[index]]; + } + this._targetPath = targetPropertyPath[targetPropertyPath.length - 1]; + this._activeTargets[targetIndex] = property; + } + else { + this._targetPath = targetPropertyPath[0]; + this._activeTargets[targetIndex] = target; + } + }; + Object.defineProperty(RuntimeAnimation.prototype, "animation", { + /** + * Gets the animation from the runtime animation + */ + get: function () { + return this._animation; + }, + enumerable: true, + configurable: true + }); + /** + * Resets the runtime animation to the beginning + * @param restoreOriginal defines whether to restore the target property to the original value + */ + RuntimeAnimation.prototype.reset = function (restoreOriginal) { + if (restoreOriginal === void 0) { restoreOriginal = false; } + if (restoreOriginal) { + if (this._target instanceof Array) { + var index = 0; + for (var _i = 0, _a = this._target; _i < _a.length; _i++) { + var target = _a[_i]; + if (this._originalValue[index] !== undefined) { + this._setValue(target, this._activeTargets[index], this._originalValue[index], -1, index); + } + index++; + } + } + else { + if (this._originalValue[0] !== undefined) { + this._setValue(this._target, this._directTarget, this._originalValue[0], -1, 0); + } + } + } + this._offsetsCache = {}; + this._highLimitsCache = {}; + this._currentFrame = 0; + this._blendingFactor = 0; + // Events + for (var index = 0; index < this._events.length; index++) { + this._events[index].isDone = false; + } + }; + /** + * Specifies if the runtime animation is stopped + * @returns Boolean specifying if the runtime animation is stopped + */ + RuntimeAnimation.prototype.isStopped = function () { + return this._stopped; + }; + /** + * Disposes of the runtime animation + */ + RuntimeAnimation.prototype.dispose = function () { + var index = this._animation.runtimeAnimations.indexOf(this); + if (index > -1) { + this._animation.runtimeAnimations.splice(index, 1); + } + }; + /** + * Apply the interpolated value to the target + * @param currentValue defines the value computed by the animation + * @param weight defines the weight to apply to this value (Defaults to 1.0) + */ + RuntimeAnimation.prototype.setValue = function (currentValue, weight) { + if (this._targetIsArray) { + for (var index = 0; index < this._target.length; index++) { + var target = this._target[index]; + this._setValue(target, this._activeTargets[index], currentValue, weight, index); + } + return; + } + this._setValue(this._target, this._directTarget, currentValue, weight, 0); + }; + RuntimeAnimation.prototype._getOriginalValues = function (targetIndex) { + if (targetIndex === void 0) { targetIndex = 0; } + var originalValue; + var target = this._activeTargets[targetIndex]; + if (target.getRestPose && this._targetPath === "_matrix") { // For bones + originalValue = target.getRestPose(); + } + else { + originalValue = target[this._targetPath]; + } + if (originalValue && originalValue.clone) { + this._originalValue[targetIndex] = originalValue.clone(); + } + else { + this._originalValue[targetIndex] = originalValue; + } + }; + RuntimeAnimation.prototype._setValue = function (target, destination, currentValue, weight, targetIndex) { + // Set value + this._currentActiveTarget = destination; + this._weight = weight; + if (this._enableBlending && this._blendingFactor <= 1.0) { + if (!this._originalBlendValue) { + var originalValue = destination[this._targetPath]; + if (originalValue.clone) { + this._originalBlendValue = originalValue.clone(); + } + else { + this._originalBlendValue = originalValue; + } + } + if (this._originalBlendValue.m) { // Matrix + if (_animation__WEBPACK_IMPORTED_MODULE_1__["Animation"].AllowMatrixDecomposeForInterpolation) { + if (this._currentValue) { + _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue); + } + else { + this._currentValue = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor); + } + } + else { + if (this._currentValue) { + _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue); + } + else { + this._currentValue = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].Lerp(this._originalBlendValue, currentValue, this._blendingFactor); + } + } + } + else { + this._currentValue = _animation__WEBPACK_IMPORTED_MODULE_1__["Animation"]._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor); + } + var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed; + this._blendingFactor += blendingSpeed; + } + else { + this._currentValue = currentValue; + } + if (weight !== -1.0) { + this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]); + } + else { + destination[this._targetPath] = this._currentValue; + } + if (target.markAsDirty) { + target.markAsDirty(this._animation.targetProperty); + } + }; + /** + * Gets the loop pmode of the runtime animation + * @returns Loop Mode + */ + RuntimeAnimation.prototype._getCorrectLoopMode = function () { + if (this._target && this._target.animationPropertiesOverride) { + return this._target.animationPropertiesOverride.loopMode; + } + return this._animation.loopMode; + }; + /** + * Move the current animation to a given frame + * @param frame defines the frame to move to + */ + RuntimeAnimation.prototype.goToFrame = function (frame) { + var keys = this._animation.getKeys(); + if (frame < keys[0].frame) { + frame = keys[0].frame; + } + else if (frame > keys[keys.length - 1].frame) { + frame = keys[keys.length - 1].frame; + } + // Need to reset animation events + var events = this._events; + if (events.length) { + for (var index = 0; index < events.length; index++) { + if (!events[index].onlyOnce) { + // reset events in the future + events[index].isDone = events[index].frame < frame; + } + } + } + this._currentFrame = frame; + var currentValue = this._animation._interpolate(frame, this._animationState); + this.setValue(currentValue, -1); + }; + /** + * @hidden Internal use only + */ + RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) { + var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0; + this._ratioOffset = this._previousRatio - newRatio; + }; + /** + * Execute the current animation + * @param delay defines the delay to add to the current frame + * @param from defines the lower bound of the animation range + * @param to defines the upper bound of the animation range + * @param loop defines if the current animation must loop + * @param speedRatio defines the current speed ratio + * @param weight defines the weight of the animation (default is -1 so no weight) + * @param onLoop optional callback called when animation loops + * @returns a boolean indicating if the animation is running + */ + RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) { + if (weight === void 0) { weight = -1.0; } + var animation = this._animation; + var targetPropertyPath = animation.targetPropertyPath; + if (!targetPropertyPath || targetPropertyPath.length < 1) { + this._stopped = true; + return false; + } + var returnValue = true; + // Check limits + if (from < this._minFrame || from > this._maxFrame) { + from = this._minFrame; + } + if (to < this._minFrame || to > this._maxFrame) { + to = this._maxFrame; + } + var range = to - from; + var offsetValue; + // Compute ratio which represents the frame delta between from and to + var ratio = (delay * (animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset; + var highLimitValue = 0; + this._previousDelay = delay; + this._previousRatio = ratio; + if (!loop && (to >= from && ratio >= range)) { // If we are out of range and not looping get back to caller + returnValue = false; + highLimitValue = animation._getKeyValue(this._maxValue); + } + else if (!loop && (from >= to && ratio <= range)) { + returnValue = false; + highLimitValue = animation._getKeyValue(this._minValue); + } + else if (this._animationState.loopMode !== _animation__WEBPACK_IMPORTED_MODULE_1__["Animation"].ANIMATIONLOOPMODE_CYCLE) { + var keyOffset = to.toString() + from.toString(); + if (!this._offsetsCache[keyOffset]) { + this._animationState.repeatCount = 0; + this._animationState.loopMode = _animation__WEBPACK_IMPORTED_MODULE_1__["Animation"].ANIMATIONLOOPMODE_CYCLE; + var fromValue = animation._interpolate(from, this._animationState); + var toValue = animation._interpolate(to, this._animationState); + this._animationState.loopMode = this._getCorrectLoopMode(); + switch (animation.dataType) { + // Float + case _animation__WEBPACK_IMPORTED_MODULE_1__["Animation"].ANIMATIONTYPE_FLOAT: + this._offsetsCache[keyOffset] = toValue - fromValue; + break; + // Quaternion + case _animation__WEBPACK_IMPORTED_MODULE_1__["Animation"].ANIMATIONTYPE_QUATERNION: + this._offsetsCache[keyOffset] = toValue.subtract(fromValue); + break; + // Vector3 + case _animation__WEBPACK_IMPORTED_MODULE_1__["Animation"].ANIMATIONTYPE_VECTOR3: + this._offsetsCache[keyOffset] = toValue.subtract(fromValue); + // Vector2 + case _animation__WEBPACK_IMPORTED_MODULE_1__["Animation"].ANIMATIONTYPE_VECTOR2: + this._offsetsCache[keyOffset] = toValue.subtract(fromValue); + // Size + case _animation__WEBPACK_IMPORTED_MODULE_1__["Animation"].ANIMATIONTYPE_SIZE: + this._offsetsCache[keyOffset] = toValue.subtract(fromValue); + // Color3 + case _animation__WEBPACK_IMPORTED_MODULE_1__["Animation"].ANIMATIONTYPE_COLOR3: + this._offsetsCache[keyOffset] = toValue.subtract(fromValue); + default: + break; + } + this._highLimitsCache[keyOffset] = toValue; + } + highLimitValue = this._highLimitsCache[keyOffset]; + offsetValue = this._offsetsCache[keyOffset]; + } + if (offsetValue === undefined) { + switch (animation.dataType) { + // Float + case _animation__WEBPACK_IMPORTED_MODULE_1__["Animation"].ANIMATIONTYPE_FLOAT: + offsetValue = 0; + break; + // Quaternion + case _animation__WEBPACK_IMPORTED_MODULE_1__["Animation"].ANIMATIONTYPE_QUATERNION: + offsetValue = _staticOffsetValueQuaternion; + break; + // Vector3 + case _animation__WEBPACK_IMPORTED_MODULE_1__["Animation"].ANIMATIONTYPE_VECTOR3: + offsetValue = _staticOffsetValueVector3; + break; + // Vector2 + case _animation__WEBPACK_IMPORTED_MODULE_1__["Animation"].ANIMATIONTYPE_VECTOR2: + offsetValue = _staticOffsetValueVector2; + break; + // Size + case _animation__WEBPACK_IMPORTED_MODULE_1__["Animation"].ANIMATIONTYPE_SIZE: + offsetValue = _staticOffsetValueSize; + break; + // Color3 + case _animation__WEBPACK_IMPORTED_MODULE_1__["Animation"].ANIMATIONTYPE_COLOR3: + offsetValue = _staticOffsetValueColor3; + } + } + // Compute value + var currentFrame; + if (this._host && this._host.syncRoot) { + var syncRoot = this._host.syncRoot; + var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame); + currentFrame = from + (to - from) * hostNormalizedFrame; + } + else { + currentFrame = (returnValue && range !== 0) ? from + ratio % range : to; + } + // Reset events if looping + var events = this._events; + if (range > 0 && this.currentFrame > currentFrame || + range < 0 && this.currentFrame < currentFrame) { + this._onLoop(); + // Need to reset animation events + if (events.length) { + for (var index = 0; index < events.length; index++) { + if (!events[index].onlyOnce) { + // reset event, the animation is looping + events[index].isDone = false; + } + } + } + } + this._currentFrame = currentFrame; + this._animationState.repeatCount = range === 0 ? 0 : (ratio / range) >> 0; + this._animationState.highLimitValue = highLimitValue; + this._animationState.offsetValue = offsetValue; + var currentValue = animation._interpolate(currentFrame, this._animationState); + // Set value + this.setValue(currentValue, weight); + // Check events + if (events.length) { + for (var index = 0; index < events.length; index++) { + // Make sure current frame has passed event frame and that event frame is within the current range + // Also, handle both forward and reverse animations + if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) || + (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) { + var event = events[index]; + if (!event.isDone) { + // If event should be done only once, remove it. + if (event.onlyOnce) { + events.splice(index, 1); + index--; + } + event.isDone = true; + event.action(currentFrame); + } // Don't do anything if the event has already be done. + } + } + } + if (!returnValue) { + this._stopped = true; + } + return returnValue; + }; + return RuntimeAnimation; +}()); + + + +/***/ }), + +/***/ "./Audio/analyser.ts": +/*!***************************!*\ + !*** ./Audio/analyser.ts ***! + \***************************/ +/*! exports provided: Analyser */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Analyser", function() { return Analyser; }); +/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Engines/engine */ "./Engines/engine.ts"); + +/** + * Class used to work with sound analyzer using fast fourier transform (FFT) + * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music + */ +var Analyser = /** @class */ (function () { + /** + * Creates a new analyser + * @param scene defines hosting scene + */ + function Analyser(scene) { + /** + * Gets or sets the smoothing + * @ignorenaming + */ + this.SMOOTHING = 0.75; + /** + * Gets or sets the FFT table size + * @ignorenaming + */ + this.FFT_SIZE = 512; + /** + * Gets or sets the bar graph amplitude + * @ignorenaming + */ + this.BARGRAPHAMPLITUDE = 256; + /** + * Gets or sets the position of the debug canvas + * @ignorenaming + */ + this.DEBUGCANVASPOS = { x: 20, y: 20 }; + /** + * Gets or sets the debug canvas size + * @ignorenaming + */ + this.DEBUGCANVASSIZE = { width: 320, height: 200 }; + this._scene = scene; + this._audioEngine = _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].audioEngine; + if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) { + this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser(); + this._webAudioAnalyser.minDecibels = -140; + this._webAudioAnalyser.maxDecibels = 0; + this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount); + this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount); + this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount); + } + } + /** + * Get the number of data values you will have to play with for the visualization + * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount + * @returns a number + */ + Analyser.prototype.getFrequencyBinCount = function () { + if (this._audioEngine.canUseWebAudio) { + return this._webAudioAnalyser.frequencyBinCount; + } + else { + return 0; + } + }; + /** + * Gets the current frequency data as a byte array + * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData + * @returns a Uint8Array + */ + Analyser.prototype.getByteFrequencyData = function () { + if (this._audioEngine.canUseWebAudio) { + this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING; + this._webAudioAnalyser.fftSize = this.FFT_SIZE; + this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs); + } + return this._byteFreqs; + }; + /** + * Gets the current waveform as a byte array + * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData + * @returns a Uint8Array + */ + Analyser.prototype.getByteTimeDomainData = function () { + if (this._audioEngine.canUseWebAudio) { + this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING; + this._webAudioAnalyser.fftSize = this.FFT_SIZE; + this._webAudioAnalyser.getByteTimeDomainData(this._byteTime); + } + return this._byteTime; + }; + /** + * Gets the current frequency data as a float array + * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData + * @returns a Float32Array + */ + Analyser.prototype.getFloatFrequencyData = function () { + if (this._audioEngine.canUseWebAudio) { + this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING; + this._webAudioAnalyser.fftSize = this.FFT_SIZE; + this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs); + } + return this._floatFreqs; + }; + /** + * Renders the debug canvas + */ + Analyser.prototype.drawDebugCanvas = function () { + var _this = this; + if (this._audioEngine.canUseWebAudio) { + if (!this._debugCanvas) { + this._debugCanvas = document.createElement("canvas"); + this._debugCanvas.width = this.DEBUGCANVASSIZE.width; + this._debugCanvas.height = this.DEBUGCANVASSIZE.height; + this._debugCanvas.style.position = "absolute"; + this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px"; + this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px"; + this._debugCanvasContext = this._debugCanvas.getContext("2d"); + document.body.appendChild(this._debugCanvas); + this._registerFunc = function () { + _this.drawDebugCanvas(); + }; + this._scene.registerBeforeRender(this._registerFunc); + } + if (this._registerFunc && this._debugCanvasContext) { + var workingArray = this.getByteFrequencyData(); + this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)'; + this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height); + // Draw the frequency domain chart. + for (var i = 0; i < this.getFrequencyBinCount(); i++) { + var value = workingArray[i]; + var percent = value / this.BARGRAPHAMPLITUDE; + var height = this.DEBUGCANVASSIZE.height * percent; + var offset = this.DEBUGCANVASSIZE.height - height - 1; + var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount(); + var hue = i / this.getFrequencyBinCount() * 360; + this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)'; + this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height); + } + } + } + }; + /** + * Stops rendering the debug canvas and removes it + */ + Analyser.prototype.stopDebugCanvas = function () { + if (this._debugCanvas) { + if (this._registerFunc) { + this._scene.unregisterBeforeRender(this._registerFunc); + this._registerFunc = null; + } + document.body.removeChild(this._debugCanvas); + this._debugCanvas = null; + this._debugCanvasContext = null; + } + }; + /** + * Connects two audio nodes + * @param inputAudioNode defines first node to connect + * @param outputAudioNode defines second node to connect + */ + Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) { + if (this._audioEngine.canUseWebAudio) { + inputAudioNode.connect(this._webAudioAnalyser); + this._webAudioAnalyser.connect(outputAudioNode); + } + }; + /** + * Releases all associated resources + */ + Analyser.prototype.dispose = function () { + if (this._audioEngine.canUseWebAudio) { + this._webAudioAnalyser.disconnect(); + } + }; + return Analyser; +}()); + + + +/***/ }), + +/***/ "./Audio/audioEngine.ts": +/*!******************************!*\ + !*** ./Audio/audioEngine.ts ***! + \******************************/ +/*! exports provided: AudioEngine */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AudioEngine", function() { return AudioEngine; }); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts"); +/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Engines/engine */ "./Engines/engine.ts"); + + + +// Sets the default audio engine to Babylon.js +_Engines_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].AudioEngineFactory = function (hostElement) { return new AudioEngine(hostElement); }; +/** + * This represents the default audio engine used in babylon. + * It is responsible to play, synchronize and analyse sounds throughout the application. + * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music + */ +var AudioEngine = /** @class */ (function () { + /** + * Instantiates a new audio engine. + * + * There should be only one per page as some browsers restrict the number + * of audio contexts you can create. + * @param hostElement defines the host element where to display the mute icon if necessary + */ + function AudioEngine(hostElement) { + var _this = this; + if (hostElement === void 0) { hostElement = null; } + this._audioContext = null; + this._audioContextInitialized = false; + this._muteButton = null; + /** + * Gets whether the current host supports Web Audio and thus could create AudioContexts. + */ + this.canUseWebAudio = false; + /** + * Defines if Babylon should emit a warning if WebAudio is not supported. + * @ignoreNaming + */ + this.WarnedWebAudioUnsupported = false; + /** + * Gets whether or not mp3 are supported by your browser. + */ + this.isMP3supported = false; + /** + * Gets whether or not ogg are supported by your browser. + */ + this.isOGGsupported = false; + /** + * Gets whether audio has been unlocked on the device. + * Some Browsers have strong restrictions about Audio and won t autoplay unless + * a user interaction has happened. + */ + this.unlocked = true; + /** + * Defines if the audio engine relies on a custom unlocked button. + * In this case, the embedded button will not be displayed. + */ + this.useCustomUnlockedButton = false; + /** + * Event raised when audio has been unlocked on the browser. + */ + this.onAudioUnlockedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](); + /** + * Event raised when audio has been locked on the browser. + */ + this.onAudioLockedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](); + this._tryToRun = false; + this._onResize = function () { + _this._moveButtonToTopLeft(); + }; + if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') { + window.AudioContext = window.AudioContext || window.webkitAudioContext; + this.canUseWebAudio = true; + } + var audioElem = document.createElement('audio'); + this._hostElement = hostElement; + try { + if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) { + this.isMP3supported = true; + } + } + catch (e) { + // protect error during capability check. + } + try { + if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) { + this.isOGGsupported = true; + } + } + catch (e) { + // protect error during capability check. + } + } + Object.defineProperty(AudioEngine.prototype, "audioContext", { + /** + * Gets the current AudioContext if available. + */ + get: function () { + if (!this._audioContextInitialized) { + this._initializeAudioContext(); + } + else { + if (!this.unlocked && !this._muteButton) { + this._displayMuteButton(); + } + } + return this._audioContext; + }, + enumerable: true, + configurable: true + }); + /** + * Flags the audio engine in Locked state. + * This happens due to new browser policies preventing audio to autoplay. + */ + AudioEngine.prototype.lock = function () { + this._triggerSuspendedState(); + }; + /** + * Unlocks the audio engine once a user action has been done on the dom. + * This is helpful to resume play once browser policies have been satisfied. + */ + AudioEngine.prototype.unlock = function () { + this._triggerRunningState(); + }; + AudioEngine.prototype._resumeAudioContext = function () { + var result; + if (this._audioContext.resume) { + result = this._audioContext.resume(); + } + return result || Promise.resolve(); + }; + AudioEngine.prototype._initializeAudioContext = function () { + try { + if (this.canUseWebAudio) { + this._audioContext = new AudioContext(); + // create a global volume gain node + this.masterGain = this._audioContext.createGain(); + this.masterGain.gain.value = 1; + this.masterGain.connect(this._audioContext.destination); + this._audioContextInitialized = true; + if (this._audioContext.state === "running") { + // Do not wait for the promise to unlock. + this._triggerRunningState(); + } + } + } + catch (e) { + this.canUseWebAudio = false; + _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Error("Web Audio: " + e.message); + } + }; + AudioEngine.prototype._triggerRunningState = function () { + var _this = this; + if (this._tryToRun) { + return; + } + this._tryToRun = true; + this._resumeAudioContext() + .then(function () { + _this._tryToRun = false; + if (_this._muteButton) { + _this._hideMuteButton(); + } + }).catch(function () { + _this._tryToRun = false; + _this.unlocked = false; + }); + // Notify users that the audio stack is unlocked/unmuted + this.unlocked = true; + this.onAudioUnlockedObservable.notifyObservers(this); + }; + AudioEngine.prototype._triggerSuspendedState = function () { + this.unlocked = false; + this.onAudioLockedObservable.notifyObservers(this); + this._displayMuteButton(); + }; + AudioEngine.prototype._displayMuteButton = function () { + var _this = this; + if (this.useCustomUnlockedButton || this._muteButton) { + return; + } + this._muteButton = document.createElement("BUTTON"); + this._muteButton.className = "babylonUnmuteIcon"; + this._muteButton.id = "babylonUnmuteIconBtn"; + this._muteButton.title = "Unmute"; + var css = ".babylonUnmuteIcon { position: absolute; left: 20px; top: 20px; height: 40px; width: 60px; background-color: rgba(51,51,51,0.7); background-image: url(data:image/svg+xml;charset=UTF-8,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2239%22%20height%3D%2232%22%20viewBox%3D%220%200%2039%2032%22%3E%3Cpath%20fill%3D%22white%22%20d%3D%22M9.625%2018.938l-0.031%200.016h-4.953q-0.016%200-0.031-0.016v-12.453q0-0.016%200.031-0.016h4.953q0.031%200%200.031%200.016v12.453zM12.125%207.688l8.719-8.703v27.453l-8.719-8.719-0.016-0.047v-9.938zM23.359%207.875l1.406-1.406%204.219%204.203%204.203-4.203%201.422%201.406-4.219%204.219%204.219%204.203-1.484%201.359-4.141-4.156-4.219%204.219-1.406-1.422%204.219-4.203z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E); background-size: 80%; background-repeat:no-repeat; background-position: center; background-position-y: 4px; border: none; outline: none; transition: transform 0.125s ease-out; cursor: pointer; z-index: 9999; } .babylonUnmuteIcon:hover { transform: scale(1.05) } .babylonUnmuteIcon:active { background-color: rgba(51,51,51,1) }"; + var style = document.createElement('style'); + style.appendChild(document.createTextNode(css)); + document.getElementsByTagName('head')[0].appendChild(style); + document.body.appendChild(this._muteButton); + this._moveButtonToTopLeft(); + this._muteButton.addEventListener('touchend', function () { + _this._triggerRunningState(); + }, true); + this._muteButton.addEventListener('click', function () { + _this._triggerRunningState(); + }, true); + window.addEventListener("resize", this._onResize); + }; + AudioEngine.prototype._moveButtonToTopLeft = function () { + if (this._hostElement && this._muteButton) { + this._muteButton.style.top = this._hostElement.offsetTop + 20 + "px"; + this._muteButton.style.left = this._hostElement.offsetLeft + 20 + "px"; + } + }; + AudioEngine.prototype._hideMuteButton = function () { + if (this._muteButton) { + document.body.removeChild(this._muteButton); + this._muteButton = null; + } + }; + /** + * Destroy and release the resources associated with the audio ccontext. + */ + AudioEngine.prototype.dispose = function () { + if (this.canUseWebAudio && this._audioContextInitialized) { + if (this._connectedAnalyser && this._audioContext) { + this._connectedAnalyser.stopDebugCanvas(); + this._connectedAnalyser.dispose(); + this.masterGain.disconnect(); + this.masterGain.connect(this._audioContext.destination); + this._connectedAnalyser = null; + } + this.masterGain.gain.value = 1; + } + this.WarnedWebAudioUnsupported = false; + this._hideMuteButton(); + window.removeEventListener("resize", this._onResize); + this.onAudioUnlockedObservable.clear(); + this.onAudioLockedObservable.clear(); + }; + /** + * Gets the global volume sets on the master gain. + * @returns the global volume if set or -1 otherwise + */ + AudioEngine.prototype.getGlobalVolume = function () { + if (this.canUseWebAudio && this._audioContextInitialized) { + return this.masterGain.gain.value; + } + else { + return -1; + } + }; + /** + * Sets the global volume of your experience (sets on the master gain). + * @param newVolume Defines the new global volume of the application + */ + AudioEngine.prototype.setGlobalVolume = function (newVolume) { + if (this.canUseWebAudio && this._audioContextInitialized) { + this.masterGain.gain.value = newVolume; + } + }; + /** + * Connect the audio engine to an audio analyser allowing some amazing + * synchornization between the sounds/music and your visualization (VuMeter for instance). + * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser + * @param analyser The analyser to connect to the engine + */ + AudioEngine.prototype.connectToAnalyser = function (analyser) { + if (this._connectedAnalyser) { + this._connectedAnalyser.stopDebugCanvas(); + } + if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) { + this._connectedAnalyser = analyser; + this.masterGain.disconnect(); + this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination); + } + }; + return AudioEngine; +}()); + + + +/***/ }), + +/***/ "./Audio/audioSceneComponent.ts": +/*!**************************************!*\ + !*** ./Audio/audioSceneComponent.ts ***! + \**************************************/ +/*! exports provided: AudioSceneComponent */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AudioSceneComponent", function() { return AudioSceneComponent; }); +/* harmony import */ var _sound__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./sound */ "./Audio/sound.ts"); +/* harmony import */ var _soundTrack__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./soundTrack */ "./Audio/soundTrack.ts"); +/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Engines/engine */ "./Engines/engine.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _sceneComponent__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../sceneComponent */ "./sceneComponent.ts"); +/* harmony import */ var _scene__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../scene */ "./scene.ts"); +/* harmony import */ var _abstractScene__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../abstractScene */ "./abstractScene.ts"); + + + + + + + +// Adds the parser to the scene parsers. +_abstractScene__WEBPACK_IMPORTED_MODULE_6__["AbstractScene"].AddParser(_sceneComponent__WEBPACK_IMPORTED_MODULE_4__["SceneComponentConstants"].NAME_AUDIO, function (parsedData, scene, container, rootUrl) { + // TODO: add sound + var loadedSounds = []; + var loadedSound; + container.sounds = container.sounds || []; + if (parsedData.sounds !== undefined && parsedData.sounds !== null) { + for (var index = 0, cache = parsedData.sounds.length; index < cache; index++) { + var parsedSound = parsedData.sounds[index]; + if (_Engines_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].audioEngine.canUseWebAudio) { + if (!parsedSound.url) { + parsedSound.url = parsedSound.name; + } + if (!loadedSounds[parsedSound.url]) { + loadedSound = _sound__WEBPACK_IMPORTED_MODULE_0__["Sound"].Parse(parsedSound, scene, rootUrl); + loadedSounds[parsedSound.url] = loadedSound; + container.sounds.push(loadedSound); + } + else { + container.sounds.push(_sound__WEBPACK_IMPORTED_MODULE_0__["Sound"].Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url])); + } + } + else { + container.sounds.push(new _sound__WEBPACK_IMPORTED_MODULE_0__["Sound"](parsedSound.name, null, scene)); + } + } + } + loadedSounds = []; +}); +Object.defineProperty(_scene__WEBPACK_IMPORTED_MODULE_5__["Scene"].prototype, "mainSoundTrack", { + get: function () { + var compo = this._getComponent(_sceneComponent__WEBPACK_IMPORTED_MODULE_4__["SceneComponentConstants"].NAME_AUDIO); + if (!compo) { + compo = new AudioSceneComponent(this); + this._addComponent(compo); + } + if (!this._mainSoundTrack) { + this._mainSoundTrack = new _soundTrack__WEBPACK_IMPORTED_MODULE_1__["SoundTrack"](this, { mainTrack: true }); + } + return this._mainSoundTrack; + }, + enumerable: true, + configurable: true +}); +_scene__WEBPACK_IMPORTED_MODULE_5__["Scene"].prototype.getSoundByName = function (name) { + var index; + for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) { + if (this.mainSoundTrack.soundCollection[index].name === name) { + return this.mainSoundTrack.soundCollection[index]; + } + } + if (this.soundTracks) { + for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) { + for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) { + if (this.soundTracks[sdIndex].soundCollection[index].name === name) { + return this.soundTracks[sdIndex].soundCollection[index]; + } + } + } + } + return null; +}; +Object.defineProperty(_scene__WEBPACK_IMPORTED_MODULE_5__["Scene"].prototype, "audioEnabled", { + get: function () { + var compo = this._getComponent(_sceneComponent__WEBPACK_IMPORTED_MODULE_4__["SceneComponentConstants"].NAME_AUDIO); + if (!compo) { + compo = new AudioSceneComponent(this); + this._addComponent(compo); + } + return compo.audioEnabled; + }, + set: function (value) { + var compo = this._getComponent(_sceneComponent__WEBPACK_IMPORTED_MODULE_4__["SceneComponentConstants"].NAME_AUDIO); + if (!compo) { + compo = new AudioSceneComponent(this); + this._addComponent(compo); + } + if (value) { + compo.enableAudio(); + } + else { + compo.disableAudio(); + } + }, + enumerable: true, + configurable: true +}); +Object.defineProperty(_scene__WEBPACK_IMPORTED_MODULE_5__["Scene"].prototype, "headphone", { + get: function () { + var compo = this._getComponent(_sceneComponent__WEBPACK_IMPORTED_MODULE_4__["SceneComponentConstants"].NAME_AUDIO); + if (!compo) { + compo = new AudioSceneComponent(this); + this._addComponent(compo); + } + return compo.headphone; + }, + set: function (value) { + var compo = this._getComponent(_sceneComponent__WEBPACK_IMPORTED_MODULE_4__["SceneComponentConstants"].NAME_AUDIO); + if (!compo) { + compo = new AudioSceneComponent(this); + this._addComponent(compo); + } + if (value) { + compo.switchAudioModeForHeadphones(); + } + else { + compo.switchAudioModeForNormalSpeakers(); + } + }, + enumerable: true, + configurable: true +}); +/** + * Defines the sound scene component responsible to manage any sounds + * in a given scene. + */ +var AudioSceneComponent = /** @class */ (function () { + /** + * Creates a new instance of the component for the given scene + * @param scene Defines the scene to register the component in + */ + function AudioSceneComponent(scene) { + /** + * The component name helpfull to identify the component in the list of scene components. + */ + this.name = _sceneComponent__WEBPACK_IMPORTED_MODULE_4__["SceneComponentConstants"].NAME_AUDIO; + this._audioEnabled = true; + this._headphone = false; + this.scene = scene; + scene.soundTracks = new Array(); + scene.sounds = new Array(); + } + Object.defineProperty(AudioSceneComponent.prototype, "audioEnabled", { + /** + * Gets whether audio is enabled or not. + * Please use related enable/disable method to switch state. + */ + get: function () { + return this._audioEnabled; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(AudioSceneComponent.prototype, "headphone", { + /** + * Gets whether audio is outputing to headphone or not. + * Please use the according Switch methods to change output. + */ + get: function () { + return this._headphone; + }, + enumerable: true, + configurable: true + }); + /** + * Registers the component in a given scene + */ + AudioSceneComponent.prototype.register = function () { + this.scene._afterRenderStage.registerStep(_sceneComponent__WEBPACK_IMPORTED_MODULE_4__["SceneComponentConstants"].STEP_AFTERRENDER_AUDIO, this, this._afterRender); + }; + /** + * Rebuilds the elements related to this component in case of + * context lost for instance. + */ + AudioSceneComponent.prototype.rebuild = function () { + // Nothing to do here. (Not rendering related) + }; + /** + * Serializes the component data to the specified json object + * @param serializationObject The object to serialize to + */ + AudioSceneComponent.prototype.serialize = function (serializationObject) { + serializationObject.sounds = []; + if (this.scene.soundTracks) { + for (var index = 0; index < this.scene.soundTracks.length; index++) { + var soundtrack = this.scene.soundTracks[index]; + for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) { + serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize()); + } + } + } + }; + /** + * Adds all the elements from the container to the scene + * @param container the container holding the elements + */ + AudioSceneComponent.prototype.addFromContainer = function (container) { + var _this = this; + if (!container.sounds) { + return; + } + container.sounds.forEach(function (sound) { + sound.play(); + sound.autoplay = true; + _this.scene.mainSoundTrack.AddSound(sound); + }); + }; + /** + * Removes all the elements in the container from the scene + * @param container contains the elements to remove + * @param dispose if the removed element should be disposed (default: false) + */ + AudioSceneComponent.prototype.removeFromContainer = function (container, dispose) { + var _this = this; + if (dispose === void 0) { dispose = false; } + if (!container.sounds) { + return; + } + container.sounds.forEach(function (sound) { + sound.stop(); + sound.autoplay = false; + _this.scene.mainSoundTrack.RemoveSound(sound); + if (dispose) { + sound.dispose(); + } + }); + }; + /** + * Disposes the component and the associated ressources. + */ + AudioSceneComponent.prototype.dispose = function () { + var scene = this.scene; + if (scene._mainSoundTrack) { + scene.mainSoundTrack.dispose(); + } + if (scene.soundTracks) { + for (var scIndex = 0; scIndex < scene.soundTracks.length; scIndex++) { + scene.soundTracks[scIndex].dispose(); + } + } + }; + /** + * Disables audio in the associated scene. + */ + AudioSceneComponent.prototype.disableAudio = function () { + var scene = this.scene; + this._audioEnabled = false; + var i; + for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) { + scene.mainSoundTrack.soundCollection[i].pause(); + } + if (scene.soundTracks) { + for (i = 0; i < scene.soundTracks.length; i++) { + for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) { + scene.soundTracks[i].soundCollection[j].pause(); + } + } + } + }; + /** + * Enables audio in the associated scene. + */ + AudioSceneComponent.prototype.enableAudio = function () { + var scene = this.scene; + this._audioEnabled = true; + var i; + for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) { + if (scene.mainSoundTrack.soundCollection[i].isPaused) { + scene.mainSoundTrack.soundCollection[i].play(); + } + } + if (scene.soundTracks) { + for (i = 0; i < scene.soundTracks.length; i++) { + for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) { + if (scene.soundTracks[i].soundCollection[j].isPaused) { + scene.soundTracks[i].soundCollection[j].play(); + } + } + } + } + }; + /** + * Switch audio to headphone output. + */ + AudioSceneComponent.prototype.switchAudioModeForHeadphones = function () { + var scene = this.scene; + this._headphone = true; + scene.mainSoundTrack.switchPanningModelToHRTF(); + if (scene.soundTracks) { + for (var i = 0; i < scene.soundTracks.length; i++) { + scene.soundTracks[i].switchPanningModelToHRTF(); + } + } + }; + /** + * Switch audio to normal speakers. + */ + AudioSceneComponent.prototype.switchAudioModeForNormalSpeakers = function () { + var scene = this.scene; + this._headphone = false; + scene.mainSoundTrack.switchPanningModelToEqualPower(); + if (scene.soundTracks) { + for (var i = 0; i < scene.soundTracks.length; i++) { + scene.soundTracks[i].switchPanningModelToEqualPower(); + } + } + }; + AudioSceneComponent.prototype._afterRender = function () { + var scene = this.scene; + if (!this._audioEnabled || !scene._mainSoundTrack || !scene.soundTracks || (scene._mainSoundTrack.soundCollection.length === 0 && scene.soundTracks.length === 1)) { + return; + } + var listeningCamera; + var audioEngine = _Engines_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].audioEngine; + if (scene.activeCameras.length > 0) { + listeningCamera = scene.activeCameras[0]; + } + else { + listeningCamera = scene.activeCamera; + } + if (listeningCamera && audioEngine.audioContext) { + audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z); + // for VR cameras + if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) { + listeningCamera = listeningCamera.rigCameras[0]; + } + var mat = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"].Invert(listeningCamera.getViewMatrix()); + var cameraDirection = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformNormal(new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, -1), mat); + cameraDirection.normalize(); + // To avoid some errors on GearVR + if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) { + audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0); + } + var i; + for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) { + var sound = scene.mainSoundTrack.soundCollection[i]; + if (sound.useCustomAttenuation) { + sound.updateDistanceFromListener(); + } + } + if (scene.soundTracks) { + for (i = 0; i < scene.soundTracks.length; i++) { + for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) { + sound = scene.soundTracks[i].soundCollection[j]; + if (sound.useCustomAttenuation) { + sound.updateDistanceFromListener(); + } + } + } + } + } + }; + return AudioSceneComponent; +}()); + +_sound__WEBPACK_IMPORTED_MODULE_0__["Sound"]._SceneComponentInitialization = function (scene) { + var compo = scene._getComponent(_sceneComponent__WEBPACK_IMPORTED_MODULE_4__["SceneComponentConstants"].NAME_AUDIO); + if (!compo) { + compo = new AudioSceneComponent(scene); + scene._addComponent(compo); + } +}; + + +/***/ }), + +/***/ "./Audio/index.ts": +/*!************************!*\ + !*** ./Audio/index.ts ***! + \************************/ +/*! exports provided: Analyser, AudioEngine, AudioSceneComponent, Sound, SoundTrack, WeightedSound */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _analyser__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./analyser */ "./Audio/analyser.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Analyser", function() { return _analyser__WEBPACK_IMPORTED_MODULE_0__["Analyser"]; }); + +/* harmony import */ var _audioEngine__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./audioEngine */ "./Audio/audioEngine.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AudioEngine", function() { return _audioEngine__WEBPACK_IMPORTED_MODULE_1__["AudioEngine"]; }); + +/* harmony import */ var _audioSceneComponent__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./audioSceneComponent */ "./Audio/audioSceneComponent.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AudioSceneComponent", function() { return _audioSceneComponent__WEBPACK_IMPORTED_MODULE_2__["AudioSceneComponent"]; }); + +/* harmony import */ var _sound__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./sound */ "./Audio/sound.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Sound", function() { return _sound__WEBPACK_IMPORTED_MODULE_3__["Sound"]; }); + +/* harmony import */ var _soundTrack__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./soundTrack */ "./Audio/soundTrack.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SoundTrack", function() { return _soundTrack__WEBPACK_IMPORTED_MODULE_4__["SoundTrack"]; }); + +/* harmony import */ var _weightedsound__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./weightedsound */ "./Audio/weightedsound.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WeightedSound", function() { return _weightedsound__WEBPACK_IMPORTED_MODULE_5__["WeightedSound"]; }); + + + + + + + + + +/***/ }), + +/***/ "./Audio/sound.ts": +/*!************************!*\ + !*** ./Audio/sound.ts ***! + \************************/ +/*! exports provided: Sound */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Sound", function() { return Sound; }); +/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/tools */ "./Misc/tools.ts"); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Engines/engine */ "./Engines/engine.ts"); +/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts"); +/* harmony import */ var _Misc_devTools__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Misc/devTools */ "./Misc/devTools.ts"); + + + + + + +/** + * Defines a sound that can be played in the application. + * The sound can either be an ambient track or a simple sound played in reaction to a user action. + * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music + */ +var Sound = /** @class */ (function () { + /** + * Create a sound and attach it to a scene + * @param name Name of your sound + * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams + * @param scene defines the scene the sound belongs to + * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played + * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming + */ + function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) { + var _this = this; + if (readyToPlayCallback === void 0) { readyToPlayCallback = null; } + /** + * Does the sound autoplay once loaded. + */ + this.autoplay = false; + /** + * Does the sound loop after it finishes playing once. + */ + this.loop = false; + /** + * Does the sound use a custom attenuation curve to simulate the falloff + * happening when the source gets further away from the camera. + * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function + */ + this.useCustomAttenuation = false; + /** + * Is this sound currently played. + */ + this.isPlaying = false; + /** + * Is this sound currently paused. + */ + this.isPaused = false; + /** + * Does this sound enables spatial sound. + * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound + */ + this.spatialSound = false; + /** + * Define the reference distance the sound should be heard perfectly. + * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound + */ + this.refDistance = 1; + /** + * Define the roll off factor of spatial sounds. + * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound + */ + this.rolloffFactor = 1; + /** + * Define the max distance the sound should be heard (intensity just became 0 at this point). + * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound + */ + this.maxDistance = 100; + /** + * Define the distance attenuation model the sound will follow. + * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound + */ + this.distanceModel = "linear"; + /** + * Observable event when the current playing sound finishes. + */ + this.onEndedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + this._panningModel = "equalpower"; + this._playbackRate = 1; + this._streaming = false; + this._startTime = 0; + this._startOffset = 0; + this._position = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); + /** @hidden */ + this._positionInEmitterSpace = false; + this._localDirection = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](1, 0, 0); + this._volume = 1; + this._isReadyToPlay = false; + this._isDirectional = false; + // Used if you'd like to create a directional sound. + // If not set, the sound will be omnidirectional + this._coneInnerAngle = 360; + this._coneOuterAngle = 360; + this._coneOuterGain = 0; + this._isOutputConnected = false; + this._urlType = "Unknown"; + this.name = name; + this._scene = scene; + Sound._SceneComponentInitialization(scene); + this._readyToPlayCallback = readyToPlayCallback; + // Default custom attenuation function is a linear attenuation + this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) { + if (currentDistance < maxDistance) { + return currentVolume * (1 - currentDistance / maxDistance); + } + else { + return 0; + } + }; + if (options) { + this.autoplay = options.autoplay || false; + this.loop = options.loop || false; + // if volume === 0, we need another way to check this option + if (options.volume !== undefined) { + this._volume = options.volume; + } + this.spatialSound = options.spatialSound || false; + this.maxDistance = options.maxDistance || 100; + this.useCustomAttenuation = options.useCustomAttenuation || false; + this.rolloffFactor = options.rolloffFactor || 1; + this.refDistance = options.refDistance || 1; + this.distanceModel = options.distanceModel || "linear"; + this._playbackRate = options.playbackRate || 1; + this._streaming = options.streaming || false; + } + if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.canUseWebAudio && _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext) { + this._soundGain = _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.createGain(); + this._soundGain.gain.value = this._volume; + this._inputAudioNode = this._soundGain; + this._outputAudioNode = this._soundGain; + if (this.spatialSound) { + this._createSpatialParameters(); + } + this._scene.mainSoundTrack.AddSound(this); + var validParameter = true; + // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound + if (urlOrArrayBuffer) { + try { + if (typeof (urlOrArrayBuffer) === "string") { + this._urlType = "String"; + } + else if (urlOrArrayBuffer instanceof ArrayBuffer) { + this._urlType = "ArrayBuffer"; + } + else if (urlOrArrayBuffer instanceof MediaStream) { + this._urlType = "MediaStream"; + } + else if (Array.isArray(urlOrArrayBuffer)) { + this._urlType = "Array"; + } + var urls = []; + var codecSupportedFound = false; + switch (this._urlType) { + case "MediaStream": + this._streaming = true; + this._isReadyToPlay = true; + this._streamingSource = _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.createMediaStreamSource(urlOrArrayBuffer); + if (this.autoplay) { + this.play(); + } + if (this._readyToPlayCallback) { + this._readyToPlayCallback(); + } + break; + case "ArrayBuffer": + if (urlOrArrayBuffer.byteLength > 0) { + codecSupportedFound = true; + this._soundLoaded(urlOrArrayBuffer); + } + break; + case "String": + urls.push(urlOrArrayBuffer); + case "Array": + if (urls.length === 0) { + urls = urlOrArrayBuffer; + } + // If we found a supported format, we load it immediately and stop the loop + for (var i = 0; i < urls.length; i++) { + var url = urls[i]; + if (url.indexOf(".mp3", url.length - 4) !== -1 && _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.isMP3supported) { + codecSupportedFound = true; + } + if (url.indexOf(".ogg", url.length - 4) !== -1 && _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.isOGGsupported) { + codecSupportedFound = true; + } + if (url.indexOf(".wav", url.length - 4) !== -1) { + codecSupportedFound = true; + } + if (url.indexOf("blob:") !== -1) { + codecSupportedFound = true; + } + if (codecSupportedFound) { + // Loading sound using XHR2 + if (!this._streaming) { + this._scene._loadFile(url, function (data) { + _this._soundLoaded(data); + }, undefined, true, true, function (exception) { + if (exception) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_4__["Logger"].Error("XHR " + exception.status + " error on: " + url + "."); + } + _Misc_logger__WEBPACK_IMPORTED_MODULE_4__["Logger"].Error("Sound creation aborted."); + _this._scene.mainSoundTrack.RemoveSound(_this); + }); + } + // Streaming sound using HTML5 Audio tag + else { + this._htmlAudioElement = new Audio(url); + this._htmlAudioElement.controls = false; + this._htmlAudioElement.loop = this.loop; + _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].SetCorsBehavior(url, this._htmlAudioElement); + this._htmlAudioElement.preload = "auto"; + this._htmlAudioElement.addEventListener("canplaythrough", function () { + _this._isReadyToPlay = true; + if (_this.autoplay) { + _this.play(); + } + if (_this._readyToPlayCallback) { + _this._readyToPlayCallback(); + } + }); + document.body.appendChild(this._htmlAudioElement); + this._htmlAudioElement.load(); + } + break; + } + } + break; + default: + validParameter = false; + break; + } + if (!validParameter) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_4__["Logger"].Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound."); + } + else { + if (!codecSupportedFound) { + this._isReadyToPlay = true; + // Simulating a ready to play event to avoid breaking code path + if (this._readyToPlayCallback) { + window.setTimeout(function () { + if (_this._readyToPlayCallback) { + _this._readyToPlayCallback(); + } + }, 1000); + } + } + } + } + catch (ex) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_4__["Logger"].Error("Unexpected error. Sound creation aborted."); + this._scene.mainSoundTrack.RemoveSound(this); + } + } + } + else { + // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers + this._scene.mainSoundTrack.AddSound(this); + if (!_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.WarnedWebAudioUnsupported) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_4__["Logger"].Error("Web Audio is not supported by your browser."); + _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.WarnedWebAudioUnsupported = true; + } + // Simulating a ready to play event to avoid breaking code for non web audio browsers + if (this._readyToPlayCallback) { + window.setTimeout(function () { + if (_this._readyToPlayCallback) { + _this._readyToPlayCallback(); + } + }, 1000); + } + } + } + /** + * Release the sound and its associated resources + */ + Sound.prototype.dispose = function () { + if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.canUseWebAudio) { + if (this.isPlaying) { + this.stop(); + } + this._isReadyToPlay = false; + if (this.soundTrackId === -1) { + this._scene.mainSoundTrack.RemoveSound(this); + } + else if (this._scene.soundTracks) { + this._scene.soundTracks[this.soundTrackId].RemoveSound(this); + } + if (this._soundGain) { + this._soundGain.disconnect(); + this._soundGain = null; + } + if (this._soundPanner) { + this._soundPanner.disconnect(); + this._soundPanner = null; + } + if (this._soundSource) { + this._soundSource.disconnect(); + this._soundSource = null; + } + this._audioBuffer = null; + if (this._htmlAudioElement) { + this._htmlAudioElement.pause(); + this._htmlAudioElement.src = ""; + document.body.removeChild(this._htmlAudioElement); + } + if (this._streamingSource) { + this._streamingSource.disconnect(); + } + if (this._connectedTransformNode && this._registerFunc) { + this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc); + this._connectedTransformNode = null; + } + } + }; + /** + * Gets if the sounds is ready to be played or not. + * @returns true if ready, otherwise false + */ + Sound.prototype.isReady = function () { + return this._isReadyToPlay; + }; + Sound.prototype._soundLoaded = function (audioData) { + var _this = this; + if (!_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext) { + return; + } + _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.decodeAudioData(audioData, function (buffer) { + _this._audioBuffer = buffer; + _this._isReadyToPlay = true; + if (_this.autoplay) { + _this.play(); + } + if (_this._readyToPlayCallback) { + _this._readyToPlayCallback(); + } + }, function (err) { _Misc_logger__WEBPACK_IMPORTED_MODULE_4__["Logger"].Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); }); + }; + /** + * Sets the data of the sound from an audiobuffer + * @param audioBuffer The audioBuffer containing the data + */ + Sound.prototype.setAudioBuffer = function (audioBuffer) { + if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.canUseWebAudio) { + this._audioBuffer = audioBuffer; + this._isReadyToPlay = true; + } + }; + /** + * Updates the current sounds options such as maxdistance, loop... + * @param options A JSON object containing values named as the object properties + */ + Sound.prototype.updateOptions = function (options) { + if (options) { + this.loop = options.loop || this.loop; + this.maxDistance = options.maxDistance || this.maxDistance; + this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation; + this.rolloffFactor = options.rolloffFactor || this.rolloffFactor; + this.refDistance = options.refDistance || this.refDistance; + this.distanceModel = options.distanceModel || this.distanceModel; + this._playbackRate = options.playbackRate || this._playbackRate; + this._updateSpatialParameters(); + if (this.isPlaying) { + if (this._streaming && this._htmlAudioElement) { + this._htmlAudioElement.playbackRate = this._playbackRate; + } + else { + if (this._soundSource) { + this._soundSource.playbackRate.value = this._playbackRate; + } + } + } + } + }; + Sound.prototype._createSpatialParameters = function () { + if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.canUseWebAudio && _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext) { + if (this._scene.headphone) { + this._panningModel = "HRTF"; + } + this._soundPanner = _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.createPanner(); + this._updateSpatialParameters(); + this._soundPanner.connect(this._outputAudioNode); + this._inputAudioNode = this._soundPanner; + } + }; + Sound.prototype._updateSpatialParameters = function () { + if (this.spatialSound && this._soundPanner) { + if (this.useCustomAttenuation) { + // Tricks to disable in a way embedded Web Audio attenuation + this._soundPanner.distanceModel = "linear"; + this._soundPanner.maxDistance = Number.MAX_VALUE; + this._soundPanner.refDistance = 1; + this._soundPanner.rolloffFactor = 1; + this._soundPanner.panningModel = this._panningModel; + } + else { + this._soundPanner.distanceModel = this.distanceModel; + this._soundPanner.maxDistance = this.maxDistance; + this._soundPanner.refDistance = this.refDistance; + this._soundPanner.rolloffFactor = this.rolloffFactor; + this._soundPanner.panningModel = this._panningModel; + } + } + }; + /** + * Switch the panning model to HRTF: + * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects. + * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound + */ + Sound.prototype.switchPanningModelToHRTF = function () { + this._panningModel = "HRTF"; + this._switchPanningModel(); + }; + /** + * Switch the panning model to Equal Power: + * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value. + * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound + */ + Sound.prototype.switchPanningModelToEqualPower = function () { + this._panningModel = "equalpower"; + this._switchPanningModel(); + }; + Sound.prototype._switchPanningModel = function () { + if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) { + this._soundPanner.panningModel = this._panningModel; + } + }; + /** + * Connect this sound to a sound track audio node like gain... + * @param soundTrackAudioNode the sound track audio node to connect to + */ + Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) { + if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.canUseWebAudio) { + if (this._isOutputConnected) { + this._outputAudioNode.disconnect(); + } + this._outputAudioNode.connect(soundTrackAudioNode); + this._isOutputConnected = true; + } + }; + /** + * Transform this sound into a directional source + * @param coneInnerAngle Size of the inner cone in degree + * @param coneOuterAngle Size of the outer cone in degree + * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0) + */ + Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) { + if (coneOuterAngle < coneInnerAngle) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_4__["Logger"].Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle."); + return; + } + this._coneInnerAngle = coneInnerAngle; + this._coneOuterAngle = coneOuterAngle; + this._coneOuterGain = coneOuterGain; + this._isDirectional = true; + if (this.isPlaying && this.loop) { + this.stop(); + this.play(); + } + }; + Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", { + /** + * Gets or sets the inner angle for the directional cone. + */ + get: function () { + return this._coneInnerAngle; + }, + /** + * Gets or sets the inner angle for the directional cone. + */ + set: function (value) { + if (value != this._coneInnerAngle) { + if (this._coneOuterAngle < value) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_4__["Logger"].Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle."); + return; + } + this._coneInnerAngle = value; + if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) { + this._soundPanner.coneInnerAngle = this._coneInnerAngle; + } + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", { + /** + * Gets or sets the outer angle for the directional cone. + */ + get: function () { + return this._coneOuterAngle; + }, + /** + * Gets or sets the outer angle for the directional cone. + */ + set: function (value) { + if (value != this._coneOuterAngle) { + if (value < this._coneInnerAngle) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_4__["Logger"].Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle."); + return; + } + this._coneOuterAngle = value; + if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) { + this._soundPanner.coneOuterAngle = this._coneOuterAngle; + } + } + }, + enumerable: true, + configurable: true + }); + /** + * Sets the position of the emitter if spatial sound is enabled + * @param newPosition Defines the new posisiton + */ + Sound.prototype.setPosition = function (newPosition) { + this._position = newPosition; + if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) { + this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z); + } + }; + /** + * Sets the local direction of the emitter if spatial sound is enabled + * @param newLocalDirection Defines the new local direction + */ + Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) { + this._localDirection = newLocalDirection; + if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.canUseWebAudio && this._connectedTransformNode && this.isPlaying) { + this._updateDirection(); + } + }; + Sound.prototype._updateDirection = function () { + if (!this._connectedTransformNode || !this._soundPanner) { + return; + } + var mat = this._connectedTransformNode.getWorldMatrix(); + var direction = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].TransformNormal(this._localDirection, mat); + direction.normalize(); + this._soundPanner.setOrientation(direction.x, direction.y, direction.z); + }; + /** @hidden */ + Sound.prototype.updateDistanceFromListener = function () { + if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.canUseWebAudio && this._connectedTransformNode && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) { + var distance = this._connectedTransformNode.getDistanceToCamera(this._scene.activeCamera); + this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor); + } + }; + /** + * Sets a new custom attenuation function for the sound. + * @param callback Defines the function used for the attenuation + * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function + */ + Sound.prototype.setAttenuationFunction = function (callback) { + this._customAttenuationFunction = callback; + }; + /** + * Play the sound + * @param time (optional) Start the sound after X seconds. Start immediately (0) by default. + * @param offset (optional) Start the sound setting it at a specific time + */ + Sound.prototype.play = function (time, offset) { + var _this = this; + if (this._isReadyToPlay && this._scene.audioEnabled && _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext) { + try { + if (this._startOffset < 0) { + time = -this._startOffset; + this._startOffset = 0; + } + var startTime = time ? _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.currentTime + time : _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.currentTime; + if (!this._soundSource || !this._streamingSource) { + if (this.spatialSound && this._soundPanner) { + if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) { + this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z); + } + if (this._isDirectional) { + this._soundPanner.coneInnerAngle = this._coneInnerAngle; + this._soundPanner.coneOuterAngle = this._coneOuterAngle; + this._soundPanner.coneOuterGain = this._coneOuterGain; + if (this._connectedTransformNode) { + this._updateDirection(); + } + else { + this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z); + } + } + } + } + if (this._streaming) { + if (!this._streamingSource) { + this._streamingSource = _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement); + this._htmlAudioElement.onended = function () { _this._onended(); }; + this._htmlAudioElement.playbackRate = this._playbackRate; + } + this._streamingSource.disconnect(); + this._streamingSource.connect(this._inputAudioNode); + if (this._htmlAudioElement) { + // required to manage properly the new suspended default state of Chrome + // When the option 'streaming: true' is used, we need first to wait for + // the audio engine to be unlocked by a user gesture before trying to play + // an HTML Audio elememt + var tryToPlay = function () { + if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.unlocked) { + var playPromise = _this._htmlAudioElement.play(); + // In browsers that don’t yet support this functionality, + // playPromise won’t be defined. + if (playPromise !== undefined) { + playPromise.catch(function (error) { + // Automatic playback failed. + // Waiting for the audio engine to be unlocked by user click on unmute + _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.lock(); + if (_this.loop || _this.autoplay) { + _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); }); + } + }); + } + } + else { + if (_this.loop || _this.autoplay) { + _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); }); + } + } + }; + tryToPlay(); + } + } + else { + var tryToPlay = function () { + if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext) { + _this._soundSource = _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.createBufferSource(); + _this._soundSource.buffer = _this._audioBuffer; + _this._soundSource.connect(_this._inputAudioNode); + _this._soundSource.loop = _this.loop; + _this._soundSource.playbackRate.value = _this._playbackRate; + _this._soundSource.onended = function () { _this._onended(); }; + startTime = time ? _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.currentTime + time : _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.currentTime; + _this._soundSource.start(startTime, _this.isPaused ? _this._startOffset % _this._soundSource.buffer.duration : offset ? offset : 0); + } + }; + if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.state === "suspended") { + // Wait a bit for FF as context seems late to be ready. + setTimeout(function () { + if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.state === "suspended") { + // Automatic playback failed. + // Waiting for the audio engine to be unlocked by user click on unmute + _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.lock(); + if (_this.loop || _this.autoplay) { + _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); }); + } + } + else { + tryToPlay(); + } + }, 500); + } + else { + tryToPlay(); + } + } + this._startTime = startTime; + this.isPlaying = true; + this.isPaused = false; + } + catch (ex) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_4__["Logger"].Error("Error while trying to play audio: " + this.name + ", " + ex.message); + } + } + }; + Sound.prototype._onended = function () { + this.isPlaying = false; + if (this.onended) { + this.onended(); + } + this.onEndedObservable.notifyObservers(this); + }; + /** + * Stop the sound + * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default. + */ + Sound.prototype.stop = function (time) { + var _this = this; + if (this.isPlaying) { + if (this._streaming) { + if (this._htmlAudioElement) { + this._htmlAudioElement.pause(); + // Test needed for Firefox or it will generate an Invalid State Error + if (this._htmlAudioElement.currentTime > 0) { + this._htmlAudioElement.currentTime = 0; + } + } + else { + this._streamingSource.disconnect(); + } + this.isPlaying = false; + } + else if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext && this._soundSource) { + var stopTime = time ? _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.currentTime + time : _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.currentTime; + this._soundSource.stop(stopTime); + this._soundSource.onended = function () { _this.isPlaying = false; }; + if (!this.isPaused) { + this._startOffset = 0; + } + } + } + }; + /** + * Put the sound in pause + */ + Sound.prototype.pause = function () { + if (this.isPlaying) { + this.isPaused = true; + if (this._streaming) { + if (this._htmlAudioElement) { + this._htmlAudioElement.pause(); + } + else { + this._streamingSource.disconnect(); + } + } + else if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext) { + this.stop(0); + this._startOffset += _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.currentTime - this._startTime; + } + } + }; + /** + * Sets a dedicated volume for this sounds + * @param newVolume Define the new volume of the sound + * @param time Define in how long the sound should be at this value + */ + Sound.prototype.setVolume = function (newVolume, time) { + if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.canUseWebAudio && this._soundGain) { + if (time && _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext) { + this._soundGain.gain.cancelScheduledValues(_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.currentTime); + this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.currentTime); + this._soundGain.gain.linearRampToValueAtTime(newVolume, _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.currentTime + time); + } + else { + this._soundGain.gain.value = newVolume; + } + } + this._volume = newVolume; + }; + /** + * Set the sound play back rate + * @param newPlaybackRate Define the playback rate the sound should be played at + */ + Sound.prototype.setPlaybackRate = function (newPlaybackRate) { + this._playbackRate = newPlaybackRate; + if (this.isPlaying) { + if (this._streaming && this._htmlAudioElement) { + this._htmlAudioElement.playbackRate = this._playbackRate; + } + else if (this._soundSource) { + this._soundSource.playbackRate.value = this._playbackRate; + } + } + }; + /** + * Gets the volume of the sound. + * @returns the volume of the sound + */ + Sound.prototype.getVolume = function () { + return this._volume; + }; + /** + * Attach the sound to a dedicated mesh + * @param transformNode The transform node to connect the sound with + * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh + */ + Sound.prototype.attachToMesh = function (transformNode) { + var _this = this; + if (this._connectedTransformNode && this._registerFunc) { + this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc); + this._registerFunc = null; + } + this._connectedTransformNode = transformNode; + if (!this.spatialSound) { + this.spatialSound = true; + this._createSpatialParameters(); + if (this.isPlaying && this.loop) { + this.stop(); + this.play(); + } + } + this._onRegisterAfterWorldMatrixUpdate(this._connectedTransformNode); + this._registerFunc = function (transformNode) { return _this._onRegisterAfterWorldMatrixUpdate(transformNode); }; + this._connectedTransformNode.registerAfterWorldMatrixUpdate(this._registerFunc); + }; + /** + * Detach the sound from the previously attached mesh + * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh + */ + Sound.prototype.detachFromMesh = function () { + if (this._connectedTransformNode && this._registerFunc) { + this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc); + this._registerFunc = null; + this._connectedTransformNode = null; + } + }; + Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) { + if (!node.getBoundingInfo) { + return; + } + var mesh = node; + if (this._positionInEmitterSpace) { + mesh.worldMatrixFromCache.invertToRef(_Maths_math__WEBPACK_IMPORTED_MODULE_2__["Tmp"].Matrix[0]); + this.setPosition(_Maths_math__WEBPACK_IMPORTED_MODULE_2__["Tmp"].Matrix[0].getTranslation()); + } + else { + var boundingInfo = mesh.getBoundingInfo(); + this.setPosition(boundingInfo.boundingSphere.centerWorld); + } + if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) { + this._updateDirection(); + } + }; + /** + * Clone the current sound in the scene. + * @returns the new sound clone + */ + Sound.prototype.clone = function () { + var _this = this; + if (!this._streaming) { + var setBufferAndRun = function () { + if (_this._isReadyToPlay) { + clonedSound._audioBuffer = _this.getAudioBuffer(); + clonedSound._isReadyToPlay = true; + if (clonedSound.autoplay) { + clonedSound.play(); + } + } + else { + window.setTimeout(setBufferAndRun, 300); + } + }; + var currentOptions = { + autoplay: this.autoplay, loop: this.loop, + volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance, + useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor, + refDistance: this.refDistance, distanceModel: this.distanceModel + }; + var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions); + if (this.useCustomAttenuation) { + clonedSound.setAttenuationFunction(this._customAttenuationFunction); + } + clonedSound.setPosition(this._position); + clonedSound.setPlaybackRate(this._playbackRate); + setBufferAndRun(); + return clonedSound; + } + // Can't clone a streaming sound + else { + return null; + } + }; + /** + * Gets the current underlying audio buffer containing the data + * @returns the audio buffer + */ + Sound.prototype.getAudioBuffer = function () { + return this._audioBuffer; + }; + /** + * Serializes the Sound in a JSON representation + * @returns the JSON representation of the sound + */ + Sound.prototype.serialize = function () { + var serializationObject = { + name: this.name, + url: this.name, + autoplay: this.autoplay, + loop: this.loop, + volume: this._volume, + spatialSound: this.spatialSound, + maxDistance: this.maxDistance, + rolloffFactor: this.rolloffFactor, + refDistance: this.refDistance, + distanceModel: this.distanceModel, + playbackRate: this._playbackRate, + panningModel: this._panningModel, + soundTrackId: this.soundTrackId + }; + if (this.spatialSound) { + if (this._connectedTransformNode) { + serializationObject.connectedMeshId = this._connectedTransformNode.id; + } + serializationObject.position = this._position.asArray(); + serializationObject.refDistance = this.refDistance; + serializationObject.distanceModel = this.distanceModel; + serializationObject.isDirectional = this._isDirectional; + serializationObject.localDirectionToMesh = this._localDirection.asArray(); + serializationObject.coneInnerAngle = this._coneInnerAngle; + serializationObject.coneOuterAngle = this._coneOuterAngle; + serializationObject.coneOuterGain = this._coneOuterGain; + } + return serializationObject; + }; + /** + * Parse a JSON representation of a sound to innstantiate in a given scene + * @param parsedSound Define the JSON representation of the sound (usually coming from the serialize method) + * @param scene Define the scene the new parsed sound should be created in + * @param rootUrl Define the rooturl of the load in case we need to fetch relative dependencies + * @param sourceSound Define a cound place holder if do not need to instantiate a new one + * @returns the newly parsed sound + */ + Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) { + var soundName = parsedSound.name; + var soundUrl; + if (parsedSound.url) { + soundUrl = rootUrl + parsedSound.url; + } + else { + soundUrl = rootUrl + soundName; + } + var options = { + autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume, + spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance, + rolloffFactor: parsedSound.rolloffFactor, + refDistance: parsedSound.refDistance, + distanceModel: parsedSound.distanceModel, + playbackRate: parsedSound.playbackRate + }; + var newSound; + if (!sourceSound) { + newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options); + scene._addPendingData(newSound); + } + else { + var setBufferAndRun = function () { + if (sourceSound._isReadyToPlay) { + newSound._audioBuffer = sourceSound.getAudioBuffer(); + newSound._isReadyToPlay = true; + if (newSound.autoplay) { + newSound.play(); + } + } + else { + window.setTimeout(setBufferAndRun, 300); + } + }; + newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options); + setBufferAndRun(); + } + if (parsedSound.position) { + var soundPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].FromArray(parsedSound.position); + newSound.setPosition(soundPosition); + } + if (parsedSound.isDirectional) { + newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0); + if (parsedSound.localDirectionToMesh) { + var localDirectionToMesh = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].FromArray(parsedSound.localDirectionToMesh); + newSound.setLocalDirectionToMesh(localDirectionToMesh); + } + } + if (parsedSound.connectedMeshId) { + var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId); + if (connectedMesh) { + newSound.attachToMesh(connectedMesh); + } + } + return newSound; + }; + /** @hidden */ + Sound._SceneComponentInitialization = function (_) { + throw _Misc_devTools__WEBPACK_IMPORTED_MODULE_5__["_DevTools"].WarnImport("AudioSceneComponent"); + }; + return Sound; +}()); + + + +/***/ }), + +/***/ "./Audio/soundTrack.ts": +/*!*****************************!*\ + !*** ./Audio/soundTrack.ts ***! + \*****************************/ +/*! exports provided: SoundTrack */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SoundTrack", function() { return SoundTrack; }); +/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Engines/engine */ "./Engines/engine.ts"); + +/** + * It could be useful to isolate your music & sounds on several tracks to better manage volume on a grouped instance of sounds. + * It will be also used in a future release to apply effects on a specific track. + * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks + */ +var SoundTrack = /** @class */ (function () { + /** + * Creates a new sound track. + * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks + * @param scene Define the scene the sound track belongs to + * @param options + */ + function SoundTrack(scene, options) { + if (options === void 0) { options = {}; } + /** + * The unique identifier of the sound track in the scene. + */ + this.id = -1; + this._isMainTrack = false; + this._isInitialized = false; + this._scene = scene; + this.soundCollection = new Array(); + this._options = options; + if (!this._isMainTrack && this._scene.soundTracks) { + this._scene.soundTracks.push(this); + this.id = this._scene.soundTracks.length - 1; + } + } + SoundTrack.prototype._initializeSoundTrackAudioGraph = function () { + if (_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].audioEngine.canUseWebAudio && _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].audioEngine.audioContext) { + this._outputAudioNode = _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].audioEngine.audioContext.createGain(); + this._outputAudioNode.connect(_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].audioEngine.masterGain); + if (this._options) { + if (this._options.volume) { + this._outputAudioNode.gain.value = this._options.volume; + } + if (this._options.mainTrack) { + this._isMainTrack = this._options.mainTrack; + } + } + this._isInitialized = true; + } + }; + /** + * Release the sound track and its associated resources + */ + SoundTrack.prototype.dispose = function () { + if (_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].audioEngine && _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].audioEngine.canUseWebAudio) { + if (this._connectedAnalyser) { + this._connectedAnalyser.stopDebugCanvas(); + } + while (this.soundCollection.length) { + this.soundCollection[0].dispose(); + } + if (this._outputAudioNode) { + this._outputAudioNode.disconnect(); + } + this._outputAudioNode = null; + } + }; + /** + * Adds a sound to this sound track + * @param sound define the cound to add + * @ignoreNaming + */ + SoundTrack.prototype.AddSound = function (sound) { + if (!this._isInitialized) { + this._initializeSoundTrackAudioGraph(); + } + if (_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].audioEngine.canUseWebAudio && this._outputAudioNode) { + sound.connectToSoundTrackAudioNode(this._outputAudioNode); + } + if (sound.soundTrackId) { + if (sound.soundTrackId === -1) { + this._scene.mainSoundTrack.RemoveSound(sound); + } + else if (this._scene.soundTracks) { + this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound); + } + } + this.soundCollection.push(sound); + sound.soundTrackId = this.id; + }; + /** + * Removes a sound to this sound track + * @param sound define the cound to remove + * @ignoreNaming + */ + SoundTrack.prototype.RemoveSound = function (sound) { + var index = this.soundCollection.indexOf(sound); + if (index !== -1) { + this.soundCollection.splice(index, 1); + } + }; + /** + * Set a global volume for the full sound track. + * @param newVolume Define the new volume of the sound track + */ + SoundTrack.prototype.setVolume = function (newVolume) { + if (_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].audioEngine.canUseWebAudio && this._outputAudioNode) { + this._outputAudioNode.gain.value = newVolume; + } + }; + /** + * Switch the panning model to HRTF: + * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects. + * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound + */ + SoundTrack.prototype.switchPanningModelToHRTF = function () { + if (_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].audioEngine.canUseWebAudio) { + for (var i = 0; i < this.soundCollection.length; i++) { + this.soundCollection[i].switchPanningModelToHRTF(); + } + } + }; + /** + * Switch the panning model to Equal Power: + * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value. + * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound + */ + SoundTrack.prototype.switchPanningModelToEqualPower = function () { + if (_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].audioEngine.canUseWebAudio) { + for (var i = 0; i < this.soundCollection.length; i++) { + this.soundCollection[i].switchPanningModelToEqualPower(); + } + } + }; + /** + * Connect the sound track to an audio analyser allowing some amazing + * synchornization between the sounds/music and your visualization (VuMeter for instance). + * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser + * @param analyser The analyser to connect to the engine + */ + SoundTrack.prototype.connectToAnalyser = function (analyser) { + if (this._connectedAnalyser) { + this._connectedAnalyser.stopDebugCanvas(); + } + this._connectedAnalyser = analyser; + if (_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].audioEngine.canUseWebAudio && this._outputAudioNode) { + this._outputAudioNode.disconnect(); + this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].audioEngine.masterGain); + } + }; + return SoundTrack; +}()); + + + +/***/ }), + +/***/ "./Audio/weightedsound.ts": +/*!********************************!*\ + !*** ./Audio/weightedsound.ts ***! + \********************************/ +/*! exports provided: WeightedSound */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WeightedSound", function() { return WeightedSound; }); +/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts"); + +/** + * Wraps one or more Sound objects and selects one with random weight for playback. + */ +var WeightedSound = /** @class */ (function () { + /** + * Creates a new WeightedSound from the list of sounds given. + * @param loop When true a Sound will be selected and played when the current playing Sound completes. + * @param sounds Array of Sounds that will be selected from. + * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1 + */ + function WeightedSound(loop, sounds, weights) { + var _this = this; + /** When true a Sound will be selected and played when the current playing Sound completes. */ + this.loop = false; + this._coneInnerAngle = 360; + this._coneOuterAngle = 360; + this._volume = 1; + /** A Sound is currently playing. */ + this.isPlaying = false; + /** A Sound is currently paused. */ + this.isPaused = false; + this._sounds = []; + this._weights = []; + if (sounds.length !== weights.length) { + throw new Error('Sounds length does not equal weights length'); + } + this.loop = loop; + this._weights = weights; + // Normalize the weights + var weightSum = 0; + for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) { + var weight = weights_1[_i]; + weightSum += weight; + } + var invWeightSum = weightSum > 0 ? 1 / weightSum : 0; + for (var i = 0; i < this._weights.length; i++) { + this._weights[i] *= invWeightSum; + } + this._sounds = sounds; + for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) { + var sound = _b[_a]; + sound.onEndedObservable.add(function () { _this._onended(); }); + } + } + Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", { + /** + * The size of cone in degrees for a directional sound in which there will be no attenuation. + */ + get: function () { + return this._coneInnerAngle; + }, + /** + * The size of cone in degress for a directional sound in which there will be no attenuation. + */ + set: function (value) { + if (value !== this._coneInnerAngle) { + if (this._coneOuterAngle < value) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_0__["Logger"].Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle."); + return; + } + this._coneInnerAngle = value; + for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) { + var sound = _a[_i]; + sound.directionalConeInnerAngle = value; + } + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", { + /** + * Size of cone in degrees for a directional sound outside of which there will be no sound. + * Listener angles between innerAngle and outerAngle will falloff linearly. + */ + get: function () { + return this._coneOuterAngle; + }, + /** + * Size of cone in degrees for a directional sound outside of which there will be no sound. + * Listener angles between innerAngle and outerAngle will falloff linearly. + */ + set: function (value) { + if (value !== this._coneOuterAngle) { + if (value < this._coneInnerAngle) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_0__["Logger"].Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle."); + return; + } + this._coneOuterAngle = value; + for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) { + var sound = _a[_i]; + sound.directionalConeOuterAngle = value; + } + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(WeightedSound.prototype, "volume", { + /** + * Playback volume. + */ + get: function () { + return this._volume; + }, + /** + * Playback volume. + */ + set: function (value) { + if (value !== this._volume) { + for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) { + var sound = _a[_i]; + sound.setVolume(value); + } + } + }, + enumerable: true, + configurable: true + }); + WeightedSound.prototype._onended = function () { + if (this._currentIndex !== undefined) { + this._sounds[this._currentIndex].autoplay = false; + } + if (this.loop && this.isPlaying) { + this.play(); + } + else { + this.isPlaying = false; + } + }; + /** + * Suspend playback + */ + WeightedSound.prototype.pause = function () { + this.isPaused = true; + if (this._currentIndex !== undefined) { + this._sounds[this._currentIndex].pause(); + } + }; + /** + * Stop playback + */ + WeightedSound.prototype.stop = function () { + this.isPlaying = false; + if (this._currentIndex !== undefined) { + this._sounds[this._currentIndex].stop(); + } + }; + /** + * Start playback. + * @param startOffset Position the clip head at a specific time in seconds. + */ + WeightedSound.prototype.play = function (startOffset) { + if (!this.isPaused) { + this.stop(); + var randomValue = Math.random(); + var total = 0; + for (var i = 0; i < this._weights.length; i++) { + total += this._weights[i]; + if (randomValue <= total) { + this._currentIndex = i; + break; + } + } + } + var sound = this._sounds[this._currentIndex]; + if (sound.isReady()) { + sound.play(0, this.isPaused ? undefined : startOffset); + } + else { + sound.autoplay = true; + } + this.isPlaying = true; + this.isPaused = false; + }; + return WeightedSound; +}()); + + + +/***/ }), + +/***/ "./Behaviors/Cameras/autoRotationBehavior.ts": +/*!***************************************************!*\ + !*** ./Behaviors/Cameras/autoRotationBehavior.ts ***! + \***************************************************/ +/*! exports provided: AutoRotationBehavior */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AutoRotationBehavior", function() { return AutoRotationBehavior; }); +/* harmony import */ var _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Events/pointerEvents */ "./Events/pointerEvents.ts"); +/* harmony import */ var _Misc_precisionDate__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/precisionDate */ "./Misc/precisionDate.ts"); + + +/** + * The autoRotation behavior (AutoRotationBehavior) is designed to create a smooth rotation of an ArcRotateCamera when there is no user interaction. + * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior + */ +var AutoRotationBehavior = /** @class */ (function () { + function AutoRotationBehavior() { + this._zoomStopsAnimation = false; + this._idleRotationSpeed = 0.05; + this._idleRotationWaitTime = 2000; + this._idleRotationSpinupTime = 2000; + this._isPointerDown = false; + this._lastFrameTime = null; + this._lastInteractionTime = -Infinity; + this._cameraRotationSpeed = 0; + this._lastFrameRadius = 0; + } + Object.defineProperty(AutoRotationBehavior.prototype, "name", { + /** + * Gets the name of the behavior. + */ + get: function () { + return "AutoRotation"; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", { + /** + * Gets the flag that indicates if user zooming should stop animation. + */ + get: function () { + return this._zoomStopsAnimation; + }, + /** + * Sets the flag that indicates if user zooming should stop animation. + */ + set: function (flag) { + this._zoomStopsAnimation = flag; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", { + /** + * Gets the default speed at which the camera rotates around the model. + */ + get: function () { + return this._idleRotationSpeed; + }, + /** + * Sets the default speed at which the camera rotates around the model. + */ + set: function (speed) { + this._idleRotationSpeed = speed; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", { + /** + * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating. + */ + get: function () { + return this._idleRotationWaitTime; + }, + /** + * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating. + */ + set: function (time) { + this._idleRotationWaitTime = time; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", { + /** + * Gets the time (milliseconds) to take to spin up to the full idle rotation speed. + */ + get: function () { + return this._idleRotationSpinupTime; + }, + /** + * Sets the time (milliseconds) to take to spin up to the full idle rotation speed. + */ + set: function (time) { + this._idleRotationSpinupTime = time; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", { + /** + * Gets a value indicating if the camera is currently rotating because of this behavior + */ + get: function () { + return Math.abs(this._cameraRotationSpeed) > 0; + }, + enumerable: true, + configurable: true + }); + /** + * Initializes the behavior. + */ + AutoRotationBehavior.prototype.init = function () { + // Do notihng + }; + /** + * Attaches the behavior to its arc rotate camera. + * @param camera Defines the camera to attach the behavior to + */ + AutoRotationBehavior.prototype.attach = function (camera) { + var _this = this; + this._attachedCamera = camera; + var scene = this._attachedCamera.getScene(); + this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) { + if (pointerInfoPre.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERDOWN) { + _this._isPointerDown = true; + return; + } + if (pointerInfoPre.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERUP) { + _this._isPointerDown = false; + } + }); + this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () { + var now = _Misc_precisionDate__WEBPACK_IMPORTED_MODULE_1__["PrecisionDate"].Now; + var dt = 0; + if (_this._lastFrameTime != null) { + dt = now - _this._lastFrameTime; + } + _this._lastFrameTime = now; + // Stop the animation if there is user interaction and the animation should stop for this interaction + _this._applyUserInteraction(); + var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime; + var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0); + _this._cameraRotationSpeed = _this._idleRotationSpeed * scale; + // Step camera rotation by rotation speed + if (_this._attachedCamera) { + _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000); + } + }); + }; + /** + * Detaches the behavior from its current arc rotate camera. + */ + AutoRotationBehavior.prototype.detach = function () { + if (!this._attachedCamera) { + return; + } + var scene = this._attachedCamera.getScene(); + if (this._onPrePointerObservableObserver) { + scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver); + } + this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver); + this._attachedCamera = null; + }; + /** + * Returns true if user is scrolling. + * @return true if user is scrolling. + */ + AutoRotationBehavior.prototype._userIsZooming = function () { + if (!this._attachedCamera) { + return false; + } + return this._attachedCamera.inertialRadiusOffset !== 0; + }; + AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () { + if (!this._attachedCamera) { + return false; + } + var zoomHasHitLimit = false; + if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) { + zoomHasHitLimit = true; + } + // Update the record of previous radius - works as an approx. indicator of hitting radius limits + this._lastFrameRadius = this._attachedCamera.radius; + return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming(); + }; + /** + * Applies any current user interaction to the camera. Takes into account maximum alpha rotation. + */ + AutoRotationBehavior.prototype._applyUserInteraction = function () { + if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) { + this._lastInteractionTime = _Misc_precisionDate__WEBPACK_IMPORTED_MODULE_1__["PrecisionDate"].Now; + } + }; + // Tools + AutoRotationBehavior.prototype._userIsMoving = function () { + if (!this._attachedCamera) { + return false; + } + return this._attachedCamera.inertialAlphaOffset !== 0 || + this._attachedCamera.inertialBetaOffset !== 0 || + this._attachedCamera.inertialRadiusOffset !== 0 || + this._attachedCamera.inertialPanningX !== 0 || + this._attachedCamera.inertialPanningY !== 0 || + this._isPointerDown; + }; + return AutoRotationBehavior; +}()); + + + +/***/ }), + +/***/ "./Behaviors/Cameras/bouncingBehavior.ts": +/*!***********************************************!*\ + !*** ./Behaviors/Cameras/bouncingBehavior.ts ***! + \***********************************************/ +/*! exports provided: BouncingBehavior */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BouncingBehavior", function() { return BouncingBehavior; }); +/* harmony import */ var _Animations_easing__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Animations/easing */ "./Animations/easing.ts"); +/* harmony import */ var _Animations_animation__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Animations/animation */ "./Animations/animation.ts"); + + +/** + * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius + * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior + */ +var BouncingBehavior = /** @class */ (function () { + function BouncingBehavior() { + /** + * The duration of the animation, in milliseconds + */ + this.transitionDuration = 450; + /** + * Length of the distance animated by the transition when lower radius is reached + */ + this.lowerRadiusTransitionRange = 2; + /** + * Length of the distance animated by the transition when upper radius is reached + */ + this.upperRadiusTransitionRange = -2; + this._autoTransitionRange = false; + // Animations + this._radiusIsAnimating = false; + this._radiusBounceTransition = null; + this._animatables = new Array(); + } + Object.defineProperty(BouncingBehavior.prototype, "name", { + /** + * Gets the name of the behavior. + */ + get: function () { + return "Bouncing"; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", { + /** + * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically + */ + get: function () { + return this._autoTransitionRange; + }, + /** + * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically + * Transition ranges will be set to 5% of the bounding box diagonal in world space + */ + set: function (value) { + var _this = this; + if (this._autoTransitionRange === value) { + return; + } + this._autoTransitionRange = value; + var camera = this._attachedCamera; + if (!camera) { + return; + } + if (value) { + this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) { + if (!mesh) { + return; + } + mesh.computeWorldMatrix(true); + var diagonal = mesh.getBoundingInfo().diagonalLength; + _this.lowerRadiusTransitionRange = diagonal * 0.05; + _this.upperRadiusTransitionRange = diagonal * 0.05; + }); + } + else if (this._onMeshTargetChangedObserver) { + camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver); + } + }, + enumerable: true, + configurable: true + }); + /** + * Initializes the behavior. + */ + BouncingBehavior.prototype.init = function () { + // Do notihng + }; + /** + * Attaches the behavior to its arc rotate camera. + * @param camera Defines the camera to attach the behavior to + */ + BouncingBehavior.prototype.attach = function (camera) { + var _this = this; + this._attachedCamera = camera; + this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () { + if (!_this._attachedCamera) { + return; + } + // Add the bounce animation to the lower radius limit + if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) { + _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange); + } + // Add the bounce animation to the upper radius limit + if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) { + _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange); + } + }); + }; + /** + * Detaches the behavior from its current arc rotate camera. + */ + BouncingBehavior.prototype.detach = function () { + if (!this._attachedCamera) { + return; + } + if (this._onAfterCheckInputsObserver) { + this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver); + } + if (this._onMeshTargetChangedObserver) { + this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver); + } + this._attachedCamera = null; + }; + /** + * Checks if the camera radius is at the specified limit. Takes into account animation locks. + * @param radiusLimit The limit to check against. + * @return Bool to indicate if at limit. + */ + BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) { + if (!this._attachedCamera) { + return false; + } + if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) { + return true; + } + return false; + }; + /** + * Applies an animation to the radius of the camera, extending by the radiusDelta. + * @param radiusDelta The delta by which to animate to. Can be negative. + */ + BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) { + var _this = this; + if (!this._attachedCamera) { + return; + } + if (!this._radiusBounceTransition) { + BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode); + this._radiusBounceTransition = _Animations_animation__WEBPACK_IMPORTED_MODULE_1__["Animation"].CreateAnimation("radius", _Animations_animation__WEBPACK_IMPORTED_MODULE_1__["Animation"].ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction); + } + // Prevent zoom until bounce has completed + this._cachedWheelPrecision = this._attachedCamera.wheelPrecision; + this._attachedCamera.wheelPrecision = Infinity; + this._attachedCamera.inertialRadiusOffset = 0; + // Animate to the radius limit + this.stopAllAnimations(); + this._radiusIsAnimating = true; + var animatable = _Animations_animation__WEBPACK_IMPORTED_MODULE_1__["Animation"].TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); }); + if (animatable) { + this._animatables.push(animatable); + } + }; + /** + * Removes all animation locks. Allows new animations to be added to any of the camera properties. + */ + BouncingBehavior.prototype._clearAnimationLocks = function () { + this._radiusIsAnimating = false; + if (this._attachedCamera) { + this._attachedCamera.wheelPrecision = this._cachedWheelPrecision; + } + }; + /** + * Stops and removes all animations that have been applied to the camera + */ + BouncingBehavior.prototype.stopAllAnimations = function () { + if (this._attachedCamera) { + this._attachedCamera.animations = []; + } + while (this._animatables.length) { + this._animatables[0].onAnimationEnd = null; + this._animatables[0].stop(); + this._animatables.shift(); + } + }; + /** + * The easing function used by animations + */ + BouncingBehavior.EasingFunction = new _Animations_easing__WEBPACK_IMPORTED_MODULE_0__["BackEase"](0.3); + /** + * The easing mode used by animations + */ + BouncingBehavior.EasingMode = _Animations_easing__WEBPACK_IMPORTED_MODULE_0__["EasingFunction"].EASINGMODE_EASEOUT; + return BouncingBehavior; +}()); + + + +/***/ }), + +/***/ "./Behaviors/Cameras/framingBehavior.ts": +/*!**********************************************!*\ + !*** ./Behaviors/Cameras/framingBehavior.ts ***! + \**********************************************/ +/*! exports provided: FramingBehavior */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FramingBehavior", function() { return FramingBehavior; }); +/* harmony import */ var _Animations_easing__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Animations/easing */ "./Animations/easing.ts"); +/* harmony import */ var _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Events/pointerEvents */ "./Events/pointerEvents.ts"); +/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/tools */ "./Misc/tools.ts"); +/* harmony import */ var _Misc_precisionDate__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Misc/precisionDate */ "./Misc/precisionDate.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Animations_animation__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Animations/animation */ "./Animations/animation.ts"); + + + + + + +/** + * The framing behavior (FramingBehavior) is designed to automatically position an ArcRotateCamera when its target is set to a mesh. It is also useful if you want to prevent the camera to go under a virtual horizontal plane. + * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior + */ +var FramingBehavior = /** @class */ (function () { + function FramingBehavior() { + this._mode = FramingBehavior.FitFrustumSidesMode; + this._radiusScale = 1.0; + this._positionScale = 0.5; + this._defaultElevation = 0.3; + this._elevationReturnTime = 1500; + this._elevationReturnWaitTime = 1000; + this._zoomStopsAnimation = false; + this._framingTime = 1500; + /** + * Define if the behavior should automatically change the configured + * camera limits and sensibilities. + */ + this.autoCorrectCameraLimitsAndSensibility = true; + this._isPointerDown = false; + this._lastInteractionTime = -Infinity; + // Framing control + this._animatables = new Array(); + this._betaIsAnimating = false; + } + Object.defineProperty(FramingBehavior.prototype, "name", { + /** + * Gets the name of the behavior. + */ + get: function () { + return "Framing"; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(FramingBehavior.prototype, "mode", { + /** + * Gets current mode used by the behavior. + */ + get: function () { + return this._mode; + }, + /** + * Sets the current mode used by the behavior + */ + set: function (mode) { + this._mode = mode; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(FramingBehavior.prototype, "radiusScale", { + /** + * Gets the scale applied to the radius + */ + get: function () { + return this._radiusScale; + }, + /** + * Sets the scale applied to the radius (1 by default) + */ + set: function (radius) { + this._radiusScale = radius; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(FramingBehavior.prototype, "positionScale", { + /** + * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box. + */ + get: function () { + return this._positionScale; + }, + /** + * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box. + */ + set: function (scale) { + this._positionScale = scale; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(FramingBehavior.prototype, "defaultElevation", { + /** + * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle + * behaviour is triggered, in radians. + */ + get: function () { + return this._defaultElevation; + }, + /** + * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle + * behaviour is triggered, in radians. + */ + set: function (elevation) { + this._defaultElevation = elevation; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", { + /** + * Gets the time (in milliseconds) taken to return to the default beta position. + * Negative value indicates camera should not return to default. + */ + get: function () { + return this._elevationReturnTime; + }, + /** + * Sets the time (in milliseconds) taken to return to the default beta position. + * Negative value indicates camera should not return to default. + */ + set: function (speed) { + this._elevationReturnTime = speed; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", { + /** + * Gets the delay (in milliseconds) taken before the camera returns to the default beta position. + */ + get: function () { + return this._elevationReturnWaitTime; + }, + /** + * Sets the delay (in milliseconds) taken before the camera returns to the default beta position. + */ + set: function (time) { + this._elevationReturnWaitTime = time; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", { + /** + * Gets the flag that indicates if user zooming should stop animation. + */ + get: function () { + return this._zoomStopsAnimation; + }, + /** + * Sets the flag that indicates if user zooming should stop animation. + */ + set: function (flag) { + this._zoomStopsAnimation = flag; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(FramingBehavior.prototype, "framingTime", { + /** + * Gets the transition time when framing the mesh, in milliseconds + */ + get: function () { + return this._framingTime; + }, + /** + * Sets the transition time when framing the mesh, in milliseconds + */ + set: function (time) { + this._framingTime = time; + }, + enumerable: true, + configurable: true + }); + /** + * Initializes the behavior. + */ + FramingBehavior.prototype.init = function () { + // Do notihng + }; + /** + * Attaches the behavior to its arc rotate camera. + * @param camera Defines the camera to attach the behavior to + */ + FramingBehavior.prototype.attach = function (camera) { + var _this = this; + this._attachedCamera = camera; + var scene = this._attachedCamera.getScene(); + FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode); + this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) { + if (pointerInfoPre.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_1__["PointerEventTypes"].POINTERDOWN) { + _this._isPointerDown = true; + return; + } + if (pointerInfoPre.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_1__["PointerEventTypes"].POINTERUP) { + _this._isPointerDown = false; + } + }); + this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) { + if (mesh) { + _this.zoomOnMesh(mesh); + } + }); + this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () { + // Stop the animation if there is user interaction and the animation should stop for this interaction + _this._applyUserInteraction(); + // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it + // back to the default position after a given timeout + _this._maintainCameraAboveGround(); + }); + }; + /** + * Detaches the behavior from its current arc rotate camera. + */ + FramingBehavior.prototype.detach = function () { + if (!this._attachedCamera) { + return; + } + var scene = this._attachedCamera.getScene(); + if (this._onPrePointerObservableObserver) { + scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver); + } + if (this._onAfterCheckInputsObserver) { + this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver); + } + if (this._onMeshTargetChangedObserver) { + this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver); + } + this._attachedCamera = null; + }; + /** + * Targets the given mesh and updates zoom level accordingly. + * @param mesh The mesh to target. + * @param radius Optional. If a cached radius position already exists, overrides default. + * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top + * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh + * @param onAnimationEnd Callback triggered at the end of the framing animation + */ + FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) { + if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; } + if (onAnimationEnd === void 0) { onAnimationEnd = null; } + mesh.computeWorldMatrix(true); + var boundingBox = mesh.getBoundingInfo().boundingBox; + this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd); + }; + /** + * Targets the given mesh with its children and updates zoom level accordingly. + * @param mesh The mesh to target. + * @param radius Optional. If a cached radius position already exists, overrides default. + * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top + * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh + * @param onAnimationEnd Callback triggered at the end of the framing animation + */ + FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) { + if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; } + if (onAnimationEnd === void 0) { onAnimationEnd = null; } + mesh.computeWorldMatrix(true); + var boundingBox = mesh.getHierarchyBoundingVectors(true); + this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd); + }; + /** + * Targets the given meshes with their children and updates zoom level accordingly. + * @param meshes The mesh to target. + * @param radius Optional. If a cached radius position already exists, overrides default. + * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top + * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh + * @param onAnimationEnd Callback triggered at the end of the framing animation + */ + FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) { + if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; } + if (onAnimationEnd === void 0) { onAnimationEnd = null; } + var min = new _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"](Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); + var max = new _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"](-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE); + for (var i = 0; i < meshes.length; i++) { + var boundingInfo = meshes[i].getHierarchyBoundingVectors(true); + _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].CheckExtends(boundingInfo.min, min, max); + _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].CheckExtends(boundingInfo.max, min, max); + } + this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd); + }; + /** + * Targets the bounding box info defined by its extends and updates zoom level accordingly. + * @param minimumWorld Determines the smaller position of the bounding box extend + * @param maximumWorld Determines the bigger position of the bounding box extend + * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh + * @param onAnimationEnd Callback triggered at the end of the framing animation + */ + FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) { + var _this = this; + if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; } + if (onAnimationEnd === void 0) { onAnimationEnd = null; } + var zoomTarget; + if (!this._attachedCamera) { + return; + } + // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY + var bottom = minimumWorld.y; + var top = maximumWorld.y; + var zoomTargetY = bottom + (top - bottom) * this._positionScale; + var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5); + if (focusOnOriginXZ) { + zoomTarget = new _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"](0, zoomTargetY, 0); + } + else { + var centerWorld = minimumWorld.add(radiusWorld); + zoomTarget = new _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"](centerWorld.x, zoomTargetY, centerWorld.z); + } + if (!this._vectorTransition) { + this._vectorTransition = _Animations_animation__WEBPACK_IMPORTED_MODULE_5__["Animation"].CreateAnimation("target", _Animations_animation__WEBPACK_IMPORTED_MODULE_5__["Animation"].ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction); + } + this._betaIsAnimating = true; + var animatable = _Animations_animation__WEBPACK_IMPORTED_MODULE_5__["Animation"].TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime); + if (animatable) { + this._animatables.push(animatable); + } + // sets the radius and lower radius bounds + // Small delta ensures camera is not always at lower zoom limit. + var radius = 0; + if (this._mode === FramingBehavior.FitFrustumSidesMode) { + var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld); + if (this.autoCorrectCameraLimitsAndSensibility) { + this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ; + } + radius = position; + } + else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) { + radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld); + if (this.autoCorrectCameraLimitsAndSensibility && this._attachedCamera.lowerRadiusLimit === null) { + this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ; + } + } + // Set sensibilities + if (this.autoCorrectCameraLimitsAndSensibility) { + var extend = maximumWorld.subtract(minimumWorld).length(); + this._attachedCamera.panningSensibility = 5000 / extend; + this._attachedCamera.wheelPrecision = 100 / radius; + } + // transition to new radius + if (!this._radiusTransition) { + this._radiusTransition = _Animations_animation__WEBPACK_IMPORTED_MODULE_5__["Animation"].CreateAnimation("radius", _Animations_animation__WEBPACK_IMPORTED_MODULE_5__["Animation"].ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction); + } + animatable = _Animations_animation__WEBPACK_IMPORTED_MODULE_5__["Animation"].TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () { + _this.stopAllAnimations(); + if (onAnimationEnd) { + onAnimationEnd(); + } + if (_this._attachedCamera && _this._attachedCamera.useInputToRestoreState) { + _this._attachedCamera.storeState(); + } + }); + if (animatable) { + this._animatables.push(animatable); + } + }; + /** + * Calculates the lowest radius for the camera based on the bounding box of the mesh. + * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary + * frustum width. + * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order + * to fully enclose the mesh in the viewing frustum. + */ + FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) { + var size = maximumWorld.subtract(minimumWorld); + var boxVectorGlobalDiagonal = size.length(); + var frustumSlope = this._getFrustumSlope(); + // Formula for setting distance + // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene) + var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5; + // Horizon distance + var radius = radiusWithoutFraming * this._radiusScale; + var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x)); + var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y)); + var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum); + var camera = this._attachedCamera; + if (!camera) { + return 0; + } + if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) { + // Don't exceed the requested limit + distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance; + } + // Don't exceed the upper radius limit + if (camera.upperRadiusLimit) { + distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance; + } + return distance; + }; + /** + * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera + * is automatically returned to its default position (expected to be above ground plane). + */ + FramingBehavior.prototype._maintainCameraAboveGround = function () { + var _this = this; + if (this._elevationReturnTime < 0) { + return; + } + var timeSinceInteraction = _Misc_precisionDate__WEBPACK_IMPORTED_MODULE_3__["PrecisionDate"].Now - this._lastInteractionTime; + var defaultBeta = Math.PI * 0.5 - this._defaultElevation; + var limitBeta = Math.PI * 0.5; + // Bring the camera back up if below the ground plane + if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) { + this._betaIsAnimating = true; + //Transition to new position + this.stopAllAnimations(); + if (!this._betaTransition) { + this._betaTransition = _Animations_animation__WEBPACK_IMPORTED_MODULE_5__["Animation"].CreateAnimation("beta", _Animations_animation__WEBPACK_IMPORTED_MODULE_5__["Animation"].ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction); + } + var animatabe = _Animations_animation__WEBPACK_IMPORTED_MODULE_5__["Animation"].TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () { + _this._clearAnimationLocks(); + _this.stopAllAnimations(); + }); + if (animatabe) { + this._animatables.push(animatabe); + } + } + }; + /** + * Returns the frustum slope based on the canvas ratio and camera FOV + * @returns The frustum slope represented as a Vector2 with X and Y slopes + */ + FramingBehavior.prototype._getFrustumSlope = function () { + // Calculate the viewport ratio + // Aspect Ratio is Height/Width. + var camera = this._attachedCamera; + if (!camera) { + return _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector2"].Zero(); + } + var engine = camera.getScene().getEngine(); + var aspectRatio = engine.getAspectRatio(camera); + // Camera FOV is the vertical field of view (top-bottom) in radians. + // Slope of the frustum top/bottom planes in view space, relative to the forward vector. + var frustumSlopeY = Math.tan(camera.fov / 2); + // Slope of the frustum left/right planes in view space, relative to the forward vector. + // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit + // along the forward vector. + var frustumSlopeX = frustumSlopeY * aspectRatio; + return new _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector2"](frustumSlopeX, frustumSlopeY); + }; + /** + * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties. + */ + FramingBehavior.prototype._clearAnimationLocks = function () { + this._betaIsAnimating = false; + }; + /** + * Applies any current user interaction to the camera. Takes into account maximum alpha rotation. + */ + FramingBehavior.prototype._applyUserInteraction = function () { + if (this.isUserIsMoving) { + this._lastInteractionTime = _Misc_precisionDate__WEBPACK_IMPORTED_MODULE_3__["PrecisionDate"].Now; + this.stopAllAnimations(); + this._clearAnimationLocks(); + } + }; + /** + * Stops and removes all animations that have been applied to the camera + */ + FramingBehavior.prototype.stopAllAnimations = function () { + if (this._attachedCamera) { + this._attachedCamera.animations = []; + } + while (this._animatables.length) { + if (this._animatables[0]) { + this._animatables[0].onAnimationEnd = null; + this._animatables[0].stop(); + } + this._animatables.shift(); + } + }; + Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", { + /** + * Gets a value indicating if the user is moving the camera + */ + get: function () { + if (!this._attachedCamera) { + return false; + } + return this._attachedCamera.inertialAlphaOffset !== 0 || + this._attachedCamera.inertialBetaOffset !== 0 || + this._attachedCamera.inertialRadiusOffset !== 0 || + this._attachedCamera.inertialPanningX !== 0 || + this._attachedCamera.inertialPanningY !== 0 || + this._isPointerDown; + }, + enumerable: true, + configurable: true + }); + /** + * The easing function used by animations + */ + FramingBehavior.EasingFunction = new _Animations_easing__WEBPACK_IMPORTED_MODULE_0__["ExponentialEase"](); + /** + * The easing mode used by animations + */ + FramingBehavior.EasingMode = _Animations_easing__WEBPACK_IMPORTED_MODULE_0__["EasingFunction"].EASINGMODE_EASEINOUT; + // Statics + /** + * The camera can move all the way towards the mesh. + */ + FramingBehavior.IgnoreBoundsSizeMode = 0; + /** + * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides + */ + FramingBehavior.FitFrustumSidesMode = 1; + return FramingBehavior; +}()); + + + +/***/ }), + +/***/ "./Behaviors/Cameras/index.ts": +/*!************************************!*\ + !*** ./Behaviors/Cameras/index.ts ***! + \************************************/ +/*! exports provided: AutoRotationBehavior, BouncingBehavior, FramingBehavior */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _autoRotationBehavior__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./autoRotationBehavior */ "./Behaviors/Cameras/autoRotationBehavior.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AutoRotationBehavior", function() { return _autoRotationBehavior__WEBPACK_IMPORTED_MODULE_0__["AutoRotationBehavior"]; }); + +/* harmony import */ var _bouncingBehavior__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./bouncingBehavior */ "./Behaviors/Cameras/bouncingBehavior.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BouncingBehavior", function() { return _bouncingBehavior__WEBPACK_IMPORTED_MODULE_1__["BouncingBehavior"]; }); + +/* harmony import */ var _framingBehavior__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./framingBehavior */ "./Behaviors/Cameras/framingBehavior.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FramingBehavior", function() { return _framingBehavior__WEBPACK_IMPORTED_MODULE_2__["FramingBehavior"]; }); + + + + + + +/***/ }), + +/***/ "./Behaviors/Meshes/attachToBoxBehavior.ts": +/*!*************************************************!*\ + !*** ./Behaviors/Meshes/attachToBoxBehavior.ts ***! + \*************************************************/ +/*! exports provided: AttachToBoxBehavior */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AttachToBoxBehavior", function() { return AttachToBoxBehavior; }); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); + +/** + * @hidden + */ +var FaceDirectionInfo = /** @class */ (function () { + function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) { + if (rotatedDirection === void 0) { rotatedDirection = new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"](); } + if (diff === void 0) { diff = 0; } + if (ignore === void 0) { ignore = false; } + this.direction = direction; + this.rotatedDirection = rotatedDirection; + this.diff = diff; + this.ignore = ignore; + } + return FaceDirectionInfo; +}()); +/** + * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera + */ +var AttachToBoxBehavior = /** @class */ (function () { + /** + * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera + * @param ui The transform node that should be attched to the mesh + */ + function AttachToBoxBehavior(ui) { + this.ui = ui; + /** + * The name of the behavior + */ + this.name = "AttachToBoxBehavior"; + /** + * The distance away from the face of the mesh that the UI should be attached to (default: 0.15) + */ + this.distanceAwayFromFace = 0.15; + /** + * The distance from the bottom of the face that the UI should be attached to (default: 0.15) + */ + this.distanceAwayFromBottomOfFace = 0.15; + this._faceVectors = [new FaceDirectionInfo(_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Up()), new FaceDirectionInfo(_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Down()), new FaceDirectionInfo(_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Left()), new FaceDirectionInfo(_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Right()), new FaceDirectionInfo(_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Forward()), new FaceDirectionInfo(_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Forward().scaleInPlace(-1))]; + this._tmpMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"](); + this._tmpVector = new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"](); + this._zeroVector = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(); + this._lookAtTmpMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"](); + /* Does nothing */ + } + /** + * Initializes the behavior + */ + AttachToBoxBehavior.prototype.init = function () { + /* Does nothing */ + }; + AttachToBoxBehavior.prototype._closestFace = function (targetDirection) { + var _this = this; + // Go over each face and calculate the angle between the face's normal and targetDirection + this._faceVectors.forEach(function (v) { + if (!_this._target.rotationQuaternion) { + _this._target.rotationQuaternion = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z); + } + _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix); + _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection); + v.diff = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].GetAngleBetweenVectors(v.rotatedDirection, targetDirection, _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Cross(v.rotatedDirection, targetDirection)); + }); + // Return the face information of the one with the normal closeset to target direction + return this._faceVectors.reduce(function (min, p) { + if (min.ignore) { + return p; + } + else if (p.ignore) { + return min; + } + else { + return min.diff < p.diff ? min : p; + } + }, this._faceVectors[0]); + }; + AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) { + if (up === void 0) { up = new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"](0, 1, 0); } + _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix); + this._lookAtTmpMatrix.invert(); + _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].FromRotationMatrixToRef(this._lookAtTmpMatrix, ref); + }; + /** + * Attaches the AttachToBoxBehavior to the passed in mesh + * @param target The mesh that the specified node will be attached to + */ + AttachToBoxBehavior.prototype.attach = function (target) { + var _this = this; + this._target = target; + this._scene = this._target.getScene(); + // Every frame, update the app bars position + this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () { + if (!_this._scene.activeCamera) { + return; + } + // Find the face closest to the cameras position + var cameraPos = _this._scene.activeCamera.position; + if (_this._scene.activeCamera.devicePosition) { + cameraPos = _this._scene.activeCamera.devicePosition; + } + var facing = _this._closestFace(cameraPos.subtract(target.position)); + if (_this._scene.activeCamera.leftCamera) { + _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix); + } + else { + _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix); + } + // Get camera up direction + _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].TransformCoordinatesToRef(_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Up(), _this._tmpMatrix, _this._tmpVector); + // Ignore faces to not select a parrelel face for the up vector of the UI + _this._faceVectors.forEach(function (v) { + if (facing.direction.x && v.direction.x) { + v.ignore = true; + } + if (facing.direction.y && v.direction.y) { + v.ignore = true; + } + if (facing.direction.z && v.direction.z) { + v.ignore = true; + } + }); + var facingUp = _this._closestFace(_this._tmpVector); + // Unignore faces + _this._faceVectors.forEach(function (v) { + v.ignore = false; + }); + // Position the app bar on that face + _this.ui.position.copyFrom(target.position); + if (facing.direction.x) { + facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector); + _this.ui.position.addInPlace(_this._tmpVector); + } + if (facing.direction.y) { + facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector); + _this.ui.position.addInPlace(_this._tmpVector); + } + if (facing.direction.z) { + facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector); + _this.ui.position.addInPlace(_this._tmpVector); + } + // Rotate to be oriented properly to the camera + if (!_this.ui.rotationQuaternion) { + _this.ui.rotationQuaternion = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z); + } + facing.rotatedDirection.scaleToRef(-1, _this._tmpVector); + _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion); + // Place ui the correct distance from the bottom of the mesh + if (facingUp.direction.x) { + _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector); + } + if (facingUp.direction.y) { + _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector); + } + if (facingUp.direction.z) { + _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector); + } + _this.ui.position.addInPlace(_this._tmpVector); + }); + }; + /** + * Detaches the behavior from the mesh + */ + AttachToBoxBehavior.prototype.detach = function () { + this._scene.onBeforeRenderObservable.remove(this._onRenderObserver); + }; + return AttachToBoxBehavior; +}()); + + + +/***/ }), + +/***/ "./Behaviors/Meshes/fadeInOutBehavior.ts": +/*!***********************************************!*\ + !*** ./Behaviors/Meshes/fadeInOutBehavior.ts ***! + \***********************************************/ +/*! exports provided: FadeInOutBehavior */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FadeInOutBehavior", function() { return FadeInOutBehavior; }); +/** + * A behavior that when attached to a mesh will allow the mesh to fade in and out + */ +var FadeInOutBehavior = /** @class */ (function () { + /** + * Instatiates the FadeInOutBehavior + */ + function FadeInOutBehavior() { + var _this = this; + /** + * Time in milliseconds to delay before fading in (Default: 0) + */ + this.delay = 0; + /** + * Time in milliseconds for the mesh to fade in (Default: 300) + */ + this.fadeInTime = 300; + this._millisecondsPerFrame = 1000 / 60; + this._hovered = false; + this._hoverValue = 0; + this._ownerNode = null; + this._update = function () { + if (_this._ownerNode) { + _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame; + _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime); + if (_this._ownerNode.visibility > 1) { + _this._setAllVisibility(_this._ownerNode, 1); + _this._hoverValue = _this.fadeInTime + _this.delay; + return; + } + else if (_this._ownerNode.visibility < 0) { + _this._setAllVisibility(_this._ownerNode, 0); + if (_this._hoverValue < 0) { + _this._hoverValue = 0; + return; + } + } + setTimeout(_this._update, _this._millisecondsPerFrame); + } + }; + } + Object.defineProperty(FadeInOutBehavior.prototype, "name", { + /** + * The name of the behavior + */ + get: function () { + return "FadeInOut"; + }, + enumerable: true, + configurable: true + }); + /** + * Initializes the behavior + */ + FadeInOutBehavior.prototype.init = function () { + }; + /** + * Attaches the fade behavior on the passed in mesh + * @param ownerNode The mesh that will be faded in/out once attached + */ + FadeInOutBehavior.prototype.attach = function (ownerNode) { + this._ownerNode = ownerNode; + this._setAllVisibility(this._ownerNode, 0); + }; + /** + * Detaches the behavior from the mesh + */ + FadeInOutBehavior.prototype.detach = function () { + this._ownerNode = null; + }; + /** + * Triggers the mesh to begin fading in or out + * @param value if the object should fade in or out (true to fade in) + */ + FadeInOutBehavior.prototype.fadeIn = function (value) { + this._hovered = value; + this._update(); + }; + FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) { + var _this = this; + mesh.visibility = value; + mesh.getChildMeshes().forEach(function (c) { + _this._setAllVisibility(c, value); + }); + }; + return FadeInOutBehavior; +}()); + + + +/***/ }), + +/***/ "./Behaviors/Meshes/index.ts": +/*!***********************************!*\ + !*** ./Behaviors/Meshes/index.ts ***! + \***********************************/ +/*! exports provided: AttachToBoxBehavior, FadeInOutBehavior, MultiPointerScaleBehavior, PointerDragBehavior, SixDofDragBehavior */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _attachToBoxBehavior__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./attachToBoxBehavior */ "./Behaviors/Meshes/attachToBoxBehavior.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AttachToBoxBehavior", function() { return _attachToBoxBehavior__WEBPACK_IMPORTED_MODULE_0__["AttachToBoxBehavior"]; }); + +/* harmony import */ var _fadeInOutBehavior__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./fadeInOutBehavior */ "./Behaviors/Meshes/fadeInOutBehavior.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FadeInOutBehavior", function() { return _fadeInOutBehavior__WEBPACK_IMPORTED_MODULE_1__["FadeInOutBehavior"]; }); + +/* harmony import */ var _multiPointerScaleBehavior__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./multiPointerScaleBehavior */ "./Behaviors/Meshes/multiPointerScaleBehavior.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MultiPointerScaleBehavior", function() { return _multiPointerScaleBehavior__WEBPACK_IMPORTED_MODULE_2__["MultiPointerScaleBehavior"]; }); + +/* harmony import */ var _pointerDragBehavior__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./pointerDragBehavior */ "./Behaviors/Meshes/pointerDragBehavior.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointerDragBehavior", function() { return _pointerDragBehavior__WEBPACK_IMPORTED_MODULE_3__["PointerDragBehavior"]; }); + +/* harmony import */ var _sixDofDragBehavior__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./sixDofDragBehavior */ "./Behaviors/Meshes/sixDofDragBehavior.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SixDofDragBehavior", function() { return _sixDofDragBehavior__WEBPACK_IMPORTED_MODULE_4__["SixDofDragBehavior"]; }); + + + + + + + + +/***/ }), + +/***/ "./Behaviors/Meshes/multiPointerScaleBehavior.ts": +/*!*******************************************************!*\ + !*** ./Behaviors/Meshes/multiPointerScaleBehavior.ts ***! + \*******************************************************/ +/*! exports provided: MultiPointerScaleBehavior */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MultiPointerScaleBehavior", function() { return MultiPointerScaleBehavior; }); +/* harmony import */ var _pointerDragBehavior__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./pointerDragBehavior */ "./Behaviors/Meshes/pointerDragBehavior.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); + + +/** + * A behavior that when attached to a mesh will allow the mesh to be scaled + */ +var MultiPointerScaleBehavior = /** @class */ (function () { + /** + * Instantiate a new behavior that when attached to a mesh will allow the mesh to be scaled + */ + function MultiPointerScaleBehavior() { + this._startDistance = 0; + this._initialScale = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"](0, 0, 0); + this._targetScale = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"](0, 0, 0); + this._sceneRenderObserver = null; + this._dragBehaviorA = new _pointerDragBehavior__WEBPACK_IMPORTED_MODULE_0__["PointerDragBehavior"]({}); + this._dragBehaviorA.moveAttached = false; + this._dragBehaviorB = new _pointerDragBehavior__WEBPACK_IMPORTED_MODULE_0__["PointerDragBehavior"]({}); + this._dragBehaviorB.moveAttached = false; + } + Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", { + /** + * The name of the behavior + */ + get: function () { + return "MultiPointerScale"; + }, + enumerable: true, + configurable: true + }); + /** + * Initializes the behavior + */ + MultiPointerScaleBehavior.prototype.init = function () { }; + MultiPointerScaleBehavior.prototype._getCurrentDistance = function () { + return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length(); + }; + /** + * Attaches the scale behavior the passed in mesh + * @param ownerNode The mesh that will be scaled around once attached + */ + MultiPointerScaleBehavior.prototype.attach = function (ownerNode) { + var _this = this; + this._ownerNode = ownerNode; + // Create 2 drag behaviors such that each will only be triggered by a separate pointer + this._dragBehaviorA.onDragStartObservable.add(function (e) { + if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) { + if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) { + _this._dragBehaviorA.releaseDrag(); + } + else { + _this._initialScale.copyFrom(ownerNode.scaling); + _this._startDistance = _this._getCurrentDistance(); + } + } + }); + this._dragBehaviorB.onDragStartObservable.add(function (e) { + if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) { + if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) { + _this._dragBehaviorB.releaseDrag(); + } + else { + _this._initialScale.copyFrom(ownerNode.scaling); + _this._startDistance = _this._getCurrentDistance(); + } + } + }); + // Once both drag behaviors are active scale based on the distance between the two pointers + [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) { + behavior.onDragObservable.add(function () { + if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) { + var ratio = _this._getCurrentDistance() / _this._startDistance; + _this._initialScale.scaleToRef(ratio, _this._targetScale); + } + }); + }); + ownerNode.addBehavior(this._dragBehaviorA); + ownerNode.addBehavior(this._dragBehaviorB); + // On every frame move towards target scaling to avoid jitter caused by vr controllers + this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () { + if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) { + var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1); + if (change.length() > 0.01) { + ownerNode.scaling.addInPlace(change); + } + } + }); + }; + /** + * Detaches the behavior from the mesh + */ + MultiPointerScaleBehavior.prototype.detach = function () { + var _this = this; + this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver); + [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) { + behavior.onDragStartObservable.clear(); + behavior.onDragObservable.clear(); + _this._ownerNode.removeBehavior(behavior); + }); + }; + return MultiPointerScaleBehavior; +}()); + + + +/***/ }), + +/***/ "./Behaviors/Meshes/pointerDragBehavior.ts": +/*!*************************************************!*\ + !*** ./Behaviors/Meshes/pointerDragBehavior.ts ***! + \*************************************************/ +/*! exports provided: PointerDragBehavior */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PointerDragBehavior", function() { return PointerDragBehavior; }); +/* harmony import */ var _Meshes_mesh__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Meshes/mesh */ "./Meshes/mesh.ts"); +/* harmony import */ var _scene__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../scene */ "./scene.ts"); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Events/pointerEvents */ "./Events/pointerEvents.ts"); +/* harmony import */ var _Culling_ray__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Culling/ray */ "./Culling/ray.ts"); +/* harmony import */ var _Misc_pivotTools__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../Misc/pivotTools */ "./Misc/pivotTools.ts"); +/* harmony import */ var _Meshes_Builders_planeBuilder__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../Meshes/Builders/planeBuilder */ "./Meshes/Builders/planeBuilder.ts"); + + + + + + + + +/** + * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events + */ +var PointerDragBehavior = /** @class */ (function () { + /** + * Creates a pointer drag behavior that can be attached to a mesh + * @param options The drag axis or normal of the plane that will be dragged across. If no options are specified the drag plane will always face the ray's origin (eg. camera) + */ + function PointerDragBehavior(options) { + this._useAlternatePickedPointAboveMaxDragAngleDragSpeed = -1.1; + /** + * The maximum tolerated angle between the drag plane and dragging pointer rays to trigger pointer events. Set to 0 to allow any angle (default: 0) + */ + this.maxDragAngle = 0; + /** + * @hidden + */ + this._useAlternatePickedPointAboveMaxDragAngle = false; + /** + * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active) + */ + this.currentDraggingPointerID = -1; + /** + * If the behavior is currently in a dragging state + */ + this.dragging = false; + /** + * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2) + */ + this.dragDeltaRatio = 0.2; + /** + * If the drag plane orientation should be updated during the dragging (Default: true) + */ + this.updateDragPlane = true; + // Debug mode will display drag planes to help visualize behavior + this._debugMode = false; + this._moving = false; + /** + * Fires each time the attached mesh is dragged with the pointer + * * delta between last drag position and current drag position in world space + * * dragDistance along the drag axis + * * dragPlaneNormal normal of the current drag plane used during the drag + * * dragPlanePoint in world space where the drag intersects the drag plane + */ + this.onDragObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); + /** + * Fires each time a drag begins (eg. mouse down on mesh) + */ + this.onDragStartObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); + /** + * Fires each time a drag ends (eg. mouse release after drag) + */ + this.onDragEndObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); + /** + * If the attached mesh should be moved when dragged + */ + this.moveAttached = true; + /** + * If the drag behavior will react to drag events (Default: true) + */ + this.enabled = true; + /** + * If camera controls should be detached during the drag + */ + this.detachCameraControls = true; + /** + * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true) + */ + this.useObjectOrienationForDragging = true; + /** + * Predicate to determine if it is valid to move the object to a new position when it is moved + */ + this.validateDrag = function (targetPosition) { return true; }; + this._tmpVector = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0); + this._alternatePickedPoint = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0); + this._worldDragAxis = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0); + this._targetPosition = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0); + this._attachedElement = null; + this._startDragRay = new _Culling_ray__WEBPACK_IMPORTED_MODULE_5__["Ray"](new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](), new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"]()); + this._lastPointerRay = {}; + this._dragDelta = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](); + // Variables to avoid instantiation in the below method + this._pointA = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0); + this._pointB = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0); + this._pointC = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0); + this._lineA = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0); + this._lineB = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0); + this._localAxis = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0); + this._lookAt = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0); + this._options = options ? options : {}; + var optionCount = 0; + if (this._options.dragAxis) { + optionCount++; + } + if (this._options.dragPlaneNormal) { + optionCount++; + } + if (optionCount > 1) { + throw "Multiple drag modes specified in dragBehavior options. Only one expected"; + } + } + Object.defineProperty(PointerDragBehavior.prototype, "name", { + /** + * The name of the behavior + */ + get: function () { + return "PointerDrag"; + }, + enumerable: true, + configurable: true + }); + /** + * Initializes the behavior + */ + PointerDragBehavior.prototype.init = function () { }; + /** + * Attaches the drag behavior the passed in mesh + * @param ownerNode The mesh that will be dragged around once attached + */ + PointerDragBehavior.prototype.attach = function (ownerNode) { + var _this = this; + this._scene = ownerNode.getScene(); + this.attachedNode = ownerNode; + // Initialize drag plane to not interfere with existing scene + if (!PointerDragBehavior._planeScene) { + if (this._debugMode) { + PointerDragBehavior._planeScene = this._scene; + } + else { + PointerDragBehavior._planeScene = new _scene__WEBPACK_IMPORTED_MODULE_1__["Scene"](this._scene.getEngine(), { virtual: true }); + PointerDragBehavior._planeScene.detachControl(); + this._scene.onDisposeObservable.addOnce(function () { + PointerDragBehavior._planeScene.dispose(); + PointerDragBehavior._planeScene = null; + }); + } + } + this._dragPlane = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_0__["Mesh"].CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, _Meshes_mesh__WEBPACK_IMPORTED_MODULE_0__["Mesh"].DOUBLESIDE); + // State of the drag + this.lastDragPosition = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0); + var pickPredicate = function (m) { + return _this.attachedNode == m || m.isDescendantOf(_this.attachedNode); + }; + this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) { + if (!_this.enabled) { + return; + } + if (pointerInfo.type == _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_4__["PointerEventTypes"].POINTERDOWN) { + if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) { + _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint); + } + } + else if (pointerInfo.type == _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_4__["PointerEventTypes"].POINTERUP) { + if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) { + _this.releaseDrag(); + } + } + else if (pointerInfo.type == _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_4__["PointerEventTypes"].POINTERMOVE) { + var pointerId = pointerInfo.event.pointerId; + // If drag was started with anyMouseID specified, set pointerID to the next mouse that moved + if (_this.currentDraggingPointerID === PointerDragBehavior._AnyMouseID && pointerId !== PointerDragBehavior._AnyMouseID && pointerInfo.event.pointerType == "mouse") { + if (_this._lastPointerRay[_this.currentDraggingPointerID]) { + _this._lastPointerRay[pointerId] = _this._lastPointerRay[_this.currentDraggingPointerID]; + delete _this._lastPointerRay[_this.currentDraggingPointerID]; + } + _this.currentDraggingPointerID = pointerId; + } + // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag() + if (!_this._lastPointerRay[pointerId]) { + _this._lastPointerRay[pointerId] = new _Culling_ray__WEBPACK_IMPORTED_MODULE_5__["Ray"](new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](), new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"]()); + } + if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) { + _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin); + _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction); + if (_this.currentDraggingPointerID == pointerId && _this.dragging) { + _this._moveDrag(pointerInfo.pickInfo.ray); + } + } + } + }); + this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () { + if (_this._moving && _this.moveAttached) { + _Misc_pivotTools__WEBPACK_IMPORTED_MODULE_6__["PivotTools"]._RemoveAndStorePivotPoint(_this.attachedNode); + // Slowly move mesh to avoid jitter + _this._targetPosition.subtractToRef((_this.attachedNode).absolutePosition, _this._tmpVector); + _this._tmpVector.scaleInPlace(_this.dragDeltaRatio); + (_this.attachedNode).getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector); + if (_this.validateDrag(_this._tmpVector)) { + (_this.attachedNode).setAbsolutePosition(_this._tmpVector); + } + _Misc_pivotTools__WEBPACK_IMPORTED_MODULE_6__["PivotTools"]._RestorePivotPoint(_this.attachedNode); + } + }); + }; + /** + * Force relase the drag action by code. + */ + PointerDragBehavior.prototype.releaseDrag = function () { + this.dragging = false; + this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID }); + this.currentDraggingPointerID = -1; + this._moving = false; + // Reattach camera controls + if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) { + this._scene.activeCamera.attachControl(this._attachedElement, true); + } + }; + /** + * Simulates the start of a pointer drag event on the behavior + * @param pointerId pointerID of the pointer that should be simulated (Default: Any mouse pointer ID) + * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh) + * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position) + */ + PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) { + if (pointerId === void 0) { pointerId = PointerDragBehavior._AnyMouseID; } + this._startDrag(pointerId, fromRay, startPickedPoint); + var lastRay = this._lastPointerRay[pointerId]; + if (pointerId === PointerDragBehavior._AnyMouseID) { + lastRay = this._lastPointerRay[Object.keys(this._lastPointerRay)[0]]; + } + if (lastRay) { + // if there was a last pointer ray drag the object there + this._moveDrag(lastRay); + } + }; + PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) { + if (!this._scene.activeCamera || this.dragging || !this.attachedNode) { + return; + } + _Misc_pivotTools__WEBPACK_IMPORTED_MODULE_6__["PivotTools"]._RemoveAndStorePivotPoint(this.attachedNode); + // Create start ray from the camera to the object + if (fromRay) { + this._startDragRay.direction.copyFrom(fromRay.direction); + this._startDragRay.origin.copyFrom(fromRay.origin); + } + else { + this._startDragRay.origin.copyFrom(this._scene.activeCamera.position); + this.attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector); + this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction); + } + this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector); + var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay); + if (pickedPoint) { + this.dragging = true; + this.currentDraggingPointerID = pointerId; + this.lastDragPosition.copyFrom(pickedPoint); + this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID }); + this._targetPosition.copyFrom((this.attachedNode).absolutePosition); + // Detatch camera controls + if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) { + if (this._scene.activeCamera.inputs.attachedElement) { + this._attachedElement = this._scene.activeCamera.inputs.attachedElement; + this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement); + } + else { + this._attachedElement = null; + } + } + } + _Misc_pivotTools__WEBPACK_IMPORTED_MODULE_6__["PivotTools"]._RestorePivotPoint(this.attachedNode); + }; + PointerDragBehavior.prototype._moveDrag = function (ray) { + this._moving = true; + var pickedPoint = this._pickWithRayOnDragPlane(ray); + if (pickedPoint) { + if (this.updateDragPlane) { + this._updateDragPlanePosition(ray, pickedPoint); + } + var dragLength = 0; + // depending on the drag mode option drag accordingly + if (this._options.dragAxis) { + // Convert local drag axis to world + _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformCoordinatesToRef(this._options.dragAxis, this.attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis); + // Project delta drag from the drag plane onto the drag axis + pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector); + dragLength = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Dot(this._tmpVector, this._worldDragAxis); + this._worldDragAxis.scaleToRef(dragLength, this._dragDelta); + } + else { + dragLength = this._dragDelta.length(); + pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta); + } + this._targetPosition.addInPlace(this._dragDelta); + this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID }); + this.lastDragPosition.copyFrom(pickedPoint); + } + }; + PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) { + var _this = this; + if (!ray) { + return null; + } + // Calculate angle between plane normal and ray + var angle = Math.acos(_Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Dot(this._dragPlane.forward, ray.direction)); + // Correct if ray is casted from oposite side + if (angle > Math.PI / 2) { + angle = Math.PI - angle; + } + // If the angle is too perpendicular to the plane pick another point on the plane where it is looking + if (this.maxDragAngle > 0 && angle > this.maxDragAngle) { + if (this._useAlternatePickedPointAboveMaxDragAngle) { + // Invert ray direction along the towards object axis + this._tmpVector.copyFrom(ray.direction); + (this.attachedNode).absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint); + this._alternatePickedPoint.normalize(); + this._alternatePickedPoint.scaleInPlace(this._useAlternatePickedPointAboveMaxDragAngleDragSpeed * _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Dot(this._alternatePickedPoint, this._tmpVector)); + this._tmpVector.addInPlace(this._alternatePickedPoint); + // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point + var dot = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Dot(this._dragPlane.forward, this._tmpVector); + this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint); + this._alternatePickedPoint.addInPlace(this._tmpVector); + this._alternatePickedPoint.addInPlace((this.attachedNode).absolutePosition); + return this._alternatePickedPoint; + } + else { + return null; + } + } + var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; }); + if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) { + return pickResult.pickedPoint; + } + else { + return null; + } + }; + // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera + PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) { + this._pointA.copyFrom(dragPlanePosition); + if (this._options.dragAxis) { + this.useObjectOrienationForDragging ? _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformCoordinatesToRef(this._options.dragAxis, this.attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis); + // Calculate plane normal in direction of camera but perpendicular to drag axis + this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis + ray.origin.subtractToRef(this._pointA, this._pointC); + this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera + // Get perpendicular line from direction to camera and drag axis + this._pointB.subtractToRef(this._pointA, this._lineA); + this._pointC.subtractToRef(this._pointA, this._lineB); + _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].CrossToRef(this._lineA, this._lineB, this._lookAt); + // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera + _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].CrossToRef(this._lineA, this._lookAt, this._lookAt); + this._lookAt.normalize(); + this._dragPlane.position.copyFrom(this._pointA); + this._pointA.addToRef(this._lookAt, this._lookAt); + this._dragPlane.lookAt(this._lookAt); + } + else if (this._options.dragPlaneNormal) { + this.useObjectOrienationForDragging ? _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformCoordinatesToRef(this._options.dragPlaneNormal, this.attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal); + this._dragPlane.position.copyFrom(this._pointA); + this._pointA.addToRef(this._localAxis, this._lookAt); + this._dragPlane.lookAt(this._lookAt); + } + else { + this._dragPlane.position.copyFrom(this._pointA); + this._dragPlane.lookAt(ray.origin); + } + // Update the position of the drag plane so it doesn't get out of sync with the node (eg. when moving back and forth quickly) + this._dragPlane.position.copyFrom(this.attachedNode.absolutePosition); + this._dragPlane.computeWorldMatrix(true); + }; + /** + * Detaches the behavior from the mesh + */ + PointerDragBehavior.prototype.detach = function () { + if (this._pointerObserver) { + this._scene.onPointerObservable.remove(this._pointerObserver); + } + if (this._beforeRenderObserver) { + this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver); + } + this.releaseDrag(); + }; + PointerDragBehavior._AnyMouseID = -2; + return PointerDragBehavior; +}()); + + + +/***/ }), + +/***/ "./Behaviors/Meshes/sixDofDragBehavior.ts": +/*!************************************************!*\ + !*** ./Behaviors/Meshes/sixDofDragBehavior.ts ***! + \************************************************/ +/*! exports provided: SixDofDragBehavior */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SixDofDragBehavior", function() { return SixDofDragBehavior; }); +/* harmony import */ var _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Meshes/abstractMesh */ "./Meshes/abstractMesh.ts"); +/* harmony import */ var _scene__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../scene */ "./scene.ts"); +/* harmony import */ var _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Events/pointerEvents */ "./Events/pointerEvents.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Cameras/camera */ "./Cameras/camera.ts"); +/* harmony import */ var _Misc_pivotTools__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../Misc/pivotTools */ "./Misc/pivotTools.ts"); + + + + + + + +/** + * A behavior that when attached to a mesh will allow the mesh to be dragged around based on directions and origin of the pointer's ray + */ +var SixDofDragBehavior = /** @class */ (function () { + /** + * Instantiates a behavior that when attached to a mesh will allow the mesh to be dragged around based on directions and origin of the pointer's ray + */ + function SixDofDragBehavior() { + this._sceneRenderObserver = null; + this._targetPosition = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0); + this._moving = false; + this._startingOrientation = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"](); + /** + * How much faster the object should move when the controller is moving towards it. This is useful to bring objects that are far away from the user to them faster. Set this to 0 to avoid any speed increase. (Default: 3) + */ + this.zDragFactor = 3; + /** + * If the object should rotate to face the drag origin + */ + this.rotateDraggedObject = true; + /** + * If the behavior is currently in a dragging state + */ + this.dragging = false; + /** + * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2) + */ + this.dragDeltaRatio = 0.2; + /** + * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active) + */ + this.currentDraggingPointerID = -1; + /** + * If camera controls should be detached during the drag + */ + this.detachCameraControls = true; + /** + * Fires each time a drag starts + */ + this.onDragStartObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_4__["Observable"](); + /** + * Fires each time a drag ends (eg. mouse release after drag) + */ + this.onDragEndObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_4__["Observable"](); + } + Object.defineProperty(SixDofDragBehavior.prototype, "name", { + /** + * The name of the behavior + */ + get: function () { + return "SixDofDrag"; + }, + enumerable: true, + configurable: true + }); + /** + * Initializes the behavior + */ + SixDofDragBehavior.prototype.init = function () { }; + Object.defineProperty(SixDofDragBehavior.prototype, "_pointerCamera", { + /** + * In the case of multiplea active cameras, the cameraToUseForPointers should be used if set instead of active camera + */ + get: function () { + if (this._scene.cameraToUseForPointers) { + return this._scene.cameraToUseForPointers; + } + else { + return this._scene.activeCamera; + } + }, + enumerable: true, + configurable: true + }); + /** + * Attaches the scale behavior the passed in mesh + * @param ownerNode The mesh that will be scaled around once attached + */ + SixDofDragBehavior.prototype.attach = function (ownerNode) { + var _this = this; + this._ownerNode = ownerNode; + this._scene = this._ownerNode.getScene(); + if (!SixDofDragBehavior._virtualScene) { + SixDofDragBehavior._virtualScene = new _scene__WEBPACK_IMPORTED_MODULE_1__["Scene"](this._scene.getEngine()); + SixDofDragBehavior._virtualScene.detachControl(); + this._scene.getEngine().scenes.pop(); + } + var pickedMesh = null; + var lastSixDofOriginPosition = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0); + // Setup virtual meshes to be used for dragging without dirtying the existing scene + this._virtualOriginMesh = new _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_0__["AbstractMesh"]("", SixDofDragBehavior._virtualScene); + this._virtualOriginMesh.rotationQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"](); + this._virtualDragMesh = new _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_0__["AbstractMesh"]("", SixDofDragBehavior._virtualScene); + this._virtualDragMesh.rotationQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"](); + var pickPredicate = function (m) { + return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode); + }; + var attachedElement = null; + this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) { + if (pointerInfo.type == _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_2__["PointerEventTypes"].POINTERDOWN) { + if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) { + if (_this._pointerCamera && _this._pointerCamera.cameraRigMode == _Cameras_camera__WEBPACK_IMPORTED_MODULE_5__["Camera"].RIG_MODE_NONE) { + pointerInfo.pickInfo.ray.origin.copyFrom(_this._pointerCamera.globalPosition); + } + pickedMesh = _this._ownerNode; + _Misc_pivotTools__WEBPACK_IMPORTED_MODULE_6__["PivotTools"]._RemoveAndStorePivotPoint(pickedMesh); + lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin); + // Set position and orientation of the controller + _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin); + _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.add(pointerInfo.pickInfo.ray.direction)); + // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged + _this._virtualOriginMesh.removeChild(_this._virtualDragMesh); + pickedMesh.computeWorldMatrix(); + _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition); + if (!pickedMesh.rotationQuaternion) { + pickedMesh.rotationQuaternion = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z); + } + var oldParent = pickedMesh.parent; + pickedMesh.setParent(null); + _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion); + pickedMesh.setParent(oldParent); + _this._virtualOriginMesh.addChild(_this._virtualDragMesh); + // Update state + _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition); + _this.dragging = true; + _this.currentDraggingPointerID = pointerInfo.event.pointerId; + // Detatch camera controls + if (_this.detachCameraControls && _this._pointerCamera && !_this._pointerCamera.leftCamera) { + if (_this._pointerCamera.inputs.attachedElement) { + attachedElement = _this._pointerCamera.inputs.attachedElement; + _this._pointerCamera.detachControl(_this._pointerCamera.inputs.attachedElement); + } + else { + attachedElement = null; + } + } + _Misc_pivotTools__WEBPACK_IMPORTED_MODULE_6__["PivotTools"]._RestorePivotPoint(pickedMesh); + _this.onDragStartObservable.notifyObservers({}); + } + } + else if (pointerInfo.type == _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_2__["PointerEventTypes"].POINTERUP) { + if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) { + _this.dragging = false; + _this._moving = false; + _this.currentDraggingPointerID = -1; + pickedMesh = null; + _this._virtualOriginMesh.removeChild(_this._virtualDragMesh); + // Reattach camera controls + if (_this.detachCameraControls && attachedElement && _this._pointerCamera && !_this._pointerCamera.leftCamera) { + _this._pointerCamera.attachControl(attachedElement, true); + } + _this.onDragEndObservable.notifyObservers({}); + } + } + else if (pointerInfo.type == _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_2__["PointerEventTypes"].POINTERMOVE) { + if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) { + var zDragFactor = _this.zDragFactor; + if (_this._pointerCamera && _this._pointerCamera.cameraRigMode == _Cameras_camera__WEBPACK_IMPORTED_MODULE_5__["Camera"].RIG_MODE_NONE) { + pointerInfo.pickInfo.ray.origin.copyFrom(_this._pointerCamera.globalPosition); + zDragFactor = 0; + } + // Calculate controller drag distance in controller space + var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition); + lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin); + var localOriginDragDifference = -_Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Dot(originDragDifference, pointerInfo.pickInfo.ray.direction); + _this._virtualOriginMesh.addChild(_this._virtualDragMesh); + // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away + _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z; + if (_this._virtualDragMesh.position.z < 0) { + _this._virtualDragMesh.position.z = 0; + } + // Update the controller position + _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin); + _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.add(pointerInfo.pickInfo.ray.direction)); + _this._virtualOriginMesh.removeChild(_this._virtualDragMesh); + // Move the virtualObjectsPosition into the picked mesh's space if needed + _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition); + if (pickedMesh.parent) { + _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformCoordinatesToRef(_this._targetPosition, _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"].Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition); + } + if (!_this._moving) { + _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion); + } + _this._moving = true; + } + } + }); + var tmpQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"](); + // On every frame move towards target scaling to avoid jitter caused by vr controllers + this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () { + if (_this.dragging && _this._moving && pickedMesh) { + _Misc_pivotTools__WEBPACK_IMPORTED_MODULE_6__["PivotTools"]._RemoveAndStorePivotPoint(pickedMesh); + // Slowly move mesh to avoid jitter + pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio)); + if (_this.rotateDraggedObject) { + // Get change in rotation + tmpQuaternion.copyFrom(_this._startingOrientation); + tmpQuaternion.x = -tmpQuaternion.x; + tmpQuaternion.y = -tmpQuaternion.y; + tmpQuaternion.z = -tmpQuaternion.z; + _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion); + // Convert change in rotation to only y axis rotation + _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion); + tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion); + // Slowly move mesh to avoid jitter + var oldParent = pickedMesh.parent; + // Only rotate the mesh if it's parent has uniform scaling + if (!oldParent || (oldParent.scaling && !oldParent.scaling.isNonUniformWithinEpsilon(0.001))) { + pickedMesh.setParent(null); + _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion); + pickedMesh.setParent(oldParent); + } + } + _Misc_pivotTools__WEBPACK_IMPORTED_MODULE_6__["PivotTools"]._RestorePivotPoint(pickedMesh); + } + }); + }; + /** + * Detaches the behavior from the mesh + */ + SixDofDragBehavior.prototype.detach = function () { + if (this._scene) { + this._scene.onPointerObservable.remove(this._pointerObserver); + } + if (this._ownerNode) { + this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver); + } + if (this._virtualOriginMesh) { + this._virtualOriginMesh.dispose(); + } + if (this._virtualDragMesh) { + this._virtualDragMesh.dispose(); + } + this.onDragEndObservable.clear(); + this.onDragStartObservable.clear(); + }; + return SixDofDragBehavior; +}()); + + + +/***/ }), + +/***/ "./Behaviors/index.ts": +/*!****************************!*\ + !*** ./Behaviors/index.ts ***! + \****************************/ +/*! exports provided: AutoRotationBehavior, BouncingBehavior, FramingBehavior, AttachToBoxBehavior, FadeInOutBehavior, MultiPointerScaleBehavior, PointerDragBehavior, SixDofDragBehavior */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Cameras_index__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Cameras/index */ "./Behaviors/Cameras/index.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AutoRotationBehavior", function() { return _Cameras_index__WEBPACK_IMPORTED_MODULE_0__["AutoRotationBehavior"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BouncingBehavior", function() { return _Cameras_index__WEBPACK_IMPORTED_MODULE_0__["BouncingBehavior"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FramingBehavior", function() { return _Cameras_index__WEBPACK_IMPORTED_MODULE_0__["FramingBehavior"]; }); + +/* harmony import */ var _Meshes_index__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Meshes/index */ "./Behaviors/Meshes/index.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AttachToBoxBehavior", function() { return _Meshes_index__WEBPACK_IMPORTED_MODULE_1__["AttachToBoxBehavior"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FadeInOutBehavior", function() { return _Meshes_index__WEBPACK_IMPORTED_MODULE_1__["FadeInOutBehavior"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MultiPointerScaleBehavior", function() { return _Meshes_index__WEBPACK_IMPORTED_MODULE_1__["MultiPointerScaleBehavior"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointerDragBehavior", function() { return _Meshes_index__WEBPACK_IMPORTED_MODULE_1__["PointerDragBehavior"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SixDofDragBehavior", function() { return _Meshes_index__WEBPACK_IMPORTED_MODULE_1__["SixDofDragBehavior"]; }); + + + + + +/***/ }), + +/***/ "./Bones/bone.ts": +/*!***********************!*\ + !*** ./Bones/bone.ts ***! + \***********************/ +/*! exports provided: Bone */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Bone", function() { return Bone; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/arrayTools */ "./Misc/arrayTools.ts"); +/* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../node */ "./node.ts"); + + + + +/** + * Class used to store bone information + * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons + */ +var Bone = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Bone, _super); + /** + * Create a new bone + * @param name defines the bone name + * @param skeleton defines the parent skeleton + * @param parentBone defines the parent (can be null if the bone is the root) + * @param localMatrix defines the local matrix + * @param restPose defines the rest pose matrix + * @param baseMatrix defines the base matrix + * @param index defines index of the bone in the hiearchy + */ + function Bone( + /** + * defines the bone name + */ + name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) { + if (parentBone === void 0) { parentBone = null; } + if (localMatrix === void 0) { localMatrix = null; } + if (restPose === void 0) { restPose = null; } + if (baseMatrix === void 0) { baseMatrix = null; } + if (index === void 0) { index = null; } + var _this = _super.call(this, name, skeleton.getScene(), false) || this; + _this.name = name; + /** + * Gets the list of child bones + */ + _this.children = new Array(); + /** Gets the animations associated with this bone */ + _this.animations = new Array(); + /** + * @hidden Internal only + * Set this value to map this bone to a different index in the transform matrices + * Set this value to -1 to exclude the bone from the transform matrices + */ + _this._index = null; + _this._absoluteTransform = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"](); + _this._invertedAbsoluteTransform = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"](); + _this._scalingDeterminant = 1; + _this._worldTransform = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"](); + _this._needToDecompose = true; + _this._needToCompose = false; + /** @hidden */ + _this._linkedTransformNode = null; + /** @hidden */ + _this._waitingTransformNodeId = null; + _this._skeleton = skeleton; + _this._localMatrix = localMatrix ? localMatrix.clone() : _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Identity(); + _this._restPose = restPose ? restPose : _this._localMatrix.clone(); + _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone(); + _this._index = index; + skeleton.bones.push(_this); + _this.setParent(parentBone, false); + if (baseMatrix || localMatrix) { + _this._updateDifferenceMatrix(); + } + return _this; + } + Object.defineProperty(Bone.prototype, "_matrix", { + /** @hidden */ + get: function () { + this._compose(); + return this._localMatrix; + }, + /** @hidden */ + set: function (value) { + this._localMatrix.copyFrom(value); + this._needToDecompose = true; + }, + enumerable: true, + configurable: true + }); + /** + * Gets the current object class name. + * @return the class name + */ + Bone.prototype.getClassName = function () { + return "Bone"; + }; + // Members + /** + * Gets the parent skeleton + * @returns a skeleton + */ + Bone.prototype.getSkeleton = function () { + return this._skeleton; + }; + /** + * Gets parent bone + * @returns a bone or null if the bone is the root of the bone hierarchy + */ + Bone.prototype.getParent = function () { + return this._parent; + }; + /** + * Returns an array containing the root bones + * @returns an array containing the root bones + */ + Bone.prototype.getChildren = function () { + return this.children; + }; + /** + * Sets the parent bone + * @param parent defines the parent (can be null if the bone is the root) + * @param updateDifferenceMatrix defines if the difference matrix must be updated + */ + Bone.prototype.setParent = function (parent, updateDifferenceMatrix) { + if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; } + if (this._parent === parent) { + return; + } + if (this._parent) { + var index = this._parent.children.indexOf(this); + if (index !== -1) { + this._parent.children.splice(index, 1); + } + } + this._parent = parent; + if (this._parent) { + this._parent.children.push(this); + } + if (updateDifferenceMatrix) { + this._updateDifferenceMatrix(); + } + this.markAsDirty(); + }; + /** + * Gets the local matrix + * @returns a matrix + */ + Bone.prototype.getLocalMatrix = function () { + this._compose(); + return this._localMatrix; + }; + /** + * Gets the base matrix (initial matrix which remains unchanged) + * @returns a matrix + */ + Bone.prototype.getBaseMatrix = function () { + return this._baseMatrix; + }; + /** + * Gets the rest pose matrix + * @returns a matrix + */ + Bone.prototype.getRestPose = function () { + return this._restPose; + }; + /** + * Gets a matrix used to store world matrix (ie. the matrix sent to shaders) + */ + Bone.prototype.getWorldMatrix = function () { + return this._worldTransform; + }; + /** + * Sets the local matrix to rest pose matrix + */ + Bone.prototype.returnToRest = function () { + this.updateMatrix(this._restPose.clone()); + }; + /** + * Gets the inverse of the absolute transform matrix. + * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state) + * @returns a matrix + */ + Bone.prototype.getInvertedAbsoluteTransform = function () { + return this._invertedAbsoluteTransform; + }; + /** + * Gets the absolute transform matrix (ie base matrix * parent world matrix) + * @returns a matrix + */ + Bone.prototype.getAbsoluteTransform = function () { + return this._absoluteTransform; + }; + /** + * Links with the given transform node. + * The local matrix of this bone is copied from the transform node every frame. + * @param transformNode defines the transform node to link to + */ + Bone.prototype.linkTransformNode = function (transformNode) { + if (this._linkedTransformNode) { + this._skeleton._numBonesWithLinkedTransformNode--; + } + this._linkedTransformNode = transformNode; + if (this._linkedTransformNode) { + this._skeleton._numBonesWithLinkedTransformNode++; + } + }; + Object.defineProperty(Bone.prototype, "position", { + // Properties (matches AbstractMesh properties) + /** Gets or sets current position (in local space) */ + get: function () { + this._decompose(); + return this._localPosition; + }, + set: function (newPosition) { + this._decompose(); + this._localPosition.copyFrom(newPosition); + this._markAsDirtyAndCompose(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Bone.prototype, "rotation", { + /** Gets or sets current rotation (in local space) */ + get: function () { + return this.getRotation(); + }, + set: function (newRotation) { + this.setRotation(newRotation); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Bone.prototype, "rotationQuaternion", { + /** Gets or sets current rotation quaternion (in local space) */ + get: function () { + this._decompose(); + return this._localRotation; + }, + set: function (newRotation) { + this.setRotationQuaternion(newRotation); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Bone.prototype, "scaling", { + /** Gets or sets current scaling (in local space) */ + get: function () { + return this.getScale(); + }, + set: function (newScaling) { + this.setScale(newScaling); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Bone.prototype, "animationPropertiesOverride", { + /** + * Gets the animation properties override + */ + get: function () { + return this._skeleton.animationPropertiesOverride; + }, + enumerable: true, + configurable: true + }); + // Methods + Bone.prototype._decompose = function () { + if (!this._needToDecompose) { + return; + } + this._needToDecompose = false; + if (!this._localScaling) { + this._localScaling = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); + this._localRotation = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Quaternion"].Zero(); + this._localPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); + } + this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition); + }; + Bone.prototype._compose = function () { + if (!this._needToCompose) { + return; + } + if (!this._localScaling) { + this._needToCompose = false; + return; + } + this._needToCompose = false; + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix); + }; + /** + * Update the base and local matrices + * @param matrix defines the new base or local matrix + * @param updateDifferenceMatrix defines if the difference matrix must be updated + * @param updateLocalMatrix defines if the local matrix should be updated + */ + Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) { + if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; } + if (updateLocalMatrix === void 0) { updateLocalMatrix = true; } + this._baseMatrix.copyFrom(matrix); + if (updateDifferenceMatrix) { + this._updateDifferenceMatrix(); + } + if (updateLocalMatrix) { + this._localMatrix.copyFrom(matrix); + this._markAsDirtyAndDecompose(); + } + else { + this.markAsDirty(); + } + }; + /** @hidden */ + Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) { + if (updateChildren === void 0) { updateChildren = true; } + if (!rootMatrix) { + rootMatrix = this._baseMatrix; + } + if (this._parent) { + rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform); + } + else { + this._absoluteTransform.copyFrom(rootMatrix); + } + this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform); + if (updateChildren) { + for (var index = 0; index < this.children.length; index++) { + this.children[index]._updateDifferenceMatrix(); + } + } + this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1); + }; + /** + * Flag the bone as dirty (Forcing it to update everything) + */ + Bone.prototype.markAsDirty = function () { + this._currentRenderId++; + this._childUpdateId++; + this._skeleton._markAsDirty(); + }; + /** @hidden */ + Bone.prototype._markAsDirtyAndCompose = function () { + this.markAsDirty(); + this._needToCompose = true; + }; + Bone.prototype._markAsDirtyAndDecompose = function () { + this.markAsDirty(); + this._needToDecompose = true; + }; + /** + * Translate the bone in local or world space + * @param vec The amount to translate the bone + * @param space The space that the translation is in + * @param mesh The mesh that this bone is attached to. This is only used in world space + */ + Bone.prototype.translate = function (vec, space, mesh) { + if (space === void 0) { space = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL; } + var lm = this.getLocalMatrix(); + if (space == _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL) { + lm.addAtIndex(12, vec.x); + lm.addAtIndex(13, vec.y); + lm.addAtIndex(14, vec.z); + } + else { + var wm = null; + //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms() + if (mesh) { + wm = mesh.getWorldMatrix(); + } + this._skeleton.computeAbsoluteTransforms(); + var tmat = Bone._tmpMats[0]; + var tvec = Bone._tmpVecs[0]; + if (this._parent) { + if (mesh && wm) { + tmat.copyFrom(this._parent.getAbsoluteTransform()); + tmat.multiplyToRef(wm, tmat); + } + else { + tmat.copyFrom(this._parent.getAbsoluteTransform()); + } + } + tmat.setTranslationFromFloats(0, 0, 0); + tmat.invert(); + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(vec, tmat, tvec); + lm.addAtIndex(12, tvec.x); + lm.addAtIndex(13, tvec.y); + lm.addAtIndex(14, tvec.z); + } + this._markAsDirtyAndDecompose(); + }; + /** + * Set the postion of the bone in local or world space + * @param position The position to set the bone + * @param space The space that the position is in + * @param mesh The mesh that this bone is attached to. This is only used in world space + */ + Bone.prototype.setPosition = function (position, space, mesh) { + if (space === void 0) { space = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL; } + var lm = this.getLocalMatrix(); + if (space == _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL) { + lm.setTranslationFromFloats(position.x, position.y, position.z); + } + else { + var wm = null; + //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms() + if (mesh) { + wm = mesh.getWorldMatrix(); + } + this._skeleton.computeAbsoluteTransforms(); + var tmat = Bone._tmpMats[0]; + var vec = Bone._tmpVecs[0]; + if (this._parent) { + if (mesh && wm) { + tmat.copyFrom(this._parent.getAbsoluteTransform()); + tmat.multiplyToRef(wm, tmat); + } + else { + tmat.copyFrom(this._parent.getAbsoluteTransform()); + } + } + tmat.invert(); + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(position, tmat, vec); + lm.setTranslationFromFloats(vec.x, vec.y, vec.z); + } + this._markAsDirtyAndDecompose(); + }; + /** + * Set the absolute position of the bone (world space) + * @param position The position to set the bone + * @param mesh The mesh that this bone is attached to + */ + Bone.prototype.setAbsolutePosition = function (position, mesh) { + this.setPosition(position, _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].WORLD, mesh); + }; + /** + * Scale the bone on the x, y and z axes (in local space) + * @param x The amount to scale the bone on the x axis + * @param y The amount to scale the bone on the y axis + * @param z The amount to scale the bone on the z axis + * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default) + */ + Bone.prototype.scale = function (x, y, z, scaleChildren) { + if (scaleChildren === void 0) { scaleChildren = false; } + var locMat = this.getLocalMatrix(); + // Apply new scaling on top of current local matrix + var scaleMat = Bone._tmpMats[0]; + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].ScalingToRef(x, y, z, scaleMat); + scaleMat.multiplyToRef(locMat, locMat); + // Invert scaling matrix and apply the inverse to all children + scaleMat.invert(); + for (var _i = 0, _a = this.children; _i < _a.length; _i++) { + var child = _a[_i]; + var cm = child.getLocalMatrix(); + cm.multiplyToRef(scaleMat, cm); + cm.multiplyAtIndex(12, x); + cm.multiplyAtIndex(13, y); + cm.multiplyAtIndex(14, z); + child._markAsDirtyAndDecompose(); + } + this._markAsDirtyAndDecompose(); + if (scaleChildren) { + for (var _b = 0, _c = this.children; _b < _c.length; _b++) { + var child = _c[_b]; + child.scale(x, y, z, scaleChildren); + } + } + }; + /** + * Set the bone scaling in local space + * @param scale defines the scaling vector + */ + Bone.prototype.setScale = function (scale) { + this._decompose(); + this._localScaling.copyFrom(scale); + this._markAsDirtyAndCompose(); + }; + /** + * Gets the current scaling in local space + * @returns the current scaling vector + */ + Bone.prototype.getScale = function () { + this._decompose(); + return this._localScaling; + }; + /** + * Gets the current scaling in local space and stores it in a target vector + * @param result defines the target vector + */ + Bone.prototype.getScaleToRef = function (result) { + this._decompose(); + result.copyFrom(this._localScaling); + }; + /** + * Set the yaw, pitch, and roll of the bone in local or world space + * @param yaw The rotation of the bone on the y axis + * @param pitch The rotation of the bone on the x axis + * @param roll The rotation of the bone on the z axis + * @param space The space that the axes of rotation are in + * @param mesh The mesh that this bone is attached to. This is only used in world space + */ + Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) { + if (space === void 0) { space = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL; } + if (space === _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL) { + var quat = Bone._tmpQuat; + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Quaternion"].RotationYawPitchRollToRef(yaw, pitch, roll, quat); + this.setRotationQuaternion(quat, space, mesh); + return; + } + var rotMatInv = Bone._tmpMats[0]; + if (!this._getNegativeRotationToRef(rotMatInv, mesh)) { + return; + } + var rotMat = Bone._tmpMats[1]; + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].RotationYawPitchRollToRef(yaw, pitch, roll, rotMat); + rotMatInv.multiplyToRef(rotMat, rotMat); + this._rotateWithMatrix(rotMat, space, mesh); + }; + /** + * Add a rotation to the bone on an axis in local or world space + * @param axis The axis to rotate the bone on + * @param amount The amount to rotate the bone + * @param space The space that the axis is in + * @param mesh The mesh that this bone is attached to. This is only used in world space + */ + Bone.prototype.rotate = function (axis, amount, space, mesh) { + if (space === void 0) { space = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL; } + var rmat = Bone._tmpMats[0]; + rmat.setTranslationFromFloats(0, 0, 0); + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].RotationAxisToRef(axis, amount, rmat); + this._rotateWithMatrix(rmat, space, mesh); + }; + /** + * Set the rotation of the bone to a particular axis angle in local or world space + * @param axis The axis to rotate the bone on + * @param angle The angle that the bone should be rotated to + * @param space The space that the axis is in + * @param mesh The mesh that this bone is attached to. This is only used in world space + */ + Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) { + if (space === void 0) { space = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL; } + if (space === _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL) { + var quat = Bone._tmpQuat; + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Quaternion"].RotationAxisToRef(axis, angle, quat); + this.setRotationQuaternion(quat, space, mesh); + return; + } + var rotMatInv = Bone._tmpMats[0]; + if (!this._getNegativeRotationToRef(rotMatInv, mesh)) { + return; + } + var rotMat = Bone._tmpMats[1]; + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].RotationAxisToRef(axis, angle, rotMat); + rotMatInv.multiplyToRef(rotMat, rotMat); + this._rotateWithMatrix(rotMat, space, mesh); + }; + /** + * Set the euler rotation of the bone in local of world space + * @param rotation The euler rotation that the bone should be set to + * @param space The space that the rotation is in + * @param mesh The mesh that this bone is attached to. This is only used in world space + */ + Bone.prototype.setRotation = function (rotation, space, mesh) { + if (space === void 0) { space = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL; } + this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh); + }; + /** + * Set the quaternion rotation of the bone in local of world space + * @param quat The quaternion rotation that the bone should be set to + * @param space The space that the rotation is in + * @param mesh The mesh that this bone is attached to. This is only used in world space + */ + Bone.prototype.setRotationQuaternion = function (quat, space, mesh) { + if (space === void 0) { space = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL; } + if (space === _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL) { + this._decompose(); + this._localRotation.copyFrom(quat); + this._markAsDirtyAndCompose(); + return; + } + var rotMatInv = Bone._tmpMats[0]; + if (!this._getNegativeRotationToRef(rotMatInv, mesh)) { + return; + } + var rotMat = Bone._tmpMats[1]; + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].FromQuaternionToRef(quat, rotMat); + rotMatInv.multiplyToRef(rotMat, rotMat); + this._rotateWithMatrix(rotMat, space, mesh); + }; + /** + * Set the rotation matrix of the bone in local of world space + * @param rotMat The rotation matrix that the bone should be set to + * @param space The space that the rotation is in + * @param mesh The mesh that this bone is attached to. This is only used in world space + */ + Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) { + if (space === void 0) { space = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL; } + if (space === _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL) { + var quat = Bone._tmpQuat; + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Quaternion"].FromRotationMatrixToRef(rotMat, quat); + this.setRotationQuaternion(quat, space, mesh); + return; + } + var rotMatInv = Bone._tmpMats[0]; + if (!this._getNegativeRotationToRef(rotMatInv, mesh)) { + return; + } + var rotMat2 = Bone._tmpMats[1]; + rotMat2.copyFrom(rotMat); + rotMatInv.multiplyToRef(rotMat, rotMat2); + this._rotateWithMatrix(rotMat2, space, mesh); + }; + Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) { + if (space === void 0) { space = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL; } + var lmat = this.getLocalMatrix(); + var lx = lmat.m[12]; + var ly = lmat.m[13]; + var lz = lmat.m[14]; + var parent = this.getParent(); + var parentScale = Bone._tmpMats[3]; + var parentScaleInv = Bone._tmpMats[4]; + if (parent && space == _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].WORLD) { + if (mesh) { + parentScale.copyFrom(mesh.getWorldMatrix()); + parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale); + } + else { + parentScale.copyFrom(parent.getAbsoluteTransform()); + } + parentScaleInv.copyFrom(parentScale); + parentScaleInv.invert(); + lmat.multiplyToRef(parentScale, lmat); + lmat.multiplyToRef(rmat, lmat); + lmat.multiplyToRef(parentScaleInv, lmat); + } + else { + if (space == _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].WORLD && mesh) { + parentScale.copyFrom(mesh.getWorldMatrix()); + parentScaleInv.copyFrom(parentScale); + parentScaleInv.invert(); + lmat.multiplyToRef(parentScale, lmat); + lmat.multiplyToRef(rmat, lmat); + lmat.multiplyToRef(parentScaleInv, lmat); + } + else { + lmat.multiplyToRef(rmat, lmat); + } + } + lmat.setTranslationFromFloats(lx, ly, lz); + this.computeAbsoluteTransforms(); + this._markAsDirtyAndDecompose(); + }; + Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) { + var scaleMatrix = Bone._tmpMats[2]; + rotMatInv.copyFrom(this.getAbsoluteTransform()); + if (mesh) { + rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv); + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix); + } + rotMatInv.invert(); + if (isNaN(rotMatInv.m[0])) { + // Matrix failed to invert. + // This can happen if scale is zero for example. + return false; + } + scaleMatrix.multiplyAtIndex(0, this._scalingDeterminant); + rotMatInv.multiplyToRef(scaleMatrix, rotMatInv); + return true; + }; + /** + * Get the position of the bone in local or world space + * @param space The space that the returned position is in + * @param mesh The mesh that this bone is attached to. This is only used in world space + * @returns The position of the bone + */ + Bone.prototype.getPosition = function (space, mesh) { + if (space === void 0) { space = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL; } + if (mesh === void 0) { mesh = null; } + var pos = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); + this.getPositionToRef(space, mesh, pos); + return pos; + }; + /** + * Copy the position of the bone to a vector3 in local or world space + * @param space The space that the returned position is in + * @param mesh The mesh that this bone is attached to. This is only used in world space + * @param result The vector3 to copy the position to + */ + Bone.prototype.getPositionToRef = function (space, mesh, result) { + if (space === void 0) { space = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL; } + if (space == _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL) { + var lm = this.getLocalMatrix(); + result.x = lm.m[12]; + result.y = lm.m[13]; + result.z = lm.m[14]; + } + else { + var wm = null; + //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms() + if (mesh) { + wm = mesh.getWorldMatrix(); + } + this._skeleton.computeAbsoluteTransforms(); + var tmat = Bone._tmpMats[0]; + if (mesh && wm) { + tmat.copyFrom(this.getAbsoluteTransform()); + tmat.multiplyToRef(wm, tmat); + } + else { + tmat = this.getAbsoluteTransform(); + } + result.x = tmat.m[12]; + result.y = tmat.m[13]; + result.z = tmat.m[14]; + } + }; + /** + * Get the absolute position of the bone (world space) + * @param mesh The mesh that this bone is attached to + * @returns The absolute position of the bone + */ + Bone.prototype.getAbsolutePosition = function (mesh) { + if (mesh === void 0) { mesh = null; } + var pos = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); + this.getPositionToRef(_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].WORLD, mesh, pos); + return pos; + }; + /** + * Copy the absolute position of the bone (world space) to the result param + * @param mesh The mesh that this bone is attached to + * @param result The vector3 to copy the absolute position to + */ + Bone.prototype.getAbsolutePositionToRef = function (mesh, result) { + this.getPositionToRef(_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].WORLD, mesh, result); + }; + /** + * Compute the absolute transforms of this bone and its children + */ + Bone.prototype.computeAbsoluteTransforms = function () { + this._compose(); + if (this._parent) { + this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform); + } + else { + this._absoluteTransform.copyFrom(this._localMatrix); + var poseMatrix = this._skeleton.getPoseMatrix(); + if (poseMatrix) { + this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform); + } + } + var children = this.children; + var len = children.length; + for (var i = 0; i < len; i++) { + children[i].computeAbsoluteTransforms(); + } + }; + /** + * Get the world direction from an axis that is in the local space of the bone + * @param localAxis The local direction that is used to compute the world direction + * @param mesh The mesh that this bone is attached to + * @returns The world direction + */ + Bone.prototype.getDirection = function (localAxis, mesh) { + if (mesh === void 0) { mesh = null; } + var result = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); + this.getDirectionToRef(localAxis, mesh, result); + return result; + }; + /** + * Copy the world direction to a vector3 from an axis that is in the local space of the bone + * @param localAxis The local direction that is used to compute the world direction + * @param mesh The mesh that this bone is attached to + * @param result The vector3 that the world direction will be copied to + */ + Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) { + if (mesh === void 0) { mesh = null; } + var wm = null; + //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms() + if (mesh) { + wm = mesh.getWorldMatrix(); + } + this._skeleton.computeAbsoluteTransforms(); + var mat = Bone._tmpMats[0]; + mat.copyFrom(this.getAbsoluteTransform()); + if (mesh && wm) { + mat.multiplyToRef(wm, mat); + } + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformNormalToRef(localAxis, mat, result); + result.normalize(); + }; + /** + * Get the euler rotation of the bone in local or world space + * @param space The space that the rotation should be in + * @param mesh The mesh that this bone is attached to. This is only used in world space + * @returns The euler rotation + */ + Bone.prototype.getRotation = function (space, mesh) { + if (space === void 0) { space = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL; } + if (mesh === void 0) { mesh = null; } + var result = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); + this.getRotationToRef(space, mesh, result); + return result; + }; + /** + * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space + * @param space The space that the rotation should be in + * @param mesh The mesh that this bone is attached to. This is only used in world space + * @param result The vector3 that the rotation should be copied to + */ + Bone.prototype.getRotationToRef = function (space, mesh, result) { + if (space === void 0) { space = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL; } + if (mesh === void 0) { mesh = null; } + var quat = Bone._tmpQuat; + this.getRotationQuaternionToRef(space, mesh, quat); + quat.toEulerAnglesToRef(result); + }; + /** + * Get the quaternion rotation of the bone in either local or world space + * @param space The space that the rotation should be in + * @param mesh The mesh that this bone is attached to. This is only used in world space + * @returns The quaternion rotation + */ + Bone.prototype.getRotationQuaternion = function (space, mesh) { + if (space === void 0) { space = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL; } + if (mesh === void 0) { mesh = null; } + var result = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Quaternion"].Identity(); + this.getRotationQuaternionToRef(space, mesh, result); + return result; + }; + /** + * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space + * @param space The space that the rotation should be in + * @param mesh The mesh that this bone is attached to. This is only used in world space + * @param result The quaternion that the rotation should be copied to + */ + Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) { + if (space === void 0) { space = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL; } + if (mesh === void 0) { mesh = null; } + if (space == _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL) { + this._decompose(); + result.copyFrom(this._localRotation); + } + else { + var mat = Bone._tmpMats[0]; + var amat = this.getAbsoluteTransform(); + if (mesh) { + amat.multiplyToRef(mesh.getWorldMatrix(), mat); + } + else { + mat.copyFrom(amat); + } + mat.multiplyAtIndex(0, this._scalingDeterminant); + mat.multiplyAtIndex(1, this._scalingDeterminant); + mat.multiplyAtIndex(2, this._scalingDeterminant); + mat.decompose(undefined, result, undefined); + } + }; + /** + * Get the rotation matrix of the bone in local or world space + * @param space The space that the rotation should be in + * @param mesh The mesh that this bone is attached to. This is only used in world space + * @returns The rotation matrix + */ + Bone.prototype.getRotationMatrix = function (space, mesh) { + if (space === void 0) { space = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL; } + var result = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Identity(); + this.getRotationMatrixToRef(space, mesh, result); + return result; + }; + /** + * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space + * @param space The space that the rotation should be in + * @param mesh The mesh that this bone is attached to. This is only used in world space + * @param result The quaternion that the rotation should be copied to + */ + Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) { + if (space === void 0) { space = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL; } + if (space == _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL) { + this.getLocalMatrix().getRotationMatrixToRef(result); + } + else { + var mat = Bone._tmpMats[0]; + var amat = this.getAbsoluteTransform(); + if (mesh) { + amat.multiplyToRef(mesh.getWorldMatrix(), mat); + } + else { + mat.copyFrom(amat); + } + mat.multiplyAtIndex(0, this._scalingDeterminant); + mat.multiplyAtIndex(1, this._scalingDeterminant); + mat.multiplyAtIndex(2, this._scalingDeterminant); + mat.getRotationMatrixToRef(result); + } + }; + /** + * Get the world position of a point that is in the local space of the bone + * @param position The local position + * @param mesh The mesh that this bone is attached to + * @returns The world position + */ + Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) { + if (mesh === void 0) { mesh = null; } + var result = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); + this.getAbsolutePositionFromLocalToRef(position, mesh, result); + return result; + }; + /** + * Get the world position of a point that is in the local space of the bone and copy it to the result param + * @param position The local position + * @param mesh The mesh that this bone is attached to + * @param result The vector3 that the world position should be copied to + */ + Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) { + if (mesh === void 0) { mesh = null; } + var wm = null; + //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms() + if (mesh) { + wm = mesh.getWorldMatrix(); + } + this._skeleton.computeAbsoluteTransforms(); + var tmat = Bone._tmpMats[0]; + if (mesh && wm) { + tmat.copyFrom(this.getAbsoluteTransform()); + tmat.multiplyToRef(wm, tmat); + } + else { + tmat = this.getAbsoluteTransform(); + } + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(position, tmat, result); + }; + /** + * Get the local position of a point that is in world space + * @param position The world position + * @param mesh The mesh that this bone is attached to + * @returns The local position + */ + Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) { + if (mesh === void 0) { mesh = null; } + var result = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); + this.getLocalPositionFromAbsoluteToRef(position, mesh, result); + return result; + }; + /** + * Get the local position of a point that is in world space and copy it to the result param + * @param position The world position + * @param mesh The mesh that this bone is attached to + * @param result The vector3 that the local position should be copied to + */ + Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) { + if (mesh === void 0) { mesh = null; } + var wm = null; + //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms() + if (mesh) { + wm = mesh.getWorldMatrix(); + } + this._skeleton.computeAbsoluteTransforms(); + var tmat = Bone._tmpMats[0]; + tmat.copyFrom(this.getAbsoluteTransform()); + if (mesh && wm) { + tmat.multiplyToRef(wm, tmat); + } + tmat.invert(); + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(position, tmat, result); + }; + Bone._tmpVecs = _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_2__["ArrayTools"].BuildArray(2, _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero); + Bone._tmpQuat = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Quaternion"].Identity(); + Bone._tmpMats = _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_2__["ArrayTools"].BuildArray(5, _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Identity); + return Bone; +}(_node__WEBPACK_IMPORTED_MODULE_3__["Node"])); + + + +/***/ }), + +/***/ "./Bones/boneIKController.ts": +/*!***********************************!*\ + !*** ./Bones/boneIKController.ts ***! + \***********************************/ +/*! exports provided: BoneIKController */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BoneIKController", function() { return BoneIKController; }); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); + +/** + * Class used to apply inverse kinematics to bones + * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller + */ +var BoneIKController = /** @class */ (function () { + /** + * Creates a new BoneIKController + * @param mesh defines the mesh to control + * @param bone defines the bone to control + * @param options defines options to set up the controller + */ + function BoneIKController(mesh, bone, options) { + /** + * Gets or sets the target position + */ + this.targetPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(); + /** + * Gets or sets the pole target position + */ + this.poleTargetPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(); + /** + * Gets or sets the pole target local offset + */ + this.poleTargetLocalOffset = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(); + /** + * Gets or sets the pole angle + */ + this.poleAngle = 0; + /** + * The amount to slerp (spherical linear interpolation) to the target. Set this to a value between 0 and 1 (a value of 1 disables slerp) + */ + this.slerpAmount = 1; + this._bone1Quat = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].Identity(); + this._bone1Mat = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].Identity(); + this._bone2Ang = Math.PI; + this._maxAngle = Math.PI; + this._rightHandedSystem = false; + this._bendAxis = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Right(); + this._slerping = false; + this._adjustRoll = 0; + this._bone2 = bone; + this._bone1 = bone.getParent(); + if (!this._bone1) { + return; + } + this.mesh = mesh; + var bonePos = bone.getPosition(); + if (bone.getAbsoluteTransform().determinant() > 0) { + this._rightHandedSystem = true; + this._bendAxis.x = 0; + this._bendAxis.y = 0; + this._bendAxis.z = -1; + if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) { + this._adjustRoll = Math.PI * .5; + this._bendAxis.z = 1; + } + } + if (this._bone1.length) { + var boneScale1 = this._bone1.getScale(); + var boneScale2 = this._bone2.getScale(); + this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y; + this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y; + } + else if (this._bone1.children[0]) { + mesh.computeWorldMatrix(true); + var pos1 = this._bone2.children[0].getAbsolutePosition(mesh); + var pos2 = this._bone2.getAbsolutePosition(mesh); + var pos3 = this._bone1.getAbsolutePosition(mesh); + this._bone1Length = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Distance(pos1, pos2); + this._bone2Length = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Distance(pos2, pos3); + } + this._bone1.getRotationMatrixToRef(_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Space"].WORLD, mesh, this._bone1Mat); + this.maxAngle = Math.PI; + if (options) { + if (options.targetMesh) { + this.targetMesh = options.targetMesh; + this.targetMesh.computeWorldMatrix(true); + } + if (options.poleTargetMesh) { + this.poleTargetMesh = options.poleTargetMesh; + this.poleTargetMesh.computeWorldMatrix(true); + } + else if (options.poleTargetBone) { + this.poleTargetBone = options.poleTargetBone; + } + else if (this._bone1.getParent()) { + this.poleTargetBone = this._bone1.getParent(); + } + if (options.poleTargetLocalOffset) { + this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset); + } + if (options.poleAngle) { + this.poleAngle = options.poleAngle; + } + if (options.bendAxis) { + this._bendAxis.copyFrom(options.bendAxis); + } + if (options.maxAngle) { + this.maxAngle = options.maxAngle; + } + if (options.slerpAmount) { + this.slerpAmount = options.slerpAmount; + } + } + } + Object.defineProperty(BoneIKController.prototype, "maxAngle", { + /** + * Gets or sets maximum allowed angle + */ + get: function () { + return this._maxAngle; + }, + set: function (value) { + this._setMaxAngle(value); + }, + enumerable: true, + configurable: true + }); + BoneIKController.prototype._setMaxAngle = function (ang) { + if (ang < 0) { + ang = 0; + } + if (ang > Math.PI || ang == undefined) { + ang = Math.PI; + } + this._maxAngle = ang; + var a = this._bone1Length; + var b = this._bone2Length; + this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang)); + }; + /** + * Force the controller to update the bones + */ + BoneIKController.prototype.update = function () { + var bone1 = this._bone1; + if (!bone1) { + return; + } + var target = this.targetPosition; + var poleTarget = this.poleTargetPosition; + var mat1 = BoneIKController._tmpMats[0]; + var mat2 = BoneIKController._tmpMats[1]; + if (this.targetMesh) { + target.copyFrom(this.targetMesh.getAbsolutePosition()); + } + if (this.poleTargetBone) { + this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget); + } + else if (this.poleTargetMesh) { + _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget); + } + var bonePos = BoneIKController._tmpVecs[0]; + var zaxis = BoneIKController._tmpVecs[1]; + var xaxis = BoneIKController._tmpVecs[2]; + var yaxis = BoneIKController._tmpVecs[3]; + var upAxis = BoneIKController._tmpVecs[4]; + var _tmpQuat = BoneIKController._tmpQuat; + bone1.getAbsolutePositionToRef(this.mesh, bonePos); + poleTarget.subtractToRef(bonePos, upAxis); + if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) { + upAxis.y = 1; + } + else { + upAxis.normalize(); + } + target.subtractToRef(bonePos, yaxis); + yaxis.normalize(); + _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].CrossToRef(yaxis, upAxis, zaxis); + zaxis.normalize(); + _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].CrossToRef(yaxis, zaxis, xaxis); + xaxis.normalize(); + _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1); + var a = this._bone1Length; + var b = this._bone2Length; + var c = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Distance(bonePos, target); + if (this._maxReach > 0) { + c = Math.min(this._maxReach, c); + } + var acosa = (b * b + c * c - a * a) / (2 * b * c); + var acosb = (c * c + a * a - b * b) / (2 * c * a); + if (acosa > 1) { + acosa = 1; + } + if (acosb > 1) { + acosb = 1; + } + if (acosa < -1) { + acosa = -1; + } + if (acosb < -1) { + acosb = -1; + } + var angA = Math.acos(acosa); + var angB = Math.acos(acosb); + var angC = -angA - angB; + if (this._rightHandedSystem) { + _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2); + mat2.multiplyToRef(mat1, mat1); + _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].RotationAxisToRef(this._bendAxis, angB, mat2); + mat2.multiplyToRef(mat1, mat1); + } + else { + var _tmpVec = BoneIKController._tmpVecs[5]; + _tmpVec.copyFrom(this._bendAxis); + _tmpVec.x *= -1; + _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].RotationAxisToRef(_tmpVec, -angB, mat2); + mat2.multiplyToRef(mat1, mat1); + } + if (this.poleAngle) { + _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].RotationAxisToRef(yaxis, this.poleAngle, mat2); + mat1.multiplyToRef(mat2, mat1); + } + if (this._bone1) { + if (this.slerpAmount < 1) { + if (!this._slerping) { + _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat); + } + _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].FromRotationMatrixToRef(mat1, _tmpQuat); + _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat); + angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount; + this._bone1.setRotationQuaternion(this._bone1Quat, _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Space"].WORLD, this.mesh); + this._slerping = true; + } + else { + this._bone1.setRotationMatrix(mat1, _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Space"].WORLD, this.mesh); + this._bone1Mat.copyFrom(mat1); + this._slerping = false; + } + } + this._bone2.setAxisAngle(this._bendAxis, angC, _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Space"].LOCAL); + this._bone2Ang = angC; + }; + BoneIKController._tmpVecs = [_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(), _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(), _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(), _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(), _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(), _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero()]; + BoneIKController._tmpQuat = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].Identity(); + BoneIKController._tmpMats = [_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].Identity(), _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].Identity()]; + return BoneIKController; +}()); + + + +/***/ }), + +/***/ "./Bones/boneLookController.ts": +/*!*************************************!*\ + !*** ./Bones/boneLookController.ts ***! + \*************************************/ +/*! exports provided: BoneLookController */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BoneLookController", function() { return BoneLookController; }); +/* harmony import */ var _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/arrayTools */ "./Misc/arrayTools.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); + + +/** + * Class used to make a bone look toward a point in space + * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller + */ +var BoneLookController = /** @class */ (function () { + /** + * Create a BoneLookController + * @param mesh the mesh that the bone belongs to + * @param bone the bone that will be looking to the target + * @param target the target Vector3 to look at + * @param options optional settings: + * * maxYaw: the maximum angle the bone will yaw to + * * minYaw: the minimum angle the bone will yaw to + * * maxPitch: the maximum angle the bone will pitch to + * * minPitch: the minimum angle the bone will yaw to + * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target. + * * upAxis: the up axis of the coordinate system + * * upAxisSpace: the space that the up axis is in - Space.BONE, Space.LOCAL (default), or Space.WORLD. + * * yawAxis: set yawAxis if the bone does not yaw on the y axis + * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis + * * adjustYaw: used to make an adjustment to the yaw of the bone + * * adjustPitch: used to make an adjustment to the pitch of the bone + * * adjustRoll: used to make an adjustment to the roll of the bone + **/ + function BoneLookController(mesh, bone, target, options) { + /** + * The up axis of the coordinate system that is used when the bone is rotated + */ + this.upAxis = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Up(); + /** + * The space that the up axis is in - Space.BONE, Space.LOCAL (default), or Space.WORLD + */ + this.upAxisSpace = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL; + /** + * Used to make an adjustment to the yaw of the bone + */ + this.adjustYaw = 0; + /** + * Used to make an adjustment to the pitch of the bone + */ + this.adjustPitch = 0; + /** + * Used to make an adjustment to the roll of the bone + */ + this.adjustRoll = 0; + /** + * The amount to slerp (spherical linear interpolation) to the target. Set this to a value between 0 and 1 (a value of 1 disables slerp) + */ + this.slerpAmount = 1; + this._boneQuat = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Quaternion"].Identity(); + this._slerping = false; + this._firstFrameSkipped = false; + this._fowardAxis = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Forward(); + this.mesh = mesh; + this.bone = bone; + this.target = target; + if (options) { + if (options.adjustYaw) { + this.adjustYaw = options.adjustYaw; + } + if (options.adjustPitch) { + this.adjustPitch = options.adjustPitch; + } + if (options.adjustRoll) { + this.adjustRoll = options.adjustRoll; + } + if (options.maxYaw != null) { + this.maxYaw = options.maxYaw; + } + else { + this.maxYaw = Math.PI; + } + if (options.minYaw != null) { + this.minYaw = options.minYaw; + } + else { + this.minYaw = -Math.PI; + } + if (options.maxPitch != null) { + this.maxPitch = options.maxPitch; + } + else { + this.maxPitch = Math.PI; + } + if (options.minPitch != null) { + this.minPitch = options.minPitch; + } + else { + this.minPitch = -Math.PI; + } + if (options.slerpAmount != null) { + this.slerpAmount = options.slerpAmount; + } + if (options.upAxis != null) { + this.upAxis = options.upAxis; + } + if (options.upAxisSpace != null) { + this.upAxisSpace = options.upAxisSpace; + } + if (options.yawAxis != null || options.pitchAxis != null) { + var newYawAxis = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Axis"].Y; + var newPitchAxis = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Axis"].X; + if (options.yawAxis != null) { + newYawAxis = options.yawAxis.clone(); + newYawAxis.normalize(); + } + if (options.pitchAxis != null) { + newPitchAxis = options.pitchAxis.clone(); + newPitchAxis.normalize(); + } + var newRollAxis = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Cross(newPitchAxis, newYawAxis); + this._transformYawPitch = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Identity(); + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch); + this._transformYawPitchInv = this._transformYawPitch.clone(); + this._transformYawPitch.invert(); + } + } + if (!bone.getParent() && this.upAxisSpace == _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].BONE) { + this.upAxisSpace = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL; + } + } + Object.defineProperty(BoneLookController.prototype, "minYaw", { + /** + * Gets or sets the minimum yaw angle that the bone can look to + */ + get: function () { + return this._minYaw; + }, + set: function (value) { + this._minYaw = value; + this._minYawSin = Math.sin(value); + this._minYawCos = Math.cos(value); + if (this._maxYaw != null) { + this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw; + this._yawRange = this._maxYaw - this._minYaw; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(BoneLookController.prototype, "maxYaw", { + /** + * Gets or sets the maximum yaw angle that the bone can look to + */ + get: function () { + return this._maxYaw; + }, + set: function (value) { + this._maxYaw = value; + this._maxYawSin = Math.sin(value); + this._maxYawCos = Math.cos(value); + if (this._minYaw != null) { + this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw; + this._yawRange = this._maxYaw - this._minYaw; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(BoneLookController.prototype, "minPitch", { + /** + * Gets or sets the minimum pitch angle that the bone can look to + */ + get: function () { + return this._minPitch; + }, + set: function (value) { + this._minPitch = value; + this._minPitchTan = Math.tan(value); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(BoneLookController.prototype, "maxPitch", { + /** + * Gets or sets the maximum pitch angle that the bone can look to + */ + get: function () { + return this._maxPitch; + }, + set: function (value) { + this._maxPitch = value; + this._maxPitchTan = Math.tan(value); + }, + enumerable: true, + configurable: true + }); + /** + * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()) + */ + BoneLookController.prototype.update = function () { + //skip the first frame when slerping so that the mesh rotation is correct + if (this.slerpAmount < 1 && !this._firstFrameSkipped) { + this._firstFrameSkipped = true; + return; + } + var bone = this.bone; + var bonePos = BoneLookController._tmpVecs[0]; + bone.getAbsolutePositionToRef(this.mesh, bonePos); + var target = this.target; + var _tmpMat1 = BoneLookController._tmpMats[0]; + var _tmpMat2 = BoneLookController._tmpMats[1]; + var mesh = this.mesh; + var parentBone = bone.getParent(); + var upAxis = BoneLookController._tmpVecs[1]; + upAxis.copyFrom(this.upAxis); + if (this.upAxisSpace == _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].BONE && parentBone) { + if (this._transformYawPitch) { + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis); + } + parentBone.getDirectionToRef(upAxis, this.mesh, upAxis); + } + else if (this.upAxisSpace == _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL) { + mesh.getDirectionToRef(upAxis, upAxis); + if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) { + upAxis.normalize(); + } + } + var checkYaw = false; + var checkPitch = false; + if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) { + checkYaw = true; + } + if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) { + checkPitch = true; + } + if (checkYaw || checkPitch) { + var spaceMat = BoneLookController._tmpMats[2]; + var spaceMatInv = BoneLookController._tmpMats[3]; + if (this.upAxisSpace == _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].BONE && upAxis.y == 1 && parentBone) { + parentBone.getRotationMatrixToRef(_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].WORLD, this.mesh, spaceMat); + } + else if (this.upAxisSpace == _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL && upAxis.y == 1 && !parentBone) { + spaceMat.copyFrom(mesh.getWorldMatrix()); + } + else { + var forwardAxis = BoneLookController._tmpVecs[2]; + forwardAxis.copyFrom(this._fowardAxis); + if (this._transformYawPitch) { + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis); + } + if (parentBone) { + parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis); + } + else { + mesh.getDirectionToRef(forwardAxis, forwardAxis); + } + var rightAxis = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Cross(upAxis, forwardAxis); + rightAxis.normalize(); + var forwardAxis = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Cross(rightAxis, upAxis); + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat); + } + spaceMat.invertToRef(spaceMatInv); + var xzlen = null; + if (checkPitch) { + var localTarget = BoneLookController._tmpVecs[3]; + target.subtractToRef(bonePos, localTarget); + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget); + xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z); + var pitch = Math.atan2(localTarget.y, xzlen); + var newPitch = pitch; + if (pitch > this._maxPitch) { + localTarget.y = this._maxPitchTan * xzlen; + newPitch = this._maxPitch; + } + else if (pitch < this._minPitch) { + localTarget.y = this._minPitchTan * xzlen; + newPitch = this._minPitch; + } + if (pitch != newPitch) { + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(localTarget, spaceMat, localTarget); + localTarget.addInPlace(bonePos); + target = localTarget; + } + } + if (checkYaw) { + var localTarget = BoneLookController._tmpVecs[4]; + target.subtractToRef(bonePos, localTarget); + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget); + var yaw = Math.atan2(localTarget.x, localTarget.z); + var newYaw = yaw; + if (yaw > this._maxYaw || yaw < this._minYaw) { + if (xzlen == null) { + xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z); + } + if (this._yawRange > Math.PI) { + if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) { + localTarget.z = this._maxYawCos * xzlen; + localTarget.x = this._maxYawSin * xzlen; + newYaw = this._maxYaw; + } + else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) { + localTarget.z = this._minYawCos * xzlen; + localTarget.x = this._minYawSin * xzlen; + newYaw = this._minYaw; + } + } + else { + if (yaw > this._maxYaw) { + localTarget.z = this._maxYawCos * xzlen; + localTarget.x = this._maxYawSin * xzlen; + newYaw = this._maxYaw; + } + else if (yaw < this._minYaw) { + localTarget.z = this._minYawCos * xzlen; + localTarget.x = this._minYawSin * xzlen; + newYaw = this._minYaw; + } + } + } + if (this._slerping && this._yawRange > Math.PI) { + //are we going to be crossing into the min/max region? + var boneFwd = BoneLookController._tmpVecs[8]; + boneFwd.copyFrom(_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Axis"].Z); + if (this._transformYawPitch) { + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd); + } + var boneRotMat = BoneLookController._tmpMats[4]; + this._boneQuat.toRotationMatrix(boneRotMat); + this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat); + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd); + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd); + var boneYaw = Math.atan2(boneFwd.x, boneFwd.z); + var angBtwTar = this._getAngleBetween(boneYaw, yaw); + var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint); + if (angBtwTar > angBtwMidYaw) { + if (xzlen == null) { + xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z); + } + var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw); + var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw); + if (angBtwMin < angBtwMax) { + newYaw = boneYaw + Math.PI * .75; + localTarget.z = Math.cos(newYaw) * xzlen; + localTarget.x = Math.sin(newYaw) * xzlen; + } + else { + newYaw = boneYaw - Math.PI * .75; + localTarget.z = Math.cos(newYaw) * xzlen; + localTarget.x = Math.sin(newYaw) * xzlen; + } + } + } + if (yaw != newYaw) { + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(localTarget, spaceMat, localTarget); + localTarget.addInPlace(bonePos); + target = localTarget; + } + } + } + var zaxis = BoneLookController._tmpVecs[5]; + var xaxis = BoneLookController._tmpVecs[6]; + var yaxis = BoneLookController._tmpVecs[7]; + var _tmpQuat = BoneLookController._tmpQuat; + target.subtractToRef(bonePos, zaxis); + zaxis.normalize(); + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].CrossToRef(upAxis, zaxis, xaxis); + xaxis.normalize(); + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].CrossToRef(zaxis, xaxis, yaxis); + yaxis.normalize(); + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1); + if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) { + return; + } + if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) { + return; + } + if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) { + return; + } + if (this.adjustYaw || this.adjustPitch || this.adjustRoll) { + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2); + _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1); + } + if (this.slerpAmount < 1) { + if (!this._slerping) { + this.bone.getRotationQuaternionToRef(_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].WORLD, this.mesh, this._boneQuat); + } + if (this._transformYawPitch) { + this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1); + } + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Quaternion"].FromRotationMatrixToRef(_tmpMat1, _tmpQuat); + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Quaternion"].SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat); + this.bone.setRotationQuaternion(this._boneQuat, _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].WORLD, this.mesh); + this._slerping = true; + } + else { + if (this._transformYawPitch) { + this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1); + } + this.bone.setRotationMatrix(_tmpMat1, _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].WORLD, this.mesh); + this._slerping = false; + } + }; + BoneLookController.prototype._getAngleDiff = function (ang1, ang2) { + var angDiff = ang2 - ang1; + angDiff %= Math.PI * 2; + if (angDiff > Math.PI) { + angDiff -= Math.PI * 2; + } + else if (angDiff < -Math.PI) { + angDiff += Math.PI * 2; + } + return angDiff; + }; + BoneLookController.prototype._getAngleBetween = function (ang1, ang2) { + ang1 %= (2 * Math.PI); + ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1; + ang2 %= (2 * Math.PI); + ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2; + var ab = 0; + if (ang1 < ang2) { + ab = ang2 - ang1; + } + else { + ab = ang1 - ang2; + } + if (ab > Math.PI) { + ab = Math.PI * 2 - ab; + } + return ab; + }; + BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) { + ang %= (2 * Math.PI); + ang = (ang < 0) ? ang + (2 * Math.PI) : ang; + ang1 %= (2 * Math.PI); + ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1; + ang2 %= (2 * Math.PI); + ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2; + if (ang1 < ang2) { + if (ang > ang1 && ang < ang2) { + return true; + } + } + else { + if (ang > ang2 && ang < ang1) { + return true; + } + } + return false; + }; + BoneLookController._tmpVecs = _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_0__["ArrayTools"].BuildArray(10, _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero); + BoneLookController._tmpQuat = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Quaternion"].Identity(); + BoneLookController._tmpMats = _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_0__["ArrayTools"].BuildArray(5, _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Identity); + return BoneLookController; +}()); + + + +/***/ }), + +/***/ "./Bones/index.ts": +/*!************************!*\ + !*** ./Bones/index.ts ***! + \************************/ +/*! exports provided: Bone, BoneIKController, BoneLookController, Skeleton */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _bone__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bone */ "./Bones/bone.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Bone", function() { return _bone__WEBPACK_IMPORTED_MODULE_0__["Bone"]; }); + +/* harmony import */ var _boneIKController__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./boneIKController */ "./Bones/boneIKController.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoneIKController", function() { return _boneIKController__WEBPACK_IMPORTED_MODULE_1__["BoneIKController"]; }); + +/* harmony import */ var _boneLookController__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./boneLookController */ "./Bones/boneLookController.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoneLookController", function() { return _boneLookController__WEBPACK_IMPORTED_MODULE_2__["BoneLookController"]; }); + +/* harmony import */ var _skeleton__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./skeleton */ "./Bones/skeleton.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Skeleton", function() { return _skeleton__WEBPACK_IMPORTED_MODULE_3__["Skeleton"]; }); + + + + + + + +/***/ }), + +/***/ "./Bones/skeleton.ts": +/*!***************************!*\ + !*** ./Bones/skeleton.ts ***! + \***************************/ +/*! exports provided: Skeleton */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Skeleton", function() { return Skeleton; }); +/* harmony import */ var _bone__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bone */ "./Bones/bone.ts"); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Materials_Textures_rawTexture__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Materials/Textures/rawTexture */ "./Materials/Textures/rawTexture.ts"); +/* harmony import */ var _Animations_animation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Animations/animation */ "./Animations/animation.ts"); +/* harmony import */ var _Animations_animationRange__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Animations/animationRange */ "./Animations/animationRange.ts"); +/* harmony import */ var _Engines_engineStore__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Engines/engineStore */ "./Engines/engineStore.ts"); +/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts"); +/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts"); +/* harmony import */ var _Misc_deepCopier__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Misc/deepCopier */ "./Misc/deepCopier.ts"); + + + + + + + + + + +/** + * Class used to handle skinning animations + * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons + */ +var Skeleton = /** @class */ (function () { + /** + * Creates a new skeleton + * @param name defines the skeleton name + * @param id defines the skeleton Id + * @param scene defines the hosting scene + */ + function Skeleton( + /** defines the skeleton name */ + name, + /** defines the skeleton Id */ + id, scene) { + this.name = name; + this.id = id; + /** + * Defines the list of child bones + */ + this.bones = new Array(); + /** + * Defines a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value) + */ + this.needInitialSkinMatrix = false; + /** + * Defines a mesh that override the matrix used to get the world matrix (null by default). + */ + this.overrideMesh = null; + this._isDirty = true; + this._meshesWithPoseMatrix = new Array(); + this._identity = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"].Identity(); + this._ranges = {}; + this._lastAbsoluteTransformsUpdateId = -1; + this._canUseTextureForBones = false; + this._uniqueId = 0; + /** @hidden */ + this._numBonesWithLinkedTransformNode = 0; + /** @hidden */ + this._hasWaitingData = null; + /** + * Specifies if the skeleton should be serialized + */ + this.doNotSerialize = false; + this._useTextureToStoreBoneMatrices = true; + this._animationPropertiesOverride = null; + // Events + /** + * An observable triggered before computing the skeleton's matrices + */ + this.onBeforeComputeObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + this.bones = []; + this._scene = scene || _Engines_engineStore__WEBPACK_IMPORTED_MODULE_6__["EngineStore"].LastCreatedScene; + this._uniqueId = this._scene.getUniqueId(); + this._scene.addSkeleton(this); + //make sure it will recalculate the matrix next time prepare is called. + this._isDirty = true; + var engineCaps = this._scene.getEngine().getCaps(); + this._canUseTextureForBones = engineCaps.textureFloat && engineCaps.maxVertexTextureImageUnits > 0; + } + Object.defineProperty(Skeleton.prototype, "useTextureToStoreBoneMatrices", { + /** + * Gets or sets a boolean indicating that bone matrices should be stored as a texture instead of using shader uniforms (default is true). + * Please note that this option is not available when needInitialSkinMatrix === true or if the hardware does not support it + */ + get: function () { + return this._useTextureToStoreBoneMatrices; + }, + set: function (value) { + this._useTextureToStoreBoneMatrices = value; + this._markAsDirty(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", { + /** + * Gets or sets the animation properties override + */ + get: function () { + if (!this._animationPropertiesOverride) { + return this._scene.animationPropertiesOverride; + } + return this._animationPropertiesOverride; + }, + set: function (value) { + this._animationPropertiesOverride = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Skeleton.prototype, "isUsingTextureForMatrices", { + /** + * Gets a boolean indicating that the skeleton effectively stores matrices into a texture + */ + get: function () { + return this.useTextureToStoreBoneMatrices && this._canUseTextureForBones && !this.needInitialSkinMatrix; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Skeleton.prototype, "uniqueId", { + /** + * Gets the unique ID of this skeleton + */ + get: function () { + return this._uniqueId; + }, + enumerable: true, + configurable: true + }); + /** + * Gets the current object class name. + * @return the class name + */ + Skeleton.prototype.getClassName = function () { + return "Skeleton"; + }; + /** + * Returns an array containing the root bones + * @returns an array containing the root bones + */ + Skeleton.prototype.getChildren = function () { + return this.bones.filter(function (b) { return !b.getParent(); }); + }; + // Members + /** + * Gets the list of transform matrices to send to shaders (one matrix per bone) + * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true) + * @returns a Float32Array containing matrices data + */ + Skeleton.prototype.getTransformMatrices = function (mesh) { + if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) { + return mesh._bonesTransformMatrices; + } + if (!this._transformMatrices) { + this.prepare(); + } + return this._transformMatrices; + }; + /** + * Gets the list of transform matrices to send to shaders inside a texture (one matrix per bone) + * @returns a raw texture containing the data + */ + Skeleton.prototype.getTransformMatrixTexture = function () { + return this._transformMatrixTexture; + }; + /** + * Gets the current hosting scene + * @returns a scene object + */ + Skeleton.prototype.getScene = function () { + return this._scene; + }; + // Methods + /** + * Gets a string representing the current skeleton data + * @param fullDetails defines a boolean indicating if we want a verbose version + * @returns a string representing the current skeleton data + */ + Skeleton.prototype.toString = function (fullDetails) { + var ret = "Name: " + this.name + ", nBones: " + this.bones.length; + ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none"); + if (fullDetails) { + ret += ", Ranges: {"; + var first = true; + for (var name_1 in this._ranges) { + if (first) { + ret += ", "; + first = false; + } + ret += name_1; + } + ret += "}"; + } + return ret; + }; + /** + * Get bone's index searching by name + * @param name defines bone's name to search for + * @return the indice of the bone. Returns -1 if not found + */ + Skeleton.prototype.getBoneIndexByName = function (name) { + for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) { + if (this.bones[boneIndex].name === name) { + return boneIndex; + } + } + return -1; + }; + /** + * Creater a new animation range + * @param name defines the name of the range + * @param from defines the start key + * @param to defines the end key + */ + Skeleton.prototype.createAnimationRange = function (name, from, to) { + // check name not already in use + if (!this._ranges[name]) { + this._ranges[name] = new _Animations_animationRange__WEBPACK_IMPORTED_MODULE_5__["AnimationRange"](name, from, to); + for (var i = 0, nBones = this.bones.length; i < nBones; i++) { + if (this.bones[i].animations[0]) { + this.bones[i].animations[0].createRange(name, from, to); + } + } + } + }; + /** + * Delete a specific animation range + * @param name defines the name of the range + * @param deleteFrames defines if frames must be removed as well + */ + Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) { + if (deleteFrames === void 0) { deleteFrames = true; } + for (var i = 0, nBones = this.bones.length; i < nBones; i++) { + if (this.bones[i].animations[0]) { + this.bones[i].animations[0].deleteRange(name, deleteFrames); + } + } + this._ranges[name] = null; // said much faster than 'delete this._range[name]' + }; + /** + * Gets a specific animation range + * @param name defines the name of the range to look for + * @returns the requested animation range or null if not found + */ + Skeleton.prototype.getAnimationRange = function (name) { + return this._ranges[name]; + }; + /** + * Gets the list of all animation ranges defined on this skeleton + * @returns an array + */ + Skeleton.prototype.getAnimationRanges = function () { + var animationRanges = []; + var name; + for (name in this._ranges) { + animationRanges.push(this._ranges[name]); + } + return animationRanges; + }; + /** + * Copy animation range from a source skeleton. + * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences + * @param source defines the source skeleton + * @param name defines the name of the range to copy + * @param rescaleAsRequired defines if rescaling must be applied if required + * @returns true if operation was successful + */ + Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) { + if (rescaleAsRequired === void 0) { rescaleAsRequired = false; } + if (this._ranges[name] || !source.getAnimationRange(name)) { + return false; + } + var ret = true; + var frameOffset = this._getHighestAnimationFrame() + 1; + // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required + var boneDict = {}; + var sourceBones = source.bones; + var nBones; + var i; + for (i = 0, nBones = sourceBones.length; i < nBones; i++) { + boneDict[sourceBones[i].name] = sourceBones[i]; + } + if (this.bones.length !== sourceBones.length) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_8__["Logger"].Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length); + ret = false; + } + var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null; + for (i = 0, nBones = this.bones.length; i < nBones; i++) { + var boneName = this.bones[i].name; + var sourceBone = boneDict[boneName]; + if (sourceBone) { + ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio); + } + else { + _Misc_logger__WEBPACK_IMPORTED_MODULE_8__["Logger"].Warn("copyAnimationRange: not same rig, missing source bone " + boneName); + ret = false; + } + } + // do not call createAnimationRange(), since it also is done to bones, which was already done + var range = source.getAnimationRange(name); + if (range) { + this._ranges[name] = new _Animations_animationRange__WEBPACK_IMPORTED_MODULE_5__["AnimationRange"](name, range.from + frameOffset, range.to + frameOffset); + } + return ret; + }; + /** + * Forces the skeleton to go to rest pose + */ + Skeleton.prototype.returnToRest = function () { + for (var index = 0; index < this.bones.length; index++) { + this.bones[index].returnToRest(); + } + }; + Skeleton.prototype._getHighestAnimationFrame = function () { + var ret = 0; + for (var i = 0, nBones = this.bones.length; i < nBones; i++) { + if (this.bones[i].animations[0]) { + var highest = this.bones[i].animations[0].getHighestFrame(); + if (ret < highest) { + ret = highest; + } + } + } + return ret; + }; + /** + * Begin a specific animation range + * @param name defines the name of the range to start + * @param loop defines if looping must be turned on (false by default) + * @param speedRatio defines the speed ratio to apply (1 by default) + * @param onAnimationEnd defines a callback which will be called when animation will end + * @returns a new animatable + */ + Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) { + var range = this.getAnimationRange(name); + if (!range) { + return null; + } + return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd); + }; + /** @hidden */ + Skeleton.prototype._markAsDirty = function () { + this._isDirty = true; + }; + /** @hidden */ + Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) { + this._meshesWithPoseMatrix.push(mesh); + }; + /** @hidden */ + Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) { + var index = this._meshesWithPoseMatrix.indexOf(mesh); + if (index > -1) { + this._meshesWithPoseMatrix.splice(index, 1); + } + }; + Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) { + this.onBeforeComputeObservable.notifyObservers(this); + for (var index = 0; index < this.bones.length; index++) { + var bone = this.bones[index]; + bone._childUpdateId++; + var parentBone = bone.getParent(); + if (parentBone) { + bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix()); + } + else { + if (initialSkinMatrix) { + bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix()); + } + else { + bone.getWorldMatrix().copyFrom(bone.getLocalMatrix()); + } + } + if (bone._index !== -1) { + var mappedIndex = bone._index === null ? index : bone._index; + bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16); + } + } + this._identity.copyToArray(targetMatrix, this.bones.length * 16); + }; + /** + * Build all resources required to render a skeleton + */ + Skeleton.prototype.prepare = function () { + // Update the local matrix of bones with linked transform nodes. + if (this._numBonesWithLinkedTransformNode > 0) { + for (var _i = 0, _a = this.bones; _i < _a.length; _i++) { + var bone_1 = _a[_i]; + if (bone_1._linkedTransformNode) { + // Computing the world matrix also computes the local matrix. + bone_1._linkedTransformNode.computeWorldMatrix(); + bone_1._matrix = bone_1._linkedTransformNode._localMatrix; + bone_1.markAsDirty(); + } + } + } + if (!this._isDirty) { + return; + } + if (this.needInitialSkinMatrix) { + for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) { + var mesh = this._meshesWithPoseMatrix[index]; + var poseMatrix = mesh.getPoseMatrix(); + if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) { + mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1)); + } + if (this._synchronizedWithMesh !== mesh) { + this._synchronizedWithMesh = mesh; + // Prepare bones + for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) { + var bone = this.bones[boneIndex]; + if (!bone.getParent()) { + var matrix = bone.getBaseMatrix(); + matrix.multiplyToRef(poseMatrix, _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Tmp"].Matrix[1]); + bone._updateDifferenceMatrix(_Maths_math__WEBPACK_IMPORTED_MODULE_2__["Tmp"].Matrix[1]); + } + } + } + this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix); + } + } + else { + if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) { + this._transformMatrices = new Float32Array(16 * (this.bones.length + 1)); + if (this.isUsingTextureForMatrices) { + if (this._transformMatrixTexture) { + this._transformMatrixTexture.dispose(); + } + this._transformMatrixTexture = _Materials_Textures_rawTexture__WEBPACK_IMPORTED_MODULE_3__["RawTexture"].CreateRGBATexture(this._transformMatrices, (this.bones.length + 1) * 4, 1, this._scene, false, false, _Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURE_NEAREST_SAMPLINGMODE, _Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_FLOAT); + } + } + this._computeTransformMatrices(this._transformMatrices, null); + if (this.isUsingTextureForMatrices && this._transformMatrixTexture) { + this._transformMatrixTexture.update(this._transformMatrices); + } + } + this._isDirty = false; + this._scene._activeBones.addCount(this.bones.length, false); + }; + /** + * Gets the list of animatables currently running for this skeleton + * @returns an array of animatables + */ + Skeleton.prototype.getAnimatables = function () { + if (!this._animatables || this._animatables.length !== this.bones.length) { + this._animatables = []; + for (var index = 0; index < this.bones.length; index++) { + this._animatables.push(this.bones[index]); + } + } + return this._animatables; + }; + /** + * Clone the current skeleton + * @param name defines the name of the new skeleton + * @param id defines the id of the new skeleton + * @returns the new skeleton + */ + Skeleton.prototype.clone = function (name, id) { + var result = new Skeleton(name, id || name, this._scene); + result.needInitialSkinMatrix = this.needInitialSkinMatrix; + for (var index = 0; index < this.bones.length; index++) { + var source = this.bones[index]; + var parentBone = null; + var parent_1 = source.getParent(); + if (parent_1) { + var parentIndex = this.bones.indexOf(parent_1); + parentBone = result.bones[parentIndex]; + } + var bone = new _bone__WEBPACK_IMPORTED_MODULE_0__["Bone"](source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone()); + _Misc_deepCopier__WEBPACK_IMPORTED_MODULE_9__["DeepCopier"].DeepCopy(source.animations, bone.animations); + } + if (this._ranges) { + result._ranges = {}; + for (var rangeName in this._ranges) { + var range = this._ranges[rangeName]; + if (range) { + result._ranges[rangeName] = range.clone(); + } + } + } + this._isDirty = true; + return result; + }; + /** + * Enable animation blending for this skeleton + * @param blendingSpeed defines the blending speed to apply + * @see http://doc.babylonjs.com/babylon101/animations#animation-blending + */ + Skeleton.prototype.enableBlending = function (blendingSpeed) { + if (blendingSpeed === void 0) { blendingSpeed = 0.01; } + this.bones.forEach(function (bone) { + bone.animations.forEach(function (animation) { + animation.enableBlending = true; + animation.blendingSpeed = blendingSpeed; + }); + }); + }; + /** + * Releases all resources associated with the current skeleton + */ + Skeleton.prototype.dispose = function () { + this._meshesWithPoseMatrix = []; + // Animations + this.getScene().stopAnimation(this); + // Remove from scene + this.getScene().removeSkeleton(this); + if (this._transformMatrixTexture) { + this._transformMatrixTexture.dispose(); + this._transformMatrixTexture = null; + } + }; + /** + * Serialize the skeleton in a JSON object + * @returns a JSON object + */ + Skeleton.prototype.serialize = function () { + var serializationObject = {}; + serializationObject.name = this.name; + serializationObject.id = this.id; + if (this.dimensionsAtRest) { + serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray(); + } + serializationObject.bones = []; + serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix; + for (var index = 0; index < this.bones.length; index++) { + var bone = this.bones[index]; + var parent_2 = bone.getParent(); + var serializedBone = { + parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1, + name: bone.name, + matrix: bone.getBaseMatrix().toArray(), + rest: bone.getRestPose().toArray() + }; + serializationObject.bones.push(serializedBone); + if (bone.length) { + serializedBone.length = bone.length; + } + if (bone.metadata) { + serializedBone.metadata = bone.metadata; + } + if (bone.animations && bone.animations.length > 0) { + serializedBone.animation = bone.animations[0].serialize(); + } + serializationObject.ranges = []; + for (var name in this._ranges) { + var source = this._ranges[name]; + if (!source) { + continue; + } + var range = {}; + range.name = name; + range.from = source.from; + range.to = source.to; + serializationObject.ranges.push(range); + } + } + return serializationObject; + }; + /** + * Creates a new skeleton from serialized data + * @param parsedSkeleton defines the serialized data + * @param scene defines the hosting scene + * @returns a new skeleton + */ + Skeleton.Parse = function (parsedSkeleton, scene) { + var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene); + if (parsedSkeleton.dimensionsAtRest) { + skeleton.dimensionsAtRest = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].FromArray(parsedSkeleton.dimensionsAtRest); + } + skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix; + var index; + for (index = 0; index < parsedSkeleton.bones.length; index++) { + var parsedBone = parsedSkeleton.bones[index]; + var parentBone = null; + if (parsedBone.parentBoneIndex > -1) { + parentBone = skeleton.bones[parsedBone.parentBoneIndex]; + } + var rest = parsedBone.rest ? _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"].FromArray(parsedBone.rest) : null; + var bone = new _bone__WEBPACK_IMPORTED_MODULE_0__["Bone"](parsedBone.name, skeleton, parentBone, _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"].FromArray(parsedBone.matrix), rest); + if (parsedBone.id !== undefined && parsedBone.id !== null) { + bone.id = parsedBone.id; + } + if (parsedBone.length) { + bone.length = parsedBone.length; + } + if (parsedBone.metadata) { + bone.metadata = parsedBone.metadata; + } + if (parsedBone.animation) { + bone.animations.push(_Animations_animation__WEBPACK_IMPORTED_MODULE_4__["Animation"].Parse(parsedBone.animation)); + } + if (parsedBone.linkedTransformNodeId !== undefined && parsedBone.linkedTransformNodeId !== null) { + skeleton._hasWaitingData = true; + bone._waitingTransformNodeId = parsedBone.linkedTransformNodeId; + } + } + // placed after bones, so createAnimationRange can cascade down + if (parsedSkeleton.ranges) { + for (index = 0; index < parsedSkeleton.ranges.length; index++) { + var data = parsedSkeleton.ranges[index]; + skeleton.createAnimationRange(data.name, data.from, data.to); + } + } + return skeleton; + }; + /** + * Compute all node absolute transforms + * @param forceUpdate defines if computation must be done even if cache is up to date + */ + Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) { + if (forceUpdate === void 0) { forceUpdate = false; } + var renderId = this._scene.getRenderId(); + if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) { + this.bones[0].computeAbsoluteTransforms(); + this._lastAbsoluteTransformsUpdateId = renderId; + } + }; + /** + * Gets the root pose matrix + * @returns a matrix + */ + Skeleton.prototype.getPoseMatrix = function () { + var poseMatrix = null; + if (this._meshesWithPoseMatrix.length > 0) { + poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix(); + } + return poseMatrix; + }; + /** + * Sorts bones per internal index + */ + Skeleton.prototype.sortBones = function () { + var bones = new Array(); + var visited = new Array(this.bones.length); + for (var index = 0; index < this.bones.length; index++) { + this._sortBones(index, bones, visited); + } + this.bones = bones; + }; + Skeleton.prototype._sortBones = function (index, bones, visited) { + if (visited[index]) { + return; + } + visited[index] = true; + var bone = this.bones[index]; + if (bone._index === undefined) { + bone._index = index; + } + var parentBone = bone.getParent(); + if (parentBone) { + this._sortBones(this.bones.indexOf(parentBone), bones, visited); + } + bones.push(bone); + }; + return Skeleton; +}()); + + + +/***/ }), + +/***/ "./Cameras/Inputs/BaseCameraPointersInput.ts": +/*!***************************************************!*\ + !*** ./Cameras/Inputs/BaseCameraPointersInput.ts ***! + \***************************************************/ +/*! exports provided: BaseCameraPointersInput */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BaseCameraPointersInput", function() { return BaseCameraPointersInput; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/tools */ "./Misc/tools.ts"); +/* harmony import */ var _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Events/pointerEvents */ "./Events/pointerEvents.ts"); + + + + +/** + * Base class for Camera Pointer Inputs. + * See FollowCameraPointersInput in src/Cameras/Inputs/followCameraPointersInput.ts + * for example usage. + */ +var BaseCameraPointersInput = /** @class */ (function () { + function BaseCameraPointersInput() { + /** + * Defines the buttons associated with the input to handle camera move. + */ + this.buttons = [0, 1, 2]; + } + /** + * Attach the input controls to a specific dom element to get the input from. + * @param element Defines the element the controls should be listened from + * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) + */ + BaseCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) { + var _this = this; + var engine = this.camera.getEngine(); + var previousPinchSquaredDistance = 0; + var previousMultiTouchPanPosition = null; + this.pointA = null; + this.pointB = null; + this._altKey = false; + this._ctrlKey = false; + this._metaKey = false; + this._shiftKey = false; + this._buttonsPressed = 0; + this._pointerInput = function (p, s) { + var evt = p.event; + var isTouch = evt.pointerType === "touch"; + if (engine.isInVRExclusivePointerMode) { + return; + } + if (p.type !== _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERMOVE && + _this.buttons.indexOf(evt.button) === -1) { + return; + } + var srcElement = (evt.srcElement || evt.target); + _this._altKey = evt.altKey; + _this._ctrlKey = evt.ctrlKey; + _this._metaKey = evt.metaKey; + _this._shiftKey = evt.shiftKey; + _this._buttonsPressed = evt.buttons; + if (engine.isPointerLock) { + var offsetX = evt.movementX || + evt.mozMovementX || + evt.webkitMovementX || + evt.msMovementX || + 0; + var offsetY = evt.movementY || + evt.mozMovementY || + evt.webkitMovementY || + evt.msMovementY || + 0; + _this.onTouch(null, offsetX, offsetY); + _this.pointA = null; + _this.pointB = null; + } + else if (p.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERDOWN && srcElement) { + try { + srcElement.setPointerCapture(evt.pointerId); + } + catch (e) { + //Nothing to do with the error. Execution will continue. + } + if (_this.pointA === null) { + _this.pointA = { x: evt.clientX, + y: evt.clientY, + pointerId: evt.pointerId, + type: evt.pointerType }; + } + else if (_this.pointB === null) { + _this.pointB = { x: evt.clientX, + y: evt.clientY, + pointerId: evt.pointerId, + type: evt.pointerType }; + } + _this.onButtonDown(evt); + if (!noPreventDefault) { + evt.preventDefault(); + element.focus(); + } + } + else if (p.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERDOUBLETAP) { + _this.onDoubleTap(evt.pointerType); + } + else if (p.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERUP && srcElement) { + try { + srcElement.releasePointerCapture(evt.pointerId); + } + catch (e) { + //Nothing to do with the error. + } + if (!isTouch) { + _this.pointB = null; // Mouse and pen are mono pointer + } + //would be better to use pointers.remove(evt.pointerId) for multitouch gestures, + //but emptying completely pointers collection is required to fix a bug on iPhone : + //when changing orientation while pinching camera, + //one pointer stay pressed forever if we don't release all pointers + //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected + if (engine._badOS) { + _this.pointA = _this.pointB = null; + } + else { + //only remove the impacted pointer in case of multitouch allowing on most + //platforms switching from rotate to zoom and pan seamlessly. + if (_this.pointB && _this.pointA && _this.pointA.pointerId == evt.pointerId) { + _this.pointA = _this.pointB; + _this.pointB = null; + } + else if (_this.pointA && _this.pointB && + _this.pointB.pointerId == evt.pointerId) { + _this.pointB = null; + } + else { + _this.pointA = _this.pointB = null; + } + } + if (previousPinchSquaredDistance !== 0 || previousMultiTouchPanPosition) { + // Previous pinch data is populated but a button has been lifted + // so pinch has ended. + _this.onMultiTouch(_this.pointA, _this.pointB, previousPinchSquaredDistance, 0, // pinchSquaredDistance + previousMultiTouchPanPosition, null // multiTouchPanPosition + ); + previousPinchSquaredDistance = 0; + previousMultiTouchPanPosition = null; + } + _this.onButtonUp(evt); + if (!noPreventDefault) { + evt.preventDefault(); + } + } + else if (p.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERMOVE) { + if (!noPreventDefault) { + evt.preventDefault(); + } + // One button down + if (_this.pointA && _this.pointB === null) { + var offsetX = evt.clientX - _this.pointA.x; + var offsetY = evt.clientY - _this.pointA.y; + _this.onTouch(_this.pointA, offsetX, offsetY); + _this.pointA.x = evt.clientX; + _this.pointA.y = evt.clientY; + } + // Two buttons down: pinch + else if (_this.pointA && _this.pointB) { + var ed = (_this.pointA.pointerId === evt.pointerId) ? + _this.pointA : _this.pointB; + ed.x = evt.clientX; + ed.y = evt.clientY; + var distX = _this.pointA.x - _this.pointB.x; + var distY = _this.pointA.y - _this.pointB.y; + var pinchSquaredDistance = (distX * distX) + (distY * distY); + var multiTouchPanPosition = { x: (_this.pointA.x + _this.pointB.x) / 2, + y: (_this.pointA.y + _this.pointB.y) / 2, + pointerId: evt.pointerId, + type: p.type }; + _this.onMultiTouch(_this.pointA, _this.pointB, previousPinchSquaredDistance, pinchSquaredDistance, previousMultiTouchPanPosition, multiTouchPanPosition); + previousMultiTouchPanPosition = multiTouchPanPosition; + previousPinchSquaredDistance = pinchSquaredDistance; + } + } + }; + this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERDOWN | _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERUP | + _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERMOVE); + this._onLostFocus = function () { + _this.pointA = _this.pointB = null; + previousPinchSquaredDistance = 0; + previousMultiTouchPanPosition = null; + _this.onLostFocus(); + }; + element.addEventListener("contextmenu", this.onContextMenu.bind(this), false); + _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].RegisterTopRootEvents([ + { name: "blur", handler: this._onLostFocus } + ]); + }; + /** + * Detach the current controls from the specified dom element. + * @param element Defines the element to stop listening the inputs from + */ + BaseCameraPointersInput.prototype.detachControl = function (element) { + if (this._onLostFocus) { + _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].UnregisterTopRootEvents([ + { name: "blur", handler: this._onLostFocus } + ]); + } + if (element && this._observer) { + this.camera.getScene().onPointerObservable.remove(this._observer); + this._observer = null; + if (this.onContextMenu) { + element.removeEventListener("contextmenu", this.onContextMenu); + } + this._onLostFocus = null; + } + this._altKey = false; + this._ctrlKey = false; + this._metaKey = false; + this._shiftKey = false; + this._buttonsPressed = 0; + }; + /** + * Gets the class name of the current input. + * @returns the class name + */ + BaseCameraPointersInput.prototype.getClassName = function () { + return "BaseCameraPointersInput"; + }; + /** + * Get the friendly name associated with the input class. + * @returns the input friendly name + */ + BaseCameraPointersInput.prototype.getSimpleName = function () { + return "pointers"; + }; + /** + * Called on pointer POINTERDOUBLETAP event. + * Override this method to provide functionality on POINTERDOUBLETAP event. + */ + BaseCameraPointersInput.prototype.onDoubleTap = function (type) { + }; + /** + * Called on pointer POINTERMOVE event if only a single touch is active. + * Override this method to provide functionality. + */ + BaseCameraPointersInput.prototype.onTouch = function (point, offsetX, offsetY) { + }; + /** + * Called on pointer POINTERMOVE event if multiple touches are active. + * Override this method to provide functionality. + */ + BaseCameraPointersInput.prototype.onMultiTouch = function (pointA, pointB, previousPinchSquaredDistance, pinchSquaredDistance, previousMultiTouchPanPosition, multiTouchPanPosition) { + }; + /** + * Called on JS contextmenu event. + * Override this method to provide functionality. + */ + BaseCameraPointersInput.prototype.onContextMenu = function (evt) { + evt.preventDefault(); + }; + /** + * Called each time a new POINTERDOWN event occurs. Ie, for each button + * press. + * Override this method to provide functionality. + */ + BaseCameraPointersInput.prototype.onButtonDown = function (evt) { + }; + /** + * Called each time a new POINTERUP event occurs. Ie, for each button + * release. + * Override this method to provide functionality. + */ + BaseCameraPointersInput.prototype.onButtonUp = function (evt) { + }; + /** + * Called when window becomes inactive. + * Override this method to provide functionality. + */ + BaseCameraPointersInput.prototype.onLostFocus = function () { + }; + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], BaseCameraPointersInput.prototype, "buttons", void 0); + return BaseCameraPointersInput; +}()); + + + +/***/ }), + +/***/ "./Cameras/Inputs/arcRotateCameraGamepadInput.ts": +/*!*******************************************************!*\ + !*** ./Cameras/Inputs/arcRotateCameraGamepadInput.ts ***! + \*******************************************************/ +/*! exports provided: ArcRotateCameraGamepadInput */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraGamepadInput", function() { return ArcRotateCameraGamepadInput; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); +/* harmony import */ var _Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Gamepads/gamepad */ "./Gamepads/gamepad.ts"); + + + + +/** + * Manage the gamepad inputs to control an arc rotate camera. + * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs + */ +var ArcRotateCameraGamepadInput = /** @class */ (function () { + function ArcRotateCameraGamepadInput() { + /** + * Defines the gamepad rotation sensiblity. + * This is the threshold from when rotation starts to be accounted for to prevent jittering. + */ + this.gamepadRotationSensibility = 80; + /** + * Defines the gamepad move sensiblity. + * This is the threshold from when moving starts to be accounted for for to prevent jittering. + */ + this.gamepadMoveSensibility = 40; + } + /** + * Attach the input controls to a specific dom element to get the input from. + * @param element Defines the element the controls should be listened from + * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) + */ + ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) { + var _this = this; + var manager = this.camera.getScene().gamepadManager; + this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) { + if (gamepad.type !== _Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_3__["Gamepad"].POSE_ENABLED) { + // prioritize XBOX gamepads. + if (!_this.gamepad || gamepad.type === _Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_3__["Gamepad"].XBOX) { + _this.gamepad = gamepad; + } + } + }); + this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) { + if (_this.gamepad === gamepad) { + _this.gamepad = null; + } + }); + this.gamepad = manager.getGamepadByType(_Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_3__["Gamepad"].XBOX); + }; + /** + * Detach the current controls from the specified dom element. + * @param element Defines the element to stop listening the inputs from + */ + ArcRotateCameraGamepadInput.prototype.detachControl = function (element) { + this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver); + this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver); + this.gamepad = null; + }; + /** + * Update the current camera state depending on the inputs that have been used this frame. + * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. + */ + ArcRotateCameraGamepadInput.prototype.checkInputs = function () { + if (this.gamepad) { + var camera = this.camera; + var RSValues = this.gamepad.rightStick; + if (RSValues) { + if (RSValues.x != 0) { + var normalizedRX = RSValues.x / this.gamepadRotationSensibility; + if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) { + camera.inertialAlphaOffset += normalizedRX; + } + } + if (RSValues.y != 0) { + var normalizedRY = RSValues.y / this.gamepadRotationSensibility; + if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) { + camera.inertialBetaOffset += normalizedRY; + } + } + } + var LSValues = this.gamepad.leftStick; + if (LSValues && LSValues.y != 0) { + var normalizedLY = LSValues.y / this.gamepadMoveSensibility; + if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) { + this.camera.inertialRadiusOffset -= normalizedLY; + } + } + } + }; + /** + * Gets the class name of the current intput. + * @returns the class name + */ + ArcRotateCameraGamepadInput.prototype.getClassName = function () { + return "ArcRotateCameraGamepadInput"; + }; + /** + * Get the friendly name associated with the input class. + * @returns the input friendly name + */ + ArcRotateCameraGamepadInput.prototype.getSimpleName = function () { + return "gamepad"; + }; + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0); + return ArcRotateCameraGamepadInput; +}()); + +_Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__["CameraInputTypes"]["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput; + + +/***/ }), + +/***/ "./Cameras/Inputs/arcRotateCameraKeyboardMoveInput.ts": +/*!************************************************************!*\ + !*** ./Cameras/Inputs/arcRotateCameraKeyboardMoveInput.ts ***! + \************************************************************/ +/*! exports provided: ArcRotateCameraKeyboardMoveInput */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraKeyboardMoveInput", function() { return ArcRotateCameraKeyboardMoveInput; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); +/* harmony import */ var _Events_keyboardEvents__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Events/keyboardEvents */ "./Events/keyboardEvents.ts"); + + + + +/** + * Manage the keyboard inputs to control the movement of an arc rotate camera. + * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs + */ +var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () { + function ArcRotateCameraKeyboardMoveInput() { + /** + * Defines the list of key codes associated with the up action (increase alpha) + */ + this.keysUp = [38]; + /** + * Defines the list of key codes associated with the down action (decrease alpha) + */ + this.keysDown = [40]; + /** + * Defines the list of key codes associated with the left action (increase beta) + */ + this.keysLeft = [37]; + /** + * Defines the list of key codes associated with the right action (decrease beta) + */ + this.keysRight = [39]; + /** + * Defines the list of key codes associated with the reset action. + * Those keys reset the camera to its last stored state (with the method camera.storeState()) + */ + this.keysReset = [220]; + /** + * Defines the panning sensibility of the inputs. + * (How fast is the camera paning) + */ + this.panningSensibility = 50.0; + /** + * Defines the zooming sensibility of the inputs. + * (How fast is the camera zooming) + */ + this.zoomingSensibility = 25.0; + /** + * Defines wether maintaining the alt key down switch the movement mode from + * orientation to zoom. + */ + this.useAltToZoom = true; + /** + * Rotation speed of the camera + */ + this.angularSpeed = 0.01; + this._keys = new Array(); + } + /** + * Attach the input controls to a specific dom element to get the input from. + * @param element Defines the element the controls should be listened from + * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) + */ + ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) { + var _this = this; + if (this._onCanvasBlurObserver) { + return; + } + this._scene = this.camera.getScene(); + this._engine = this._scene.getEngine(); + this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () { + _this._keys = []; + }); + this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) { + var evt = info.event; + if (!evt.metaKey) { + if (info.type === _Events_keyboardEvents__WEBPACK_IMPORTED_MODULE_3__["KeyboardEventTypes"].KEYDOWN) { + _this._ctrlPressed = evt.ctrlKey; + _this._altPressed = evt.altKey; + if (_this.keysUp.indexOf(evt.keyCode) !== -1 || + _this.keysDown.indexOf(evt.keyCode) !== -1 || + _this.keysLeft.indexOf(evt.keyCode) !== -1 || + _this.keysRight.indexOf(evt.keyCode) !== -1 || + _this.keysReset.indexOf(evt.keyCode) !== -1) { + var index = _this._keys.indexOf(evt.keyCode); + if (index === -1) { + _this._keys.push(evt.keyCode); + } + if (evt.preventDefault) { + if (!noPreventDefault) { + evt.preventDefault(); + } + } + } + } + else { + if (_this.keysUp.indexOf(evt.keyCode) !== -1 || + _this.keysDown.indexOf(evt.keyCode) !== -1 || + _this.keysLeft.indexOf(evt.keyCode) !== -1 || + _this.keysRight.indexOf(evt.keyCode) !== -1 || + _this.keysReset.indexOf(evt.keyCode) !== -1) { + var index = _this._keys.indexOf(evt.keyCode); + if (index >= 0) { + _this._keys.splice(index, 1); + } + if (evt.preventDefault) { + if (!noPreventDefault) { + evt.preventDefault(); + } + } + } + } + } + }); + }; + /** + * Detach the current controls from the specified dom element. + * @param element Defines the element to stop listening the inputs from + */ + ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) { + if (this._scene) { + if (this._onKeyboardObserver) { + this._scene.onKeyboardObservable.remove(this._onKeyboardObserver); + } + if (this._onCanvasBlurObserver) { + this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver); + } + this._onKeyboardObserver = null; + this._onCanvasBlurObserver = null; + } + this._keys = []; + }; + /** + * Update the current camera state depending on the inputs that have been used this frame. + * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. + */ + ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () { + if (this._onKeyboardObserver) { + var camera = this.camera; + for (var index = 0; index < this._keys.length; index++) { + var keyCode = this._keys[index]; + if (this.keysLeft.indexOf(keyCode) !== -1) { + if (this._ctrlPressed && this.camera._useCtrlForPanning) { + camera.inertialPanningX -= 1 / this.panningSensibility; + } + else { + camera.inertialAlphaOffset -= this.angularSpeed; + } + } + else if (this.keysUp.indexOf(keyCode) !== -1) { + if (this._ctrlPressed && this.camera._useCtrlForPanning) { + camera.inertialPanningY += 1 / this.panningSensibility; + } + else if (this._altPressed && this.useAltToZoom) { + camera.inertialRadiusOffset += 1 / this.zoomingSensibility; + } + else { + camera.inertialBetaOffset -= this.angularSpeed; + } + } + else if (this.keysRight.indexOf(keyCode) !== -1) { + if (this._ctrlPressed && this.camera._useCtrlForPanning) { + camera.inertialPanningX += 1 / this.panningSensibility; + } + else { + camera.inertialAlphaOffset += this.angularSpeed; + } + } + else if (this.keysDown.indexOf(keyCode) !== -1) { + if (this._ctrlPressed && this.camera._useCtrlForPanning) { + camera.inertialPanningY -= 1 / this.panningSensibility; + } + else if (this._altPressed && this.useAltToZoom) { + camera.inertialRadiusOffset -= 1 / this.zoomingSensibility; + } + else { + camera.inertialBetaOffset += this.angularSpeed; + } + } + else if (this.keysReset.indexOf(keyCode) !== -1) { + if (camera.useInputToRestoreState) { + camera.restoreState(); + } + } + } + } + }; + /** + * Gets the class name of the current intput. + * @returns the class name + */ + ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () { + return "ArcRotateCameraKeyboardMoveInput"; + }; + /** + * Get the friendly name associated with the input class. + * @returns the input friendly name + */ + ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () { + return "keyboard"; + }; + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ArcRotateCameraKeyboardMoveInput.prototype, "angularSpeed", void 0); + return ArcRotateCameraKeyboardMoveInput; +}()); + +_Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__["CameraInputTypes"]["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput; + + +/***/ }), + +/***/ "./Cameras/Inputs/arcRotateCameraMouseWheelInput.ts": +/*!**********************************************************!*\ + !*** ./Cameras/Inputs/arcRotateCameraMouseWheelInput.ts ***! + \**********************************************************/ +/*! exports provided: ArcRotateCameraMouseWheelInput */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraMouseWheelInput", function() { return ArcRotateCameraMouseWheelInput; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); +/* harmony import */ var _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Events/pointerEvents */ "./Events/pointerEvents.ts"); +/* harmony import */ var _Maths_math_scalar__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Maths/math.scalar */ "./Maths/math.scalar.ts"); + + + + + +/** + * Manage the mouse wheel inputs to control an arc rotate camera. + * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs + */ +var ArcRotateCameraMouseWheelInput = /** @class */ (function () { + function ArcRotateCameraMouseWheelInput() { + /** + * Gets or Set the mouse wheel precision or how fast is the camera zooming. + */ + this.wheelPrecision = 3.0; + /** + * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0. + * It defines the percentage of current camera.radius to use as delta when wheel is used. + */ + this.wheelDeltaPercentage = 0; + } + ArcRotateCameraMouseWheelInput.prototype.computeDeltaFromMouseWheelLegacyEvent = function (mouseWheelLegacyEvent, radius) { + var delta = 0; + var wheelDelta = (mouseWheelLegacyEvent.wheelDelta * 0.01 * this.wheelDeltaPercentage) * radius; + if (mouseWheelLegacyEvent.wheelDelta > 0) { + delta = wheelDelta / (1.0 + this.wheelDeltaPercentage); + } + else { + delta = wheelDelta * (1.0 + this.wheelDeltaPercentage); + } + return delta; + }; + /** + * Attach the input controls to a specific dom element to get the input from. + * @param element Defines the element the controls should be listened from + * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) + */ + ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) { + var _this = this; + this._wheel = function (p, s) { + //sanity check - this should be a PointerWheel event. + if (p.type !== _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERWHEEL) { + return; + } + var event = p.event; + var delta = 0; + var mouseWheelLegacyEvent = event; + if (mouseWheelLegacyEvent.wheelDelta) { + if (_this.wheelDeltaPercentage) { + delta = _this.computeDeltaFromMouseWheelLegacyEvent(mouseWheelLegacyEvent, _this.camera.radius); + // If zooming in, estimate the target radius and use that to compute the delta for inertia + // this will stop multiple scroll events zooming in from adding too much inertia + if (delta > 0) { + var estimatedTargetRadius = _this.camera.radius; + var targetInertia = _this.camera.inertialRadiusOffset + delta; + for (var i = 0; i < 20 && Math.abs(targetInertia) > 0.001; i++) { + estimatedTargetRadius -= targetInertia; + targetInertia *= _this.camera.inertia; + } + estimatedTargetRadius = _Maths_math_scalar__WEBPACK_IMPORTED_MODULE_4__["Scalar"].Clamp(estimatedTargetRadius, 0, Number.MAX_VALUE); + delta = _this.computeDeltaFromMouseWheelLegacyEvent(mouseWheelLegacyEvent, estimatedTargetRadius); + } + } + else { + delta = mouseWheelLegacyEvent.wheelDelta / (_this.wheelPrecision * 40); + } + } + else { + var deltaValue = event.deltaY || event.detail; + delta = -deltaValue / _this.wheelPrecision; + } + if (delta) { + _this.camera.inertialRadiusOffset += delta; + } + if (event.preventDefault) { + if (!noPreventDefault) { + event.preventDefault(); + } + } + }; + this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERWHEEL); + }; + /** + * Detach the current controls from the specified dom element. + * @param element Defines the element to stop listening the inputs from + */ + ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) { + if (this._observer && element) { + this.camera.getScene().onPointerObservable.remove(this._observer); + this._observer = null; + this._wheel = null; + } + }; + /** + * Gets the class name of the current intput. + * @returns the class name + */ + ArcRotateCameraMouseWheelInput.prototype.getClassName = function () { + return "ArcRotateCameraMouseWheelInput"; + }; + /** + * Get the friendly name associated with the input class. + * @returns the input friendly name + */ + ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () { + return "mousewheel"; + }; + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0); + return ArcRotateCameraMouseWheelInput; +}()); + +_Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__["CameraInputTypes"]["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput; + + +/***/ }), + +/***/ "./Cameras/Inputs/arcRotateCameraPointersInput.ts": +/*!********************************************************!*\ + !*** ./Cameras/Inputs/arcRotateCameraPointersInput.ts ***! + \********************************************************/ +/*! exports provided: ArcRotateCameraPointersInput */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraPointersInput", function() { return ArcRotateCameraPointersInput; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); +/* harmony import */ var _Cameras_Inputs_BaseCameraPointersInput__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Cameras/Inputs/BaseCameraPointersInput */ "./Cameras/Inputs/BaseCameraPointersInput.ts"); + + + + +/** + * Manage the pointers inputs to control an arc rotate camera. + * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs + */ +var ArcRotateCameraPointersInput = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ArcRotateCameraPointersInput, _super); + function ArcRotateCameraPointersInput() { + var _this = _super !== null && _super.apply(this, arguments) || this; + /** + * Defines the buttons associated with the input to handle camera move. + */ + _this.buttons = [0, 1, 2]; + /** + * Defines the pointer angular sensibility along the X axis or how fast is + * the camera rotating. + */ + _this.angularSensibilityX = 1000.0; + /** + * Defines the pointer angular sensibility along the Y axis or how fast is + * the camera rotating. + */ + _this.angularSensibilityY = 1000.0; + /** + * Defines the pointer pinch precision or how fast is the camera zooming. + */ + _this.pinchPrecision = 12.0; + /** + * pinchDeltaPercentage will be used instead of pinchPrecision if different + * from 0. + * It defines the percentage of current camera.radius to use as delta when + * pinch zoom is used. + */ + _this.pinchDeltaPercentage = 0; + /** + * Defines the pointer panning sensibility or how fast is the camera moving. + */ + _this.panningSensibility = 1000.0; + /** + * Defines whether panning (2 fingers swipe) is enabled through multitouch. + */ + _this.multiTouchPanning = true; + /** + * Defines whether panning is enabled for both pan (2 fingers swipe) and + * zoom (pinch) through multitouch. + */ + _this.multiTouchPanAndZoom = true; + /** + * Revers pinch action direction. + */ + _this.pinchInwards = true; + _this._isPanClick = false; + _this._twoFingerActivityCount = 0; + _this._isPinching = false; + return _this; + } + /** + * Gets the class name of the current input. + * @returns the class name + */ + ArcRotateCameraPointersInput.prototype.getClassName = function () { + return "ArcRotateCameraPointersInput"; + }; + /** + * Called on pointer POINTERMOVE event if only a single touch is active. + */ + ArcRotateCameraPointersInput.prototype.onTouch = function (point, offsetX, offsetY) { + if (this.panningSensibility !== 0 && + ((this._ctrlKey && this.camera._useCtrlForPanning) || this._isPanClick)) { + this.camera.inertialPanningX += -offsetX / this.panningSensibility; + this.camera.inertialPanningY += offsetY / this.panningSensibility; + } + else { + this.camera.inertialAlphaOffset -= offsetX / this.angularSensibilityX; + this.camera.inertialBetaOffset -= offsetY / this.angularSensibilityY; + } + }; + /** + * Called on pointer POINTERDOUBLETAP event. + */ + ArcRotateCameraPointersInput.prototype.onDoubleTap = function (type) { + if (this.camera.useInputToRestoreState) { + this.camera.restoreState(); + } + }; + /** + * Called on pointer POINTERMOVE event if multiple touches are active. + */ + ArcRotateCameraPointersInput.prototype.onMultiTouch = function (pointA, pointB, previousPinchSquaredDistance, pinchSquaredDistance, previousMultiTouchPanPosition, multiTouchPanPosition) { + if (previousPinchSquaredDistance === 0 && previousMultiTouchPanPosition === null) { + // First time this method is called for new pinch. + // Next time this is called there will be a + // previousPinchSquaredDistance and pinchSquaredDistance to compare. + return; + } + if (pinchSquaredDistance === 0 && multiTouchPanPosition === null) { + // Last time this method is called at the end of a pinch. + return; + } + var direction = this.pinchInwards ? 1 : -1; + if (this.multiTouchPanAndZoom) { + if (this.pinchDeltaPercentage) { + this.camera.inertialRadiusOffset += + (pinchSquaredDistance - previousPinchSquaredDistance) * 0.001 * + this.camera.radius * this.pinchDeltaPercentage; + } + else { + this.camera.inertialRadiusOffset += + (pinchSquaredDistance - previousPinchSquaredDistance) / + (this.pinchPrecision * direction * + (this.angularSensibilityX + this.angularSensibilityY) / 2); + } + if (this.panningSensibility !== 0 && + previousMultiTouchPanPosition && multiTouchPanPosition) { + var moveDeltaX = multiTouchPanPosition.x - previousMultiTouchPanPosition.x; + var moveDeltaY = multiTouchPanPosition.y - previousMultiTouchPanPosition.y; + this.camera.inertialPanningX += -moveDeltaX / this.panningSensibility; + this.camera.inertialPanningY += moveDeltaY / this.panningSensibility; + } + } + else { + this._twoFingerActivityCount++; + var previousPinchDistance = Math.sqrt(previousPinchSquaredDistance); + var pinchDistance = Math.sqrt(pinchSquaredDistance); + if (this._isPinching || + (this._twoFingerActivityCount < 20 && + Math.abs(pinchDistance - previousPinchDistance) > + this.camera.pinchToPanMaxDistance)) { + // Since pinch has not been active long, assume we intend to zoom. + if (this.pinchDeltaPercentage) { + this.camera.inertialRadiusOffset += + (pinchSquaredDistance - previousPinchSquaredDistance) * 0.001 * + this.camera.radius * this.pinchDeltaPercentage; + } + else { + this.camera.inertialRadiusOffset += + (pinchSquaredDistance - previousPinchSquaredDistance) / + (this.pinchPrecision * direction * + (this.angularSensibilityX + this.angularSensibilityY) / 2); + } + // Since we are pinching, remain pinching on next iteration. + this._isPinching = true; + } + else { + // Pause between pinch starting and moving implies not a zoom event. + // Pan instead. + if (this.panningSensibility !== 0 && this.multiTouchPanning && + multiTouchPanPosition && previousMultiTouchPanPosition) { + var moveDeltaX = multiTouchPanPosition.x - previousMultiTouchPanPosition.x; + var moveDeltaY = multiTouchPanPosition.y - previousMultiTouchPanPosition.y; + this.camera.inertialPanningX += -moveDeltaX / this.panningSensibility; + this.camera.inertialPanningY += moveDeltaY / this.panningSensibility; + } + } + } + }; + /** + * Called each time a new POINTERDOWN event occurs. Ie, for each button + * press. + */ + ArcRotateCameraPointersInput.prototype.onButtonDown = function (evt) { + this._isPanClick = evt.button === this.camera._panningMouseButton; + }; + /** + * Called each time a new POINTERUP event occurs. Ie, for each button + * release. + */ + ArcRotateCameraPointersInput.prototype.onButtonUp = function (evt) { + this._twoFingerActivityCount = 0; + this._isPinching = false; + }; + /** + * Called when window becomes inactive. + */ + ArcRotateCameraPointersInput.prototype.onLostFocus = function () { + this._isPanClick = false; + this._twoFingerActivityCount = 0; + this._isPinching = false; + }; + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ArcRotateCameraPointersInput.prototype, "buttons", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0); + return ArcRotateCameraPointersInput; +}(_Cameras_Inputs_BaseCameraPointersInput__WEBPACK_IMPORTED_MODULE_3__["BaseCameraPointersInput"])); + +_Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__["CameraInputTypes"]["ArcRotateCameraPointersInput"] = + ArcRotateCameraPointersInput; + + +/***/ }), + +/***/ "./Cameras/Inputs/arcRotateCameraVRDeviceOrientationInput.ts": +/*!*******************************************************************!*\ + !*** ./Cameras/Inputs/arcRotateCameraVRDeviceOrientationInput.ts ***! + \*******************************************************************/ +/*! exports provided: ArcRotateCameraVRDeviceOrientationInput */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraVRDeviceOrientationInput", function() { return ArcRotateCameraVRDeviceOrientationInput; }); +/* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); +/* harmony import */ var _Cameras_arcRotateCameraInputsManager__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Cameras/arcRotateCameraInputsManager */ "./Cameras/arcRotateCameraInputsManager.ts"); + + +/** + * Add orientation input support to the input manager. + * @returns the current input manager + */ +_Cameras_arcRotateCameraInputsManager__WEBPACK_IMPORTED_MODULE_1__["ArcRotateCameraInputsManager"].prototype.addVRDeviceOrientation = function () { + this.add(new ArcRotateCameraVRDeviceOrientationInput()); + return this; +}; +/** + * Manage the device orientation inputs (gyroscope) to control an arc rotate camera. + * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs + */ +var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () { + /** + * Instantiate a new ArcRotateCameraVRDeviceOrientationInput. + */ + function ArcRotateCameraVRDeviceOrientationInput() { + /** + * Defines a correction factor applied on the alpha value retrieved from the orientation events. + */ + this.alphaCorrection = 1; + /** + * Defines a correction factor applied on the gamma value retrieved from the orientation events. + */ + this.gammaCorrection = 1; + this._alpha = 0; + this._gamma = 0; + this._dirty = false; + this._deviceOrientationHandler = this._onOrientationEvent.bind(this); + } + /** + * Attach the input controls to a specific dom element to get the input from. + * @param element Defines the element the controls should be listened from + * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) + */ + ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) { + this.camera.attachControl(element, noPreventDefault); + window.addEventListener("deviceorientation", this._deviceOrientationHandler); + }; + /** @hidden */ + ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) { + if (evt.alpha !== null) { + this._alpha = (+evt.alpha | 0) * this.alphaCorrection; + } + if (evt.gamma !== null) { + this._gamma = (+evt.gamma | 0) * this.gammaCorrection; + } + this._dirty = true; + }; + /** + * Update the current camera state depending on the inputs that have been used this frame. + * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. + */ + ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () { + if (this._dirty) { + this._dirty = false; + if (this._gamma < 0) { + this._gamma = 180 + this._gamma; + } + this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2; + this.camera.beta = (this._gamma / 180.0 * Math.PI); + } + }; + /** + * Detach the current controls from the specified dom element. + * @param element Defines the element to stop listening the inputs from + */ + ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) { + window.removeEventListener("deviceorientation", this._deviceOrientationHandler); + }; + /** + * Gets the class name of the current intput. + * @returns the class name + */ + ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () { + return "ArcRotateCameraVRDeviceOrientationInput"; + }; + /** + * Get the friendly name associated with the input class. + * @returns the input friendly name + */ + ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () { + return "VRDeviceOrientation"; + }; + return ArcRotateCameraVRDeviceOrientationInput; +}()); + +_Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_0__["CameraInputTypes"]["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput; + + +/***/ }), + +/***/ "./Cameras/Inputs/flyCameraKeyboardInput.ts": +/*!**************************************************!*\ + !*** ./Cameras/Inputs/flyCameraKeyboardInput.ts ***! + \**************************************************/ +/*! exports provided: FlyCameraKeyboardInput */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FlyCameraKeyboardInput", function() { return FlyCameraKeyboardInput; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); +/* harmony import */ var _Events_keyboardEvents__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Events/keyboardEvents */ "./Events/keyboardEvents.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); + + + + + +/** + * Listen to keyboard events to control the camera. + * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs + */ +var FlyCameraKeyboardInput = /** @class */ (function () { + function FlyCameraKeyboardInput() { + /** + * The list of keyboard keys used to control the forward move of the camera. + */ + this.keysForward = [87]; + /** + * The list of keyboard keys used to control the backward move of the camera. + */ + this.keysBackward = [83]; + /** + * The list of keyboard keys used to control the forward move of the camera. + */ + this.keysUp = [69]; + /** + * The list of keyboard keys used to control the backward move of the camera. + */ + this.keysDown = [81]; + /** + * The list of keyboard keys used to control the right strafe move of the camera. + */ + this.keysRight = [68]; + /** + * The list of keyboard keys used to control the left strafe move of the camera. + */ + this.keysLeft = [65]; + this._keys = new Array(); + } + /** + * Attach the input controls to a specific dom element to get the input from. + * @param element Defines the element the controls should be listened from + * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) + */ + FlyCameraKeyboardInput.prototype.attachControl = function (element, noPreventDefault) { + var _this = this; + if (this._onCanvasBlurObserver) { + return; + } + this._scene = this.camera.getScene(); + this._engine = this._scene.getEngine(); + this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () { + _this._keys = []; + }); + this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) { + var evt = info.event; + if (info.type === _Events_keyboardEvents__WEBPACK_IMPORTED_MODULE_3__["KeyboardEventTypes"].KEYDOWN) { + if (_this.keysForward.indexOf(evt.keyCode) !== -1 || + _this.keysBackward.indexOf(evt.keyCode) !== -1 || + _this.keysUp.indexOf(evt.keyCode) !== -1 || + _this.keysDown.indexOf(evt.keyCode) !== -1 || + _this.keysLeft.indexOf(evt.keyCode) !== -1 || + _this.keysRight.indexOf(evt.keyCode) !== -1) { + var index = _this._keys.indexOf(evt.keyCode); + if (index === -1) { + _this._keys.push(evt.keyCode); + } + if (!noPreventDefault) { + evt.preventDefault(); + } + } + } + else { + if (_this.keysForward.indexOf(evt.keyCode) !== -1 || + _this.keysBackward.indexOf(evt.keyCode) !== -1 || + _this.keysUp.indexOf(evt.keyCode) !== -1 || + _this.keysDown.indexOf(evt.keyCode) !== -1 || + _this.keysLeft.indexOf(evt.keyCode) !== -1 || + _this.keysRight.indexOf(evt.keyCode) !== -1) { + var index = _this._keys.indexOf(evt.keyCode); + if (index >= 0) { + _this._keys.splice(index, 1); + } + if (!noPreventDefault) { + evt.preventDefault(); + } + } + } + }); + }; + /** + * Detach the current controls from the specified dom element. + * @param element Defines the element to stop listening the inputs from + */ + FlyCameraKeyboardInput.prototype.detachControl = function (element) { + if (this._scene) { + if (this._onKeyboardObserver) { + this._scene.onKeyboardObservable.remove(this._onKeyboardObserver); + } + if (this._onCanvasBlurObserver) { + this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver); + } + this._onKeyboardObserver = null; + this._onCanvasBlurObserver = null; + } + this._keys = []; + }; + /** + * Gets the class name of the current intput. + * @returns the class name + */ + FlyCameraKeyboardInput.prototype.getClassName = function () { + return "FlyCameraKeyboardInput"; + }; + /** @hidden */ + FlyCameraKeyboardInput.prototype._onLostFocus = function (e) { + this._keys = []; + }; + /** + * Get the friendly name associated with the input class. + * @returns the input friendly name + */ + FlyCameraKeyboardInput.prototype.getSimpleName = function () { + return "keyboard"; + }; + /** + * Update the current camera state depending on the inputs that have been used this frame. + * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. + */ + FlyCameraKeyboardInput.prototype.checkInputs = function () { + if (this._onKeyboardObserver) { + var camera = this.camera; + // Keyboard + for (var index = 0; index < this._keys.length; index++) { + var keyCode = this._keys[index]; + var speed = camera._computeLocalCameraSpeed(); + if (this.keysForward.indexOf(keyCode) !== -1) { + camera._localDirection.copyFromFloats(0, 0, speed); + } + else if (this.keysBackward.indexOf(keyCode) !== -1) { + camera._localDirection.copyFromFloats(0, 0, -speed); + } + else if (this.keysUp.indexOf(keyCode) !== -1) { + camera._localDirection.copyFromFloats(0, speed, 0); + } + else if (this.keysDown.indexOf(keyCode) !== -1) { + camera._localDirection.copyFromFloats(0, -speed, 0); + } + else if (this.keysRight.indexOf(keyCode) !== -1) { + camera._localDirection.copyFromFloats(speed, 0, 0); + } + else if (this.keysLeft.indexOf(keyCode) !== -1) { + camera._localDirection.copyFromFloats(-speed, 0, 0); + } + if (camera.getScene().useRightHandedSystem) { + camera._localDirection.z *= -1; + } + camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix); + _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"].TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection); + camera.cameraDirection.addInPlace(camera._transformedDirection); + } + } + }; + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], FlyCameraKeyboardInput.prototype, "keysForward", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], FlyCameraKeyboardInput.prototype, "keysBackward", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], FlyCameraKeyboardInput.prototype, "keysUp", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], FlyCameraKeyboardInput.prototype, "keysDown", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], FlyCameraKeyboardInput.prototype, "keysRight", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], FlyCameraKeyboardInput.prototype, "keysLeft", void 0); + return FlyCameraKeyboardInput; +}()); + +_Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__["CameraInputTypes"]["FlyCameraKeyboardInput"] = FlyCameraKeyboardInput; + + +/***/ }), + +/***/ "./Cameras/Inputs/flyCameraMouseInput.ts": +/*!***********************************************!*\ + !*** ./Cameras/Inputs/flyCameraMouseInput.ts ***! + \***********************************************/ +/*! exports provided: FlyCameraMouseInput */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FlyCameraMouseInput", function() { return FlyCameraMouseInput; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); +/* harmony import */ var _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Events/pointerEvents */ "./Events/pointerEvents.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); + + + + + +/** + * Listen to mouse events to control the camera. + * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs + */ +var FlyCameraMouseInput = /** @class */ (function () { + /** + * Listen to mouse events to control the camera. + * @param touchEnabled Define if touch is enabled. (Default is true.) + * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs + */ + function FlyCameraMouseInput(touchEnabled) { + if (touchEnabled === void 0) { touchEnabled = true; } + /** + * Defines the buttons associated with the input to handle camera rotation. + */ + this.buttons = [0, 1, 2]; + /** + * Assign buttons for Yaw control. + */ + this.buttonsYaw = [-1, 0, 1]; + /** + * Assign buttons for Pitch control. + */ + this.buttonsPitch = [-1, 0, 1]; + /** + * Assign buttons for Roll control. + */ + this.buttonsRoll = [2]; + /** + * Detect if any button is being pressed while mouse is moved. + * -1 = Mouse locked. + * 0 = Left button. + * 1 = Middle Button. + * 2 = Right Button. + */ + this.activeButton = -1; + /** + * Defines the pointer's angular sensibility, to control the camera rotation speed. + * Higher values reduce its sensitivity. + */ + this.angularSensibility = 1000.0; + this.previousPosition = null; + } + /** + * Attach the mouse control to the HTML DOM element. + * @param element Defines the element that listens to the input events. + * @param noPreventDefault Defines whether events caught by the controls should call preventdefault(). + */ + FlyCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) { + var _this = this; + this.element = element; + this.noPreventDefault = noPreventDefault; + this._observer = this.camera.getScene().onPointerObservable.add(function (p, s) { + _this._pointerInput(p, s); + }, _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERDOWN | _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERUP | _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERMOVE); + // Correct Roll by rate, if enabled. + this._rollObserver = this.camera.getScene().onBeforeRenderObservable.add(function () { + if (_this.camera.rollCorrect) { + _this.camera.restoreRoll(_this.camera.rollCorrect); + } + }); + // Helper function to keep 'this'. + this._mousemoveCallback = function (e) { + _this._onMouseMove(e); + }; + element.addEventListener("mousemove", this._mousemoveCallback, false); + }; + /** + * Detach the current controls from the specified dom element. + * @param element Defines the element to stop listening the inputs from + */ + FlyCameraMouseInput.prototype.detachControl = function (element) { + if (this._observer && element) { + this.camera.getScene().onPointerObservable.remove(this._observer); + this.camera.getScene().onBeforeRenderObservable.remove(this._rollObserver); + if (this._mousemoveCallback) { + element.removeEventListener("mousemove", this._mousemoveCallback); + } + this._observer = null; + this._rollObserver = null; + this.previousPosition = null; + this.noPreventDefault = undefined; + } + }; + /** + * Gets the class name of the current input. + * @returns the class name. + */ + FlyCameraMouseInput.prototype.getClassName = function () { + return "FlyCameraMouseInput"; + }; + /** + * Get the friendly name associated with the input class. + * @returns the input's friendly name. + */ + FlyCameraMouseInput.prototype.getSimpleName = function () { + return "mouse"; + }; + // Track mouse movement, when the pointer is not locked. + FlyCameraMouseInput.prototype._pointerInput = function (p, s) { + var e = p.event; + var camera = this.camera; + var engine = camera.getEngine(); + if (engine.isInVRExclusivePointerMode) { + return; + } + if (!this.touchEnabled && e.pointerType === "touch") { + return; + } + // Mouse is moved but an unknown mouse button is pressed. + if (p.type !== _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERMOVE && this.buttons.indexOf(e.button) === -1) { + return; + } + var srcElement = (e.srcElement || e.target); + // Mouse down. + if (p.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERDOWN && srcElement) { + try { + srcElement.setPointerCapture(e.pointerId); + } + catch (e) { + // Nothing to do with the error. Execution continues. + } + this.previousPosition = { + x: e.clientX, + y: e.clientY + }; + this.activeButton = e.button; + if (!this.noPreventDefault) { + e.preventDefault(); + this.element.focus(); + } + } + else + // Mouse up. + if (p.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERUP && srcElement) { + try { + srcElement.releasePointerCapture(e.pointerId); + } + catch (e) { + // Nothing to do with the error. Execution continues. + } + this.activeButton = -1; + this.previousPosition = null; + if (!this.noPreventDefault) { + e.preventDefault(); + } + } + else + // Mouse move. + if (p.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERMOVE) { + if (!this.previousPosition || engine.isPointerLock) { + return; + } + var offsetX = e.clientX - this.previousPosition.x; + var offsetY = e.clientY - this.previousPosition.y; + this.rotateCamera(offsetX, offsetY); + this.previousPosition = { + x: e.clientX, + y: e.clientY + }; + if (!this.noPreventDefault) { + e.preventDefault(); + } + } + }; + // Track mouse movement, when pointer is locked. + FlyCameraMouseInput.prototype._onMouseMove = function (e) { + var camera = this.camera; + var engine = camera.getEngine(); + if (!engine.isPointerLock || engine.isInVRExclusivePointerMode) { + return; + } + var offsetX = e.movementX || e.mozMovementX || e.webkitMovementX || e.msMovementX || 0; + var offsetY = e.movementY || e.mozMovementY || e.webkitMovementY || e.msMovementY || 0; + this.rotateCamera(offsetX, offsetY); + this.previousPosition = null; + if (!this.noPreventDefault) { + e.preventDefault(); + } + }; + /** + * Rotate camera by mouse offset. + */ + FlyCameraMouseInput.prototype.rotateCamera = function (offsetX, offsetY) { + var _this = this; + var camera = this.camera; + var scene = this.camera.getScene(); + if (scene.useRightHandedSystem) { + offsetX *= -1; + } + if (camera.parent && camera.parent._getWorldMatrixDeterminant() < 0) { + offsetX *= -1; + } + var x = offsetX / this.angularSensibility; + var y = offsetY / this.angularSensibility; + // Initialize to current rotation. + var currentRotation = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Quaternion"].RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, camera.rotation.z); + var rotationChange; + // Pitch. + if (this.buttonsPitch.some(function (v) { return v === _this.activeButton; })) { + // Apply change in Radians to vector Angle. + rotationChange = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Quaternion"].RotationAxis(_Maths_math__WEBPACK_IMPORTED_MODULE_4__["Axis"].X, y); + // Apply Pitch to quaternion. + currentRotation.multiplyInPlace(rotationChange); + } + // Yaw. + if (this.buttonsYaw.some(function (v) { return v === _this.activeButton; })) { + // Apply change in Radians to vector Angle. + rotationChange = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Quaternion"].RotationAxis(_Maths_math__WEBPACK_IMPORTED_MODULE_4__["Axis"].Y, x); + // Apply Yaw to quaternion. + currentRotation.multiplyInPlace(rotationChange); + // Add Roll, if banked turning is enabled, within Roll limit. + var limit = (camera.bankedTurnLimit) + camera._trackRoll; // Defaults to 90° plus manual roll. + if (camera.bankedTurn && -limit < camera.rotation.z && camera.rotation.z < limit) { + var bankingDelta = camera.bankedTurnMultiplier * -x; + // Apply change in Radians to vector Angle. + rotationChange = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Quaternion"].RotationAxis(_Maths_math__WEBPACK_IMPORTED_MODULE_4__["Axis"].Z, bankingDelta); + // Apply Yaw to quaternion. + currentRotation.multiplyInPlace(rotationChange); + } + } + // Roll. + if (this.buttonsRoll.some(function (v) { return v === _this.activeButton; })) { + // Apply change in Radians to vector Angle. + rotationChange = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Quaternion"].RotationAxis(_Maths_math__WEBPACK_IMPORTED_MODULE_4__["Axis"].Z, -x); + // Track Rolling. + camera._trackRoll -= x; + // Apply Pitch to quaternion. + currentRotation.multiplyInPlace(rotationChange); + } + // Apply rotationQuaternion to Euler camera.rotation. + currentRotation.toEulerAnglesToRef(camera.rotation); + }; + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], FlyCameraMouseInput.prototype, "buttons", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], FlyCameraMouseInput.prototype, "angularSensibility", void 0); + return FlyCameraMouseInput; +}()); + +_Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__["CameraInputTypes"]["FlyCameraMouseInput"] = FlyCameraMouseInput; + + +/***/ }), + +/***/ "./Cameras/Inputs/followCameraKeyboardMoveInput.ts": +/*!*********************************************************!*\ + !*** ./Cameras/Inputs/followCameraKeyboardMoveInput.ts ***! + \*********************************************************/ +/*! exports provided: FollowCameraKeyboardMoveInput */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FollowCameraKeyboardMoveInput", function() { return FollowCameraKeyboardMoveInput; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _Events_keyboardEvents__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Events/keyboardEvents */ "./Events/keyboardEvents.ts"); + + + + +/** + * Manage the keyboard inputs to control the movement of a follow camera. + * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs + */ +var FollowCameraKeyboardMoveInput = /** @class */ (function () { + function FollowCameraKeyboardMoveInput() { + /** + * Defines the list of key codes associated with the up action (increase heightOffset) + */ + this.keysHeightOffsetIncr = [38]; + /** + * Defines the list of key codes associated with the down action (decrease heightOffset) + */ + this.keysHeightOffsetDecr = [40]; + /** + * Defines whether the Alt modifier key is required to move up/down (alter heightOffset) + */ + this.keysHeightOffsetModifierAlt = false; + /** + * Defines whether the Ctrl modifier key is required to move up/down (alter heightOffset) + */ + this.keysHeightOffsetModifierCtrl = false; + /** + * Defines whether the Shift modifier key is required to move up/down (alter heightOffset) + */ + this.keysHeightOffsetModifierShift = false; + /** + * Defines the list of key codes associated with the left action (increase rotationOffset) + */ + this.keysRotationOffsetIncr = [37]; + /** + * Defines the list of key codes associated with the right action (decrease rotationOffset) + */ + this.keysRotationOffsetDecr = [39]; + /** + * Defines whether the Alt modifier key is required to move left/right (alter rotationOffset) + */ + this.keysRotationOffsetModifierAlt = false; + /** + * Defines whether the Ctrl modifier key is required to move left/right (alter rotationOffset) + */ + this.keysRotationOffsetModifierCtrl = false; + /** + * Defines whether the Shift modifier key is required to move left/right (alter rotationOffset) + */ + this.keysRotationOffsetModifierShift = false; + /** + * Defines the list of key codes associated with the zoom-in action (decrease radius) + */ + this.keysRadiusIncr = [40]; + /** + * Defines the list of key codes associated with the zoom-out action (increase radius) + */ + this.keysRadiusDecr = [38]; + /** + * Defines whether the Alt modifier key is required to zoom in/out (alter radius value) + */ + this.keysRadiusModifierAlt = true; + /** + * Defines whether the Ctrl modifier key is required to zoom in/out (alter radius value) + */ + this.keysRadiusModifierCtrl = false; + /** + * Defines whether the Shift modifier key is required to zoom in/out (alter radius value) + */ + this.keysRadiusModifierShift = false; + /** + * Defines the rate of change of heightOffset. + */ + this.heightSensibility = 1; + /** + * Defines the rate of change of rotationOffset. + */ + this.rotationSensibility = 1; + /** + * Defines the rate of change of radius. + */ + this.radiusSensibility = 1; + this._keys = new Array(); + } + /** + * Attach the input controls to a specific dom element to get the input from. + * @param element Defines the element the controls should be listened from + * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) + */ + FollowCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) { + var _this = this; + if (this._onCanvasBlurObserver) { + return; + } + this._scene = this.camera.getScene(); + this._engine = this._scene.getEngine(); + this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () { + _this._keys = []; + }); + this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) { + var evt = info.event; + if (!evt.metaKey) { + if (info.type === _Events_keyboardEvents__WEBPACK_IMPORTED_MODULE_3__["KeyboardEventTypes"].KEYDOWN) { + _this._ctrlPressed = evt.ctrlKey; + _this._altPressed = evt.altKey; + _this._shiftPressed = evt.shiftKey; + if (_this.keysHeightOffsetIncr.indexOf(evt.keyCode) !== -1 || + _this.keysHeightOffsetDecr.indexOf(evt.keyCode) !== -1 || + _this.keysRotationOffsetIncr.indexOf(evt.keyCode) !== -1 || + _this.keysRotationOffsetDecr.indexOf(evt.keyCode) !== -1 || + _this.keysRadiusIncr.indexOf(evt.keyCode) !== -1 || + _this.keysRadiusDecr.indexOf(evt.keyCode) !== -1) { + var index = _this._keys.indexOf(evt.keyCode); + if (index === -1) { + _this._keys.push(evt.keyCode); + } + if (evt.preventDefault) { + if (!noPreventDefault) { + evt.preventDefault(); + } + } + } + } + else { + if (_this.keysHeightOffsetIncr.indexOf(evt.keyCode) !== -1 || + _this.keysHeightOffsetDecr.indexOf(evt.keyCode) !== -1 || + _this.keysRotationOffsetIncr.indexOf(evt.keyCode) !== -1 || + _this.keysRotationOffsetDecr.indexOf(evt.keyCode) !== -1 || + _this.keysRadiusIncr.indexOf(evt.keyCode) !== -1 || + _this.keysRadiusDecr.indexOf(evt.keyCode) !== -1) { + var index = _this._keys.indexOf(evt.keyCode); + if (index >= 0) { + _this._keys.splice(index, 1); + } + if (evt.preventDefault) { + if (!noPreventDefault) { + evt.preventDefault(); + } + } + } + } + } + }); + }; + /** + * Detach the current controls from the specified dom element. + * @param element Defines the element to stop listening the inputs from + */ + FollowCameraKeyboardMoveInput.prototype.detachControl = function (element) { + if (this._scene) { + if (this._onKeyboardObserver) { + this._scene.onKeyboardObservable.remove(this._onKeyboardObserver); + } + if (this._onCanvasBlurObserver) { + this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver); + } + this._onKeyboardObserver = null; + this._onCanvasBlurObserver = null; + } + this._keys = []; + }; + /** + * Update the current camera state depending on the inputs that have been used this frame. + * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. + */ + FollowCameraKeyboardMoveInput.prototype.checkInputs = function () { + var _this = this; + if (this._onKeyboardObserver) { + this._keys.forEach(function (keyCode) { + if (_this.keysHeightOffsetIncr.indexOf(keyCode) !== -1 && + _this._modifierHeightOffset()) { + _this.camera.heightOffset += _this.heightSensibility; + } + else if (_this.keysHeightOffsetDecr.indexOf(keyCode) !== -1 && + _this._modifierHeightOffset()) { + _this.camera.heightOffset -= _this.heightSensibility; + } + else if (_this.keysRotationOffsetIncr.indexOf(keyCode) !== -1 && + _this._modifierRotationOffset()) { + _this.camera.rotationOffset += _this.rotationSensibility; + _this.camera.rotationOffset %= 360; + } + else if (_this.keysRotationOffsetDecr.indexOf(keyCode) !== -1 && + _this._modifierRotationOffset()) { + _this.camera.rotationOffset -= _this.rotationSensibility; + _this.camera.rotationOffset %= 360; + } + else if (_this.keysRadiusIncr.indexOf(keyCode) !== -1 && + _this._modifierRadius()) { + _this.camera.radius += _this.radiusSensibility; + } + else if (_this.keysRadiusDecr.indexOf(keyCode) !== -1 && + _this._modifierRadius()) { + _this.camera.radius -= _this.radiusSensibility; + } + }); + } + }; + /** + * Gets the class name of the current input. + * @returns the class name + */ + FollowCameraKeyboardMoveInput.prototype.getClassName = function () { + return "FollowCameraKeyboardMoveInput"; + }; + /** + * Get the friendly name associated with the input class. + * @returns the input friendly name + */ + FollowCameraKeyboardMoveInput.prototype.getSimpleName = function () { + return "keyboard"; + }; + /** + * Check if the pressed modifier keys (Alt/Ctrl/Shift) match those configured to + * allow modification of the heightOffset value. + */ + FollowCameraKeyboardMoveInput.prototype._modifierHeightOffset = function () { + return (this.keysHeightOffsetModifierAlt === this._altPressed && + this.keysHeightOffsetModifierCtrl === this._ctrlPressed && + this.keysHeightOffsetModifierShift === this._shiftPressed); + }; + /** + * Check if the pressed modifier keys (Alt/Ctrl/Shift) match those configured to + * allow modification of the rotationOffset value. + */ + FollowCameraKeyboardMoveInput.prototype._modifierRotationOffset = function () { + return (this.keysRotationOffsetModifierAlt === this._altPressed && + this.keysRotationOffsetModifierCtrl === this._ctrlPressed && + this.keysRotationOffsetModifierShift === this._shiftPressed); + }; + /** + * Check if the pressed modifier keys (Alt/Ctrl/Shift) match those configured to + * allow modification of the radius value. + */ + FollowCameraKeyboardMoveInput.prototype._modifierRadius = function () { + return (this.keysRadiusModifierAlt === this._altPressed && + this.keysRadiusModifierCtrl === this._ctrlPressed && + this.keysRadiusModifierShift === this._shiftPressed); + }; + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() + ], FollowCameraKeyboardMoveInput.prototype, "keysHeightOffsetIncr", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() + ], FollowCameraKeyboardMoveInput.prototype, "keysHeightOffsetDecr", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() + ], FollowCameraKeyboardMoveInput.prototype, "keysHeightOffsetModifierAlt", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() + ], FollowCameraKeyboardMoveInput.prototype, "keysHeightOffsetModifierCtrl", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() + ], FollowCameraKeyboardMoveInput.prototype, "keysHeightOffsetModifierShift", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() + ], FollowCameraKeyboardMoveInput.prototype, "keysRotationOffsetIncr", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() + ], FollowCameraKeyboardMoveInput.prototype, "keysRotationOffsetDecr", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() + ], FollowCameraKeyboardMoveInput.prototype, "keysRotationOffsetModifierAlt", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() + ], FollowCameraKeyboardMoveInput.prototype, "keysRotationOffsetModifierCtrl", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() + ], FollowCameraKeyboardMoveInput.prototype, "keysRotationOffsetModifierShift", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() + ], FollowCameraKeyboardMoveInput.prototype, "keysRadiusIncr", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() + ], FollowCameraKeyboardMoveInput.prototype, "keysRadiusDecr", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() + ], FollowCameraKeyboardMoveInput.prototype, "keysRadiusModifierAlt", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() + ], FollowCameraKeyboardMoveInput.prototype, "keysRadiusModifierCtrl", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() + ], FollowCameraKeyboardMoveInput.prototype, "keysRadiusModifierShift", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() + ], FollowCameraKeyboardMoveInput.prototype, "heightSensibility", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() + ], FollowCameraKeyboardMoveInput.prototype, "rotationSensibility", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() + ], FollowCameraKeyboardMoveInput.prototype, "radiusSensibility", void 0); + return FollowCameraKeyboardMoveInput; +}()); + +_Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_1__["CameraInputTypes"]["FollowCameraKeyboardMoveInput"] = FollowCameraKeyboardMoveInput; + + +/***/ }), + +/***/ "./Cameras/Inputs/followCameraMouseWheelInput.ts": +/*!*******************************************************!*\ + !*** ./Cameras/Inputs/followCameraMouseWheelInput.ts ***! + \*******************************************************/ +/*! exports provided: FollowCameraMouseWheelInput */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FollowCameraMouseWheelInput", function() { return FollowCameraMouseWheelInput; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); +/* harmony import */ var _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Events/pointerEvents */ "./Events/pointerEvents.ts"); + + + + +/** + * Manage the mouse wheel inputs to control a follow camera. + * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs + */ +var FollowCameraMouseWheelInput = /** @class */ (function () { + function FollowCameraMouseWheelInput() { + /** + * Moue wheel controls zoom. (Mouse wheel modifies camera.radius value.) + */ + this.axisControlRadius = true; + /** + * Moue wheel controls height. (Mouse wheel modifies camera.heightOffset value.) + */ + this.axisControlHeight = false; + /** + * Moue wheel controls angle. (Mouse wheel modifies camera.rotationOffset value.) + */ + this.axisControlRotation = false; + /** + * Gets or Set the mouse wheel precision or how fast is the camera moves in + * relation to mouseWheel events. + */ + this.wheelPrecision = 3.0; + /** + * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0. + * It defines the percentage of current camera.radius to use as delta when wheel is used. + */ + this.wheelDeltaPercentage = 0; + } + /** + * Attach the input controls to a specific dom element to get the input from. + * @param element Defines the element the controls should be listened from + * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) + */ + FollowCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) { + var _this = this; + this._wheel = function (p, s) { + // sanity check - this should be a PointerWheel event. + if (p.type !== _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERWHEEL) { + return; + } + var event = p.event; + var delta = 0; + // Chrome, Safari: event.deltaY + // IE: event.wheelDelta + // Firefox: event.detail (inverted) + var wheelDelta = Math.max(-1, Math.min(1, (event.deltaY || event.wheelDelta || -event.detail))); + if (_this.wheelDeltaPercentage) { + console.assert((_this.axisControlRadius + + _this.axisControlHeight + + _this.axisControlRotation) <= 1, "wheelDeltaPercentage only usable when mouse wheel " + + "controlls ONE axis. " + + "Currently enabled: " + + "axisControlRadius: " + _this.axisControlRadius + + ", axisControlHeightOffset: " + _this.axisControlHeight + + ", axisControlRotationOffset: " + _this.axisControlRotation); + if (_this.axisControlRadius) { + delta = + wheelDelta * 0.01 * _this.wheelDeltaPercentage * + _this.camera.radius; + } + else if (_this.axisControlHeight) { + delta = + wheelDelta * 0.01 * _this.wheelDeltaPercentage * + _this.camera.heightOffset; + } + else if (_this.axisControlRotation) { + delta = + wheelDelta * 0.01 * _this.wheelDeltaPercentage * + _this.camera.rotationOffset; + } + } + else { + delta = wheelDelta * _this.wheelPrecision; + } + if (delta) { + if (_this.axisControlRadius) { + _this.camera.radius += delta; + } + else if (_this.axisControlHeight) { + _this.camera.heightOffset -= delta; + } + else if (_this.axisControlRotation) { + _this.camera.rotationOffset -= delta; + } + } + if (event.preventDefault) { + if (!noPreventDefault) { + event.preventDefault(); + } + } + }; + this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERWHEEL); + }; + /** + * Detach the current controls from the specified dom element. + * @param element Defines the element to stop listening the inputs from + */ + FollowCameraMouseWheelInput.prototype.detachControl = function (element) { + if (this._observer && element) { + this.camera.getScene().onPointerObservable.remove(this._observer); + this._observer = null; + this._wheel = null; + } + }; + /** + * Gets the class name of the current intput. + * @returns the class name + */ + FollowCameraMouseWheelInput.prototype.getClassName = function () { + return "ArcRotateCameraMouseWheelInput"; + }; + /** + * Get the friendly name associated with the input class. + * @returns the input friendly name + */ + FollowCameraMouseWheelInput.prototype.getSimpleName = function () { + return "mousewheel"; + }; + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], FollowCameraMouseWheelInput.prototype, "axisControlRadius", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], FollowCameraMouseWheelInput.prototype, "axisControlHeight", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], FollowCameraMouseWheelInput.prototype, "axisControlRotation", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], FollowCameraMouseWheelInput.prototype, "wheelPrecision", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], FollowCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0); + return FollowCameraMouseWheelInput; +}()); + +_Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__["CameraInputTypes"]["FollowCameraMouseWheelInput"] = FollowCameraMouseWheelInput; + + +/***/ }), + +/***/ "./Cameras/Inputs/followCameraPointersInput.ts": +/*!*****************************************************!*\ + !*** ./Cameras/Inputs/followCameraPointersInput.ts ***! + \*****************************************************/ +/*! exports provided: FollowCameraPointersInput */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FollowCameraPointersInput", function() { return FollowCameraPointersInput; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); +/* harmony import */ var _Cameras_Inputs_BaseCameraPointersInput__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Cameras/Inputs/BaseCameraPointersInput */ "./Cameras/Inputs/BaseCameraPointersInput.ts"); + + + + +/** + * Manage the pointers inputs to control an follow camera. + * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs + */ +var FollowCameraPointersInput = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](FollowCameraPointersInput, _super); + function FollowCameraPointersInput() { + var _this = _super !== null && _super.apply(this, arguments) || this; + /** + * Defines the pointer angular sensibility along the X axis or how fast is + * the camera rotating. + * A negative number will reverse the axis direction. + */ + _this.angularSensibilityX = 1; + /** + * Defines the pointer angular sensibility along the Y axis or how fast is + * the camera rotating. + * A negative number will reverse the axis direction. + */ + _this.angularSensibilityY = 1; + /** + * Defines the pointer pinch precision or how fast is the camera zooming. + * A negative number will reverse the axis direction. + */ + _this.pinchPrecision = 10000.0; + /** + * pinchDeltaPercentage will be used instead of pinchPrecision if different + * from 0. + * It defines the percentage of current camera.radius to use as delta when + * pinch zoom is used. + */ + _this.pinchDeltaPercentage = 0; + /** + * Pointer X axis controls zoom. (X axis modifies camera.radius value.) + */ + _this.axisXControlRadius = false; + /** + * Pointer X axis controls height. (X axis modifies camera.heightOffset value.) + */ + _this.axisXControlHeight = false; + /** + * Pointer X axis controls angle. (X axis modifies camera.rotationOffset value.) + */ + _this.axisXControlRotation = true; + /** + * Pointer Y axis controls zoom. (Y axis modifies camera.radius value.) + */ + _this.axisYControlRadius = false; + /** + * Pointer Y axis controls height. (Y axis modifies camera.heightOffset value.) + */ + _this.axisYControlHeight = true; + /** + * Pointer Y axis controls angle. (Y axis modifies camera.rotationOffset value.) + */ + _this.axisYControlRotation = false; + /** + * Pinch controls zoom. (Pinch modifies camera.radius value.) + */ + _this.axisPinchControlRadius = true; + /** + * Pinch controls height. (Pinch modifies camera.heightOffset value.) + */ + _this.axisPinchControlHeight = false; + /** + * Pinch controls angle. (Pinch modifies camera.rotationOffset value.) + */ + _this.axisPinchControlRotation = false; + /** + * Log error messages if basic misconfiguration has occurred. + */ + _this.warningEnable = true; + /* Check for obvious misconfiguration. */ + _this._warningCounter = 0; + return _this; + } + /** + * Gets the class name of the current input. + * @returns the class name + */ + FollowCameraPointersInput.prototype.getClassName = function () { + return "FollowCameraPointersInput"; + }; + FollowCameraPointersInput.prototype.onTouch = function (pointA, offsetX, offsetY) { + this._warning(); + if (this.axisXControlRotation) { + this.camera.rotationOffset += offsetX / this.angularSensibilityX; + } + else if (this.axisYControlRotation) { + this.camera.rotationOffset += offsetY / this.angularSensibilityX; + } + if (this.axisXControlHeight) { + this.camera.heightOffset += offsetX / this.angularSensibilityY; + } + else if (this.axisYControlHeight) { + this.camera.heightOffset += offsetY / this.angularSensibilityY; + } + if (this.axisXControlRadius) { + this.camera.radius -= offsetX / this.angularSensibilityY; + } + else if (this.axisYControlRadius) { + this.camera.radius -= offsetY / this.angularSensibilityY; + } + }; + FollowCameraPointersInput.prototype.onMultiTouch = function (pointA, pointB, previousPinchSquaredDistance, pinchSquaredDistance, previousMultiTouchPanPosition, multiTouchPanPosition) { + if (previousPinchSquaredDistance === 0 && previousMultiTouchPanPosition === null) { + // First time this method is called for new pinch. + // Next time this is called there will be a + // previousPinchSquaredDistance and pinchSquaredDistance to compare. + return; + } + if (pinchSquaredDistance === 0 && multiTouchPanPosition === null) { + // Last time this method is called at the end of a pinch. + return; + } + var pinchDelta = (pinchSquaredDistance - previousPinchSquaredDistance) / + (this.pinchPrecision * (this.angularSensibilityX + this.angularSensibilityY) / 2); + if (this.pinchDeltaPercentage) { + pinchDelta *= 0.01 * this.pinchDeltaPercentage; + if (this.axisPinchControlRotation) { + this.camera.rotationOffset += pinchDelta * this.camera.rotationOffset; + } + if (this.axisPinchControlHeight) { + this.camera.heightOffset += pinchDelta * this.camera.heightOffset; + } + if (this.axisPinchControlRadius) { + this.camera.radius -= pinchDelta * this.camera.radius; + } + } + else { + if (this.axisPinchControlRotation) { + this.camera.rotationOffset += pinchDelta; + } + if (this.axisPinchControlHeight) { + this.camera.heightOffset += pinchDelta; + } + if (this.axisPinchControlRadius) { + this.camera.radius -= pinchDelta; + } + } + }; + FollowCameraPointersInput.prototype._warning = function () { + if (!this.warningEnable || this._warningCounter++ % 100 !== 0) { + return; + } + var warn = "It probably only makes sense to control ONE camera " + + "property with each pointer axis. Set 'warningEnable = false' " + + "if you are sure. Currently enabled: "; + console.assert((this.axisXControlRotation + + this.axisXControlHeight + + this.axisXControlRadius) <= 1, warn + + "axisXControlRotation: " + this.axisXControlRotation + + ", axisXControlHeight: " + this.axisXControlHeight + + ", axisXControlRadius: " + this.axisXControlRadius); + console.assert((this.axisYControlRotation + + this.axisYControlHeight + + this.axisYControlRadius) <= 1, warn + + "axisYControlRotation: " + this.axisYControlRotation + + ", axisYControlHeight: " + this.axisYControlHeight + + ", axisYControlRadius: " + this.axisYControlRadius); + console.assert((this.axisPinchControlRotation + + this.axisPinchControlHeight + + this.axisPinchControlRadius) <= 1, warn + + "axisPinchControlRotation: " + this.axisPinchControlRotation + + ", axisPinchControlHeight: " + this.axisPinchControlHeight + + ", axisPinchControlRadius: " + this.axisPinchControlRadius); + }; + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], FollowCameraPointersInput.prototype, "angularSensibilityX", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], FollowCameraPointersInput.prototype, "angularSensibilityY", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], FollowCameraPointersInput.prototype, "pinchPrecision", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], FollowCameraPointersInput.prototype, "pinchDeltaPercentage", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], FollowCameraPointersInput.prototype, "axisXControlRadius", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], FollowCameraPointersInput.prototype, "axisXControlHeight", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], FollowCameraPointersInput.prototype, "axisXControlRotation", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], FollowCameraPointersInput.prototype, "axisYControlRadius", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], FollowCameraPointersInput.prototype, "axisYControlHeight", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], FollowCameraPointersInput.prototype, "axisYControlRotation", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], FollowCameraPointersInput.prototype, "axisPinchControlRadius", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], FollowCameraPointersInput.prototype, "axisPinchControlHeight", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], FollowCameraPointersInput.prototype, "axisPinchControlRotation", void 0); + return FollowCameraPointersInput; +}(_Cameras_Inputs_BaseCameraPointersInput__WEBPACK_IMPORTED_MODULE_3__["BaseCameraPointersInput"])); + +_Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__["CameraInputTypes"]["FollowCameraPointersInput"] = FollowCameraPointersInput; + + +/***/ }), + +/***/ "./Cameras/Inputs/freeCameraDeviceOrientationInput.ts": +/*!************************************************************!*\ + !*** ./Cameras/Inputs/freeCameraDeviceOrientationInput.ts ***! + \************************************************************/ +/*! exports provided: FreeCameraDeviceOrientationInput */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FreeCameraDeviceOrientationInput", function() { return FreeCameraDeviceOrientationInput; }); +/* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/tools */ "./Misc/tools.ts"); +/* harmony import */ var _Cameras_freeCameraInputsManager__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Cameras/freeCameraInputsManager */ "./Cameras/freeCameraInputsManager.ts"); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts"); + + + + + +/** + * Add orientation input support to the input manager. + * @returns the current input manager + */ +_Cameras_freeCameraInputsManager__WEBPACK_IMPORTED_MODULE_3__["FreeCameraInputsManager"].prototype.addDeviceOrientation = function () { + if (!this._deviceOrientationInput) { + this._deviceOrientationInput = new FreeCameraDeviceOrientationInput(); + this.add(this._deviceOrientationInput); + } + return this; +}; +/** + * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera. + * Screen rotation is taken into account. + * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs + */ +var FreeCameraDeviceOrientationInput = /** @class */ (function () { + /** + * Instantiates a new input + * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs + */ + function FreeCameraDeviceOrientationInput() { + var _this = this; + this._screenOrientationAngle = 0; + this._screenQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Quaternion"](); + this._alpha = 0; + this._beta = 0; + this._gamma = 0; + /** + * @hidden + */ + this._onDeviceOrientationChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_4__["Observable"](); + this._orientationChanged = function () { + _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && (window.screen.orientation)['angle'] ? (window.screen.orientation).angle : 0)); + _this._screenOrientationAngle = -_Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].ToRadians(_this._screenOrientationAngle / 2); + _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle)); + }; + this._deviceOrientation = function (evt) { + _this._alpha = evt.alpha !== null ? evt.alpha : 0; + _this._beta = evt.beta !== null ? evt.beta : 0; + _this._gamma = evt.gamma !== null ? evt.gamma : 0; + if (evt.alpha !== null) { + _this._onDeviceOrientationChangedObservable.notifyObservers(); + } + }; + this._constantTranform = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Quaternion"](-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5)); + this._orientationChanged(); + } + Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", { + /** + * Define the camera controlled by the input. + */ + get: function () { + return this._camera; + }, + set: function (camera) { + var _this = this; + this._camera = camera; + if (this._camera != null && !this._camera.rotationQuaternion) { + this._camera.rotationQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Quaternion"](); + } + if (this._camera) { + this._camera.onDisposeObservable.add(function () { + _this._onDeviceOrientationChangedObservable.clear(); + }); + } + }, + enumerable: true, + configurable: true + }); + /** + * Attach the input controls to a specific dom element to get the input from. + * @param element Defines the element the controls should be listened from + * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) + */ + FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) { + window.addEventListener("orientationchange", this._orientationChanged); + window.addEventListener("deviceorientation", this._deviceOrientation); + //In certain cases, the attach control is called AFTER orientation was changed, + //So this is needed. + this._orientationChanged(); + }; + /** + * Detach the current controls from the specified dom element. + * @param element Defines the element to stop listening the inputs from + */ + FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) { + window.removeEventListener("orientationchange", this._orientationChanged); + window.removeEventListener("deviceorientation", this._deviceOrientation); + this._alpha = 0; + }; + /** + * Update the current camera state depending on the inputs that have been used this frame. + * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. + */ + FreeCameraDeviceOrientationInput.prototype.checkInputs = function () { + //if no device orientation provided, don't update the rotation. + //Only testing against alpha under the assumption thatnorientation will never be so exact when set. + if (!this._alpha) { + return; + } + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Quaternion"].RotationYawPitchRollToRef(_Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].ToRadians(this._alpha), _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].ToRadians(this._beta), -_Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].ToRadians(this._gamma), this.camera.rotationQuaternion); + this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion); + this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform); + //Mirror on XY Plane + this._camera.rotationQuaternion.z *= -1; + this._camera.rotationQuaternion.w *= -1; + }; + /** + * Gets the class name of the current intput. + * @returns the class name + */ + FreeCameraDeviceOrientationInput.prototype.getClassName = function () { + return "FreeCameraDeviceOrientationInput"; + }; + /** + * Get the friendly name associated with the input class. + * @returns the input friendly name + */ + FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () { + return "deviceOrientation"; + }; + return FreeCameraDeviceOrientationInput; +}()); + +_Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_0__["CameraInputTypes"]["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput; + + +/***/ }), + +/***/ "./Cameras/Inputs/freeCameraGamepadInput.ts": +/*!**************************************************!*\ + !*** ./Cameras/Inputs/freeCameraGamepadInput.ts ***! + \**************************************************/ +/*! exports provided: FreeCameraGamepadInput */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FreeCameraGamepadInput", function() { return FreeCameraGamepadInput; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Gamepads/gamepad */ "./Gamepads/gamepad.ts"); + + + + + +/** + * Manage the gamepad inputs to control a free camera. + * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs + */ +var FreeCameraGamepadInput = /** @class */ (function () { + function FreeCameraGamepadInput() { + /** + * Defines the gamepad rotation sensiblity. + * This is the threshold from when rotation starts to be accounted for to prevent jittering. + */ + this.gamepadAngularSensibility = 200; + /** + * Defines the gamepad move sensiblity. + * This is the threshold from when moving starts to be accounted for for to prevent jittering. + */ + this.gamepadMoveSensibility = 40; + this._cameraTransform = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"].Identity(); + this._deltaTransform = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(); + this._vector3 = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(); + this._vector2 = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector2"].Zero(); + } + /** + * Attach the input controls to a specific dom element to get the input from. + * @param element Defines the element the controls should be listened from + * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) + */ + FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) { + var _this = this; + var manager = this.camera.getScene().gamepadManager; + this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) { + if (gamepad.type !== _Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_4__["Gamepad"].POSE_ENABLED) { + // prioritize XBOX gamepads. + if (!_this.gamepad || gamepad.type === _Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_4__["Gamepad"].XBOX) { + _this.gamepad = gamepad; + } + } + }); + this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) { + if (_this.gamepad === gamepad) { + _this.gamepad = null; + } + }); + this.gamepad = manager.getGamepadByType(_Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_4__["Gamepad"].XBOX); + }; + /** + * Detach the current controls from the specified dom element. + * @param element Defines the element to stop listening the inputs from + */ + FreeCameraGamepadInput.prototype.detachControl = function (element) { + this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver); + this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver); + this.gamepad = null; + }; + /** + * Update the current camera state depending on the inputs that have been used this frame. + * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. + */ + FreeCameraGamepadInput.prototype.checkInputs = function () { + if (this.gamepad && this.gamepad.leftStick) { + var camera = this.camera; + var LSValues = this.gamepad.leftStick; + var normalizedLX = LSValues.x / this.gamepadMoveSensibility; + var normalizedLY = LSValues.y / this.gamepadMoveSensibility; + LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0; + LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0; + var RSValues = this.gamepad.rightStick; + if (RSValues) { + var normalizedRX = RSValues.x / this.gamepadAngularSensibility; + var normalizedRY = RSValues.y / this.gamepadAngularSensibility; + RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0; + RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0; + } + else { + RSValues = { x: 0, y: 0 }; + } + if (!camera.rotationQuaternion) { + _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"].RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform); + } + else { + camera.rotationQuaternion.toRotationMatrix(this._cameraTransform); + } + var speed = camera._computeLocalCameraSpeed() * 50.0; + this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed); + _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform); + camera.cameraDirection.addInPlace(this._deltaTransform); + this._vector2.copyFromFloats(RSValues.y, RSValues.x); + camera.cameraRotation.addInPlace(this._vector2); + } + }; + /** + * Gets the class name of the current intput. + * @returns the class name + */ + FreeCameraGamepadInput.prototype.getClassName = function () { + return "FreeCameraGamepadInput"; + }; + /** + * Get the friendly name associated with the input class. + * @returns the input friendly name + */ + FreeCameraGamepadInput.prototype.getSimpleName = function () { + return "gamepad"; + }; + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0); + return FreeCameraGamepadInput; +}()); + +_Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__["CameraInputTypes"]["FreeCameraGamepadInput"] = FreeCameraGamepadInput; + + +/***/ }), + +/***/ "./Cameras/Inputs/freeCameraKeyboardMoveInput.ts": +/*!*******************************************************!*\ + !*** ./Cameras/Inputs/freeCameraKeyboardMoveInput.ts ***! + \*******************************************************/ +/*! exports provided: FreeCameraKeyboardMoveInput */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FreeCameraKeyboardMoveInput", function() { return FreeCameraKeyboardMoveInput; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); +/* harmony import */ var _Events_keyboardEvents__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Events/keyboardEvents */ "./Events/keyboardEvents.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); + + + + + +/** + * Manage the keyboard inputs to control the movement of a free camera. + * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs + */ +var FreeCameraKeyboardMoveInput = /** @class */ (function () { + function FreeCameraKeyboardMoveInput() { + /** + * Gets or Set the list of keyboard keys used to control the forward move of the camera. + */ + this.keysUp = [38]; + /** + * Gets or Set the list of keyboard keys used to control the backward move of the camera. + */ + this.keysDown = [40]; + /** + * Gets or Set the list of keyboard keys used to control the left strafe move of the camera. + */ + this.keysLeft = [37]; + /** + * Gets or Set the list of keyboard keys used to control the right strafe move of the camera. + */ + this.keysRight = [39]; + this._keys = new Array(); + } + /** + * Attach the input controls to a specific dom element to get the input from. + * @param element Defines the element the controls should be listened from + * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) + */ + FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) { + var _this = this; + if (this._onCanvasBlurObserver) { + return; + } + this._scene = this.camera.getScene(); + this._engine = this._scene.getEngine(); + this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () { + _this._keys = []; + }); + this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) { + var evt = info.event; + if (!evt.metaKey) { + if (info.type === _Events_keyboardEvents__WEBPACK_IMPORTED_MODULE_3__["KeyboardEventTypes"].KEYDOWN) { + if (_this.keysUp.indexOf(evt.keyCode) !== -1 || + _this.keysDown.indexOf(evt.keyCode) !== -1 || + _this.keysLeft.indexOf(evt.keyCode) !== -1 || + _this.keysRight.indexOf(evt.keyCode) !== -1) { + var index = _this._keys.indexOf(evt.keyCode); + if (index === -1) { + _this._keys.push(evt.keyCode); + } + if (!noPreventDefault) { + evt.preventDefault(); + } + } + } + else { + if (_this.keysUp.indexOf(evt.keyCode) !== -1 || + _this.keysDown.indexOf(evt.keyCode) !== -1 || + _this.keysLeft.indexOf(evt.keyCode) !== -1 || + _this.keysRight.indexOf(evt.keyCode) !== -1) { + var index = _this._keys.indexOf(evt.keyCode); + if (index >= 0) { + _this._keys.splice(index, 1); + } + if (!noPreventDefault) { + evt.preventDefault(); + } + } + } + } + }); + }; + /** + * Detach the current controls from the specified dom element. + * @param element Defines the element to stop listening the inputs from + */ + FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) { + if (this._scene) { + if (this._onKeyboardObserver) { + this._scene.onKeyboardObservable.remove(this._onKeyboardObserver); + } + if (this._onCanvasBlurObserver) { + this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver); + } + this._onKeyboardObserver = null; + this._onCanvasBlurObserver = null; + } + this._keys = []; + }; + /** + * Update the current camera state depending on the inputs that have been used this frame. + * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. + */ + FreeCameraKeyboardMoveInput.prototype.checkInputs = function () { + if (this._onKeyboardObserver) { + var camera = this.camera; + // Keyboard + for (var index = 0; index < this._keys.length; index++) { + var keyCode = this._keys[index]; + var speed = camera._computeLocalCameraSpeed(); + if (this.keysLeft.indexOf(keyCode) !== -1) { + camera._localDirection.copyFromFloats(-speed, 0, 0); + } + else if (this.keysUp.indexOf(keyCode) !== -1) { + camera._localDirection.copyFromFloats(0, 0, speed); + } + else if (this.keysRight.indexOf(keyCode) !== -1) { + camera._localDirection.copyFromFloats(speed, 0, 0); + } + else if (this.keysDown.indexOf(keyCode) !== -1) { + camera._localDirection.copyFromFloats(0, 0, -speed); + } + if (camera.getScene().useRightHandedSystem) { + camera._localDirection.z *= -1; + } + camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix); + _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"].TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection); + camera.cameraDirection.addInPlace(camera._transformedDirection); + } + } + }; + /** + * Gets the class name of the current intput. + * @returns the class name + */ + FreeCameraKeyboardMoveInput.prototype.getClassName = function () { + return "FreeCameraKeyboardMoveInput"; + }; + /** @hidden */ + FreeCameraKeyboardMoveInput.prototype._onLostFocus = function () { + this._keys = []; + }; + /** + * Get the friendly name associated with the input class. + * @returns the input friendly name + */ + FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () { + return "keyboard"; + }; + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0); + return FreeCameraKeyboardMoveInput; +}()); + +_Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__["CameraInputTypes"]["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput; + + +/***/ }), + +/***/ "./Cameras/Inputs/freeCameraMouseInput.ts": +/*!************************************************!*\ + !*** ./Cameras/Inputs/freeCameraMouseInput.ts ***! + \************************************************/ +/*! exports provided: FreeCameraMouseInput */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FreeCameraMouseInput", function() { return FreeCameraMouseInput; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); +/* harmony import */ var _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Events/pointerEvents */ "./Events/pointerEvents.ts"); + + + + + +/** + * Manage the mouse inputs to control the movement of a free camera. + * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs + */ +var FreeCameraMouseInput = /** @class */ (function () { + /** + * Manage the mouse inputs to control the movement of a free camera. + * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs + * @param touchEnabled Defines if touch is enabled or not + */ + function FreeCameraMouseInput( + /** + * Define if touch is enabled in the mouse input + */ + touchEnabled) { + if (touchEnabled === void 0) { touchEnabled = true; } + this.touchEnabled = touchEnabled; + /** + * Defines the buttons associated with the input to handle camera move. + */ + this.buttons = [0, 1, 2]; + /** + * Defines the pointer angular sensibility along the X and Y axis or how fast is the camera rotating. + */ + this.angularSensibility = 2000.0; + this.previousPosition = null; + /** + * Observable for when a pointer move event occurs containing the move offset + */ + this.onPointerMovedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + /** + * @hidden + * If the camera should be rotated automatically based on pointer movement + */ + this._allowCameraRotation = true; + } + /** + * Attach the input controls to a specific dom element to get the input from. + * @param element Defines the element the controls should be listened from + * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) + */ + FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) { + var _this = this; + var engine = this.camera.getEngine(); + if (!this._pointerInput) { + this._pointerInput = function (p) { + var evt = p.event; + if (engine.isInVRExclusivePointerMode) { + return; + } + if (!_this.touchEnabled && evt.pointerType === "touch") { + return; + } + if (p.type !== _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_4__["PointerEventTypes"].POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) { + return; + } + var srcElement = (evt.srcElement || evt.target); + if (p.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_4__["PointerEventTypes"].POINTERDOWN && srcElement) { + try { + srcElement.setPointerCapture(evt.pointerId); + } + catch (e) { + //Nothing to do with the error. Execution will continue. + } + _this.previousPosition = { + x: evt.clientX, + y: evt.clientY + }; + if (!noPreventDefault) { + evt.preventDefault(); + element.focus(); + } + } + else if (p.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_4__["PointerEventTypes"].POINTERUP && srcElement) { + try { + srcElement.releasePointerCapture(evt.pointerId); + } + catch (e) { + //Nothing to do with the error. + } + _this.previousPosition = null; + if (!noPreventDefault) { + evt.preventDefault(); + } + } + else if (p.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_4__["PointerEventTypes"].POINTERMOVE) { + if (!_this.previousPosition || engine.isPointerLock) { + return; + } + var offsetX = evt.clientX - _this.previousPosition.x; + var offsetY = evt.clientY - _this.previousPosition.y; + if (_this.camera.getScene().useRightHandedSystem) { + offsetX *= -1; + } + if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0) { + offsetX *= -1; + } + if (_this._allowCameraRotation) { + _this.camera.cameraRotation.y += offsetX / _this.angularSensibility; + _this.camera.cameraRotation.x += offsetY / _this.angularSensibility; + } + _this.onPointerMovedObservable.notifyObservers({ offsetX: offsetX, offsetY: offsetY }); + _this.previousPosition = { + x: evt.clientX, + y: evt.clientY + }; + if (!noPreventDefault) { + evt.preventDefault(); + } + } + }; + } + this._onMouseMove = function (evt) { + if (!engine.isPointerLock) { + return; + } + if (engine.isInVRExclusivePointerMode) { + return; + } + var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0; + if (_this.camera.getScene().useRightHandedSystem) { + offsetX *= -1; + } + if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0) { + offsetX *= -1; + } + _this.camera.cameraRotation.y += offsetX / _this.angularSensibility; + var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0; + _this.camera.cameraRotation.x += offsetY / _this.angularSensibility; + _this.previousPosition = null; + if (!noPreventDefault) { + evt.preventDefault(); + } + }; + this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_4__["PointerEventTypes"].POINTERDOWN | _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_4__["PointerEventTypes"].POINTERUP | _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_4__["PointerEventTypes"].POINTERMOVE); + element.addEventListener("mousemove", this._onMouseMove, false); + element.addEventListener("contextmenu", this.onContextMenu.bind(this), false); + }; + /** + * Called on JS contextmenu event. + * Override this method to provide functionality. + */ + FreeCameraMouseInput.prototype.onContextMenu = function (evt) { + evt.preventDefault(); + }; + /** + * Detach the current controls from the specified dom element. + * @param element Defines the element to stop listening the inputs from + */ + FreeCameraMouseInput.prototype.detachControl = function (element) { + if (this._observer && element) { + this.camera.getScene().onPointerObservable.remove(this._observer); + if (this._onMouseMove) { + element.removeEventListener("mousemove", this._onMouseMove); + } + if (this.onContextMenu) { + element.removeEventListener("contextmenu", this.onContextMenu); + } + if (this.onPointerMovedObservable) { + this.onPointerMovedObservable.clear(); + } + this._observer = null; + this._onMouseMove = null; + this.previousPosition = null; + } + }; + /** + * Gets the class name of the current intput. + * @returns the class name + */ + FreeCameraMouseInput.prototype.getClassName = function () { + return "FreeCameraMouseInput"; + }; + /** + * Get the friendly name associated with the input class. + * @returns the input friendly name + */ + FreeCameraMouseInput.prototype.getSimpleName = function () { + return "mouse"; + }; + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() + ], FreeCameraMouseInput.prototype, "buttons", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() + ], FreeCameraMouseInput.prototype, "angularSensibility", void 0); + return FreeCameraMouseInput; +}()); + +_Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_3__["CameraInputTypes"]["FreeCameraMouseInput"] = FreeCameraMouseInput; + + +/***/ }), + +/***/ "./Cameras/Inputs/freeCameraTouchInput.ts": +/*!************************************************!*\ + !*** ./Cameras/Inputs/freeCameraTouchInput.ts ***! + \************************************************/ +/*! exports provided: FreeCameraTouchInput */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FreeCameraTouchInput", function() { return FreeCameraTouchInput; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); +/* harmony import */ var _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Events/pointerEvents */ "./Events/pointerEvents.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); + + + + + +/** + * Manage the touch inputs to control the movement of a free camera. + * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs + */ +var FreeCameraTouchInput = /** @class */ (function () { + function FreeCameraTouchInput() { + /** + * Defines the touch sensibility for rotation. + * The higher the faster. + */ + this.touchAngularSensibility = 200000.0; + /** + * Defines the touch sensibility for move. + * The higher the faster. + */ + this.touchMoveSensibility = 250.0; + this._offsetX = null; + this._offsetY = null; + this._pointerPressed = new Array(); + } + /** + * Attach the input controls to a specific dom element to get the input from. + * @param element Defines the element the controls should be listened from + * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) + */ + FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) { + var _this = this; + var previousPosition = null; + if (this._pointerInput === undefined) { + this._onLostFocus = function () { + _this._offsetX = null; + _this._offsetY = null; + }; + this._pointerInput = function (p) { + var evt = p.event; + if (evt.pointerType === "mouse") { + return; + } + if (p.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERDOWN) { + if (!noPreventDefault) { + evt.preventDefault(); + } + _this._pointerPressed.push(evt.pointerId); + if (_this._pointerPressed.length !== 1) { + return; + } + previousPosition = { + x: evt.clientX, + y: evt.clientY + }; + } + else if (p.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERUP) { + if (!noPreventDefault) { + evt.preventDefault(); + } + var index = _this._pointerPressed.indexOf(evt.pointerId); + if (index === -1) { + return; + } + _this._pointerPressed.splice(index, 1); + if (index != 0) { + return; + } + previousPosition = null; + _this._offsetX = null; + _this._offsetY = null; + } + else if (p.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERMOVE) { + if (!noPreventDefault) { + evt.preventDefault(); + } + if (!previousPosition) { + return; + } + var index = _this._pointerPressed.indexOf(evt.pointerId); + if (index != 0) { + return; + } + _this._offsetX = evt.clientX - previousPosition.x; + _this._offsetY = -(evt.clientY - previousPosition.y); + } + }; + } + this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERDOWN | _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERUP | _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERMOVE); + if (this._onLostFocus) { + element.addEventListener("blur", this._onLostFocus); + } + }; + /** + * Detach the current controls from the specified dom element. + * @param element Defines the element to stop listening the inputs from + */ + FreeCameraTouchInput.prototype.detachControl = function (element) { + if (this._pointerInput && element) { + if (this._observer) { + this.camera.getScene().onPointerObservable.remove(this._observer); + this._observer = null; + } + if (this._onLostFocus) { + element.removeEventListener("blur", this._onLostFocus); + this._onLostFocus = null; + } + this._pointerPressed = []; + this._offsetX = null; + this._offsetY = null; + } + }; + /** + * Update the current camera state depending on the inputs that have been used this frame. + * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. + */ + FreeCameraTouchInput.prototype.checkInputs = function () { + if (this._offsetX && this._offsetY) { + var camera = this.camera; + camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility; + if (this._pointerPressed.length > 1) { + camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility; + } + else { + var speed = camera._computeLocalCameraSpeed(); + var direction = new _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"](0, 0, speed * this._offsetY / this.touchMoveSensibility); + _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"].RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix); + camera.cameraDirection.addInPlace(_Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"].TransformCoordinates(direction, camera._cameraRotationMatrix)); + } + } + }; + /** + * Gets the class name of the current intput. + * @returns the class name + */ + FreeCameraTouchInput.prototype.getClassName = function () { + return "FreeCameraTouchInput"; + }; + /** + * Get the friendly name associated with the input class. + * @returns the input friendly name + */ + FreeCameraTouchInput.prototype.getSimpleName = function () { + return "touch"; + }; + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0); + return FreeCameraTouchInput; +}()); + +_Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__["CameraInputTypes"]["FreeCameraTouchInput"] = FreeCameraTouchInput; + + +/***/ }), + +/***/ "./Cameras/Inputs/freeCameraVirtualJoystickInput.ts": +/*!**********************************************************!*\ + !*** ./Cameras/Inputs/freeCameraVirtualJoystickInput.ts ***! + \**********************************************************/ +/*! exports provided: FreeCameraVirtualJoystickInput */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FreeCameraVirtualJoystickInput", function() { return FreeCameraVirtualJoystickInput; }); +/* harmony import */ var _Misc_virtualJoystick__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Misc/virtualJoystick */ "./Misc/virtualJoystick.ts"); +/* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Cameras_freeCameraInputsManager__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Cameras/freeCameraInputsManager */ "./Cameras/freeCameraInputsManager.ts"); + + + + +/** +* Add virtual joystick input support to the input manager. +* @returns the current input manager +*/ +_Cameras_freeCameraInputsManager__WEBPACK_IMPORTED_MODULE_3__["FreeCameraInputsManager"].prototype.addVirtualJoystick = function () { + this.add(new FreeCameraVirtualJoystickInput()); + return this; +}; +/** + * Manage the Virtual Joystick inputs to control the movement of a free camera. + * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs + */ +var FreeCameraVirtualJoystickInput = /** @class */ (function () { + function FreeCameraVirtualJoystickInput() { + } + /** + * Gets the left stick of the virtual joystick. + * @returns The virtual Joystick + */ + FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () { + return this._leftjoystick; + }; + /** + * Gets the right stick of the virtual joystick. + * @returns The virtual Joystick + */ + FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () { + return this._rightjoystick; + }; + /** + * Update the current camera state depending on the inputs that have been used this frame. + * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. + */ + FreeCameraVirtualJoystickInput.prototype.checkInputs = function () { + if (this._leftjoystick) { + var camera = this.camera; + var speed = camera._computeLocalCameraSpeed() * 50; + var cameraTransform = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"].RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0); + var deltaTransform = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].TransformCoordinates(new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform); + camera.cameraDirection = camera.cameraDirection.add(deltaTransform); + camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition); + if (!this._leftjoystick.pressed) { + this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9); + } + if (!this._rightjoystick.pressed) { + this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9); + } + } + }; + /** + * Attach the input controls to a specific dom element to get the input from. + * @param element Defines the element the controls should be listened from + * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) + */ + FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) { + this._leftjoystick = new _Misc_virtualJoystick__WEBPACK_IMPORTED_MODULE_0__["VirtualJoystick"](true); + this._leftjoystick.setAxisForUpDown(_Misc_virtualJoystick__WEBPACK_IMPORTED_MODULE_0__["JoystickAxis"].Z); + this._leftjoystick.setAxisForLeftRight(_Misc_virtualJoystick__WEBPACK_IMPORTED_MODULE_0__["JoystickAxis"].X); + this._leftjoystick.setJoystickSensibility(0.15); + this._rightjoystick = new _Misc_virtualJoystick__WEBPACK_IMPORTED_MODULE_0__["VirtualJoystick"](false); + this._rightjoystick.setAxisForUpDown(_Misc_virtualJoystick__WEBPACK_IMPORTED_MODULE_0__["JoystickAxis"].X); + this._rightjoystick.setAxisForLeftRight(_Misc_virtualJoystick__WEBPACK_IMPORTED_MODULE_0__["JoystickAxis"].Y); + this._rightjoystick.reverseUpDown = true; + this._rightjoystick.setJoystickSensibility(0.05); + this._rightjoystick.setJoystickColor("yellow"); + }; + /** + * Detach the current controls from the specified dom element. + * @param element Defines the element to stop listening the inputs from + */ + FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) { + this._leftjoystick.releaseCanvas(); + this._rightjoystick.releaseCanvas(); + }; + /** + * Gets the class name of the current intput. + * @returns the class name + */ + FreeCameraVirtualJoystickInput.prototype.getClassName = function () { + return "FreeCameraVirtualJoystickInput"; + }; + /** + * Get the friendly name associated with the input class. + * @returns the input friendly name + */ + FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () { + return "virtualJoystick"; + }; + return FreeCameraVirtualJoystickInput; +}()); + +_Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_1__["CameraInputTypes"]["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput; + + +/***/ }), + +/***/ "./Cameras/Inputs/index.ts": +/*!*********************************!*\ + !*** ./Cameras/Inputs/index.ts ***! + \*********************************/ +/*! exports provided: ArcRotateCameraGamepadInput, ArcRotateCameraKeyboardMoveInput, ArcRotateCameraMouseWheelInput, ArcRotateCameraPointersInput, ArcRotateCameraVRDeviceOrientationInput, FlyCameraKeyboardInput, FlyCameraMouseInput, FollowCameraKeyboardMoveInput, FollowCameraMouseWheelInput, FollowCameraPointersInput, FreeCameraDeviceOrientationInput, FreeCameraGamepadInput, FreeCameraKeyboardMoveInput, FreeCameraMouseInput, FreeCameraTouchInput, FreeCameraVirtualJoystickInput */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _arcRotateCameraGamepadInput__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./arcRotateCameraGamepadInput */ "./Cameras/Inputs/arcRotateCameraGamepadInput.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraGamepadInput", function() { return _arcRotateCameraGamepadInput__WEBPACK_IMPORTED_MODULE_0__["ArcRotateCameraGamepadInput"]; }); + +/* harmony import */ var _arcRotateCameraKeyboardMoveInput__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./arcRotateCameraKeyboardMoveInput */ "./Cameras/Inputs/arcRotateCameraKeyboardMoveInput.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraKeyboardMoveInput", function() { return _arcRotateCameraKeyboardMoveInput__WEBPACK_IMPORTED_MODULE_1__["ArcRotateCameraKeyboardMoveInput"]; }); + +/* harmony import */ var _arcRotateCameraMouseWheelInput__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./arcRotateCameraMouseWheelInput */ "./Cameras/Inputs/arcRotateCameraMouseWheelInput.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraMouseWheelInput", function() { return _arcRotateCameraMouseWheelInput__WEBPACK_IMPORTED_MODULE_2__["ArcRotateCameraMouseWheelInput"]; }); + +/* harmony import */ var _arcRotateCameraPointersInput__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./arcRotateCameraPointersInput */ "./Cameras/Inputs/arcRotateCameraPointersInput.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraPointersInput", function() { return _arcRotateCameraPointersInput__WEBPACK_IMPORTED_MODULE_3__["ArcRotateCameraPointersInput"]; }); + +/* harmony import */ var _arcRotateCameraVRDeviceOrientationInput__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./arcRotateCameraVRDeviceOrientationInput */ "./Cameras/Inputs/arcRotateCameraVRDeviceOrientationInput.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraVRDeviceOrientationInput", function() { return _arcRotateCameraVRDeviceOrientationInput__WEBPACK_IMPORTED_MODULE_4__["ArcRotateCameraVRDeviceOrientationInput"]; }); + +/* harmony import */ var _flyCameraKeyboardInput__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./flyCameraKeyboardInput */ "./Cameras/Inputs/flyCameraKeyboardInput.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FlyCameraKeyboardInput", function() { return _flyCameraKeyboardInput__WEBPACK_IMPORTED_MODULE_5__["FlyCameraKeyboardInput"]; }); + +/* harmony import */ var _flyCameraMouseInput__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./flyCameraMouseInput */ "./Cameras/Inputs/flyCameraMouseInput.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FlyCameraMouseInput", function() { return _flyCameraMouseInput__WEBPACK_IMPORTED_MODULE_6__["FlyCameraMouseInput"]; }); + +/* harmony import */ var _followCameraKeyboardMoveInput__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./followCameraKeyboardMoveInput */ "./Cameras/Inputs/followCameraKeyboardMoveInput.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FollowCameraKeyboardMoveInput", function() { return _followCameraKeyboardMoveInput__WEBPACK_IMPORTED_MODULE_7__["FollowCameraKeyboardMoveInput"]; }); + +/* harmony import */ var _followCameraMouseWheelInput__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./followCameraMouseWheelInput */ "./Cameras/Inputs/followCameraMouseWheelInput.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FollowCameraMouseWheelInput", function() { return _followCameraMouseWheelInput__WEBPACK_IMPORTED_MODULE_8__["FollowCameraMouseWheelInput"]; }); + +/* harmony import */ var _followCameraPointersInput__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./followCameraPointersInput */ "./Cameras/Inputs/followCameraPointersInput.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FollowCameraPointersInput", function() { return _followCameraPointersInput__WEBPACK_IMPORTED_MODULE_9__["FollowCameraPointersInput"]; }); + +/* harmony import */ var _freeCameraDeviceOrientationInput__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./freeCameraDeviceOrientationInput */ "./Cameras/Inputs/freeCameraDeviceOrientationInput.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraDeviceOrientationInput", function() { return _freeCameraDeviceOrientationInput__WEBPACK_IMPORTED_MODULE_10__["FreeCameraDeviceOrientationInput"]; }); + +/* harmony import */ var _freeCameraGamepadInput__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./freeCameraGamepadInput */ "./Cameras/Inputs/freeCameraGamepadInput.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraGamepadInput", function() { return _freeCameraGamepadInput__WEBPACK_IMPORTED_MODULE_11__["FreeCameraGamepadInput"]; }); + +/* harmony import */ var _freeCameraKeyboardMoveInput__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./freeCameraKeyboardMoveInput */ "./Cameras/Inputs/freeCameraKeyboardMoveInput.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraKeyboardMoveInput", function() { return _freeCameraKeyboardMoveInput__WEBPACK_IMPORTED_MODULE_12__["FreeCameraKeyboardMoveInput"]; }); + +/* harmony import */ var _freeCameraMouseInput__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./freeCameraMouseInput */ "./Cameras/Inputs/freeCameraMouseInput.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraMouseInput", function() { return _freeCameraMouseInput__WEBPACK_IMPORTED_MODULE_13__["FreeCameraMouseInput"]; }); + +/* harmony import */ var _freeCameraTouchInput__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./freeCameraTouchInput */ "./Cameras/Inputs/freeCameraTouchInput.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraTouchInput", function() { return _freeCameraTouchInput__WEBPACK_IMPORTED_MODULE_14__["FreeCameraTouchInput"]; }); + +/* harmony import */ var _freeCameraVirtualJoystickInput__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./freeCameraVirtualJoystickInput */ "./Cameras/Inputs/freeCameraVirtualJoystickInput.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraVirtualJoystickInput", function() { return _freeCameraVirtualJoystickInput__WEBPACK_IMPORTED_MODULE_15__["FreeCameraVirtualJoystickInput"]; }); + + + + + + + + + + + + + + + + + + + +/***/ }), + +/***/ "./Cameras/RigModes/stereoscopicAnaglyphRigMode.ts": +/*!*********************************************************!*\ + !*** ./Cameras/RigModes/stereoscopicAnaglyphRigMode.ts ***! + \*********************************************************/ +/*! no exports provided */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _camera__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../camera */ "./Cameras/camera.ts"); +/* harmony import */ var _PostProcesses_passPostProcess__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../PostProcesses/passPostProcess */ "./PostProcesses/passPostProcess.ts"); +/* harmony import */ var _PostProcesses_anaglyphPostProcess__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../PostProcesses/anaglyphPostProcess */ "./PostProcesses/anaglyphPostProcess.ts"); + + + +_camera__WEBPACK_IMPORTED_MODULE_0__["Camera"]._setStereoscopicAnaglyphRigMode = function (camera) { + camera._rigCameras[0]._rigPostProcess = new _PostProcesses_passPostProcess__WEBPACK_IMPORTED_MODULE_1__["PassPostProcess"](camera.name + "_passthru", 1.0, camera._rigCameras[0]); + camera._rigCameras[1]._rigPostProcess = new _PostProcesses_anaglyphPostProcess__WEBPACK_IMPORTED_MODULE_2__["AnaglyphPostProcess"](camera.name + "_anaglyph", 1.0, camera._rigCameras); +}; + + +/***/ }), + +/***/ "./Cameras/RigModes/stereoscopicRigMode.ts": +/*!*************************************************!*\ + !*** ./Cameras/RigModes/stereoscopicRigMode.ts ***! + \*************************************************/ +/*! no exports provided */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _camera__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../camera */ "./Cameras/camera.ts"); +/* harmony import */ var _PostProcesses_passPostProcess__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../PostProcesses/passPostProcess */ "./PostProcesses/passPostProcess.ts"); +/* harmony import */ var _PostProcesses_stereoscopicInterlacePostProcess__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../PostProcesses/stereoscopicInterlacePostProcess */ "./PostProcesses/stereoscopicInterlacePostProcess.ts"); + + + +_camera__WEBPACK_IMPORTED_MODULE_0__["Camera"]._setStereoscopicRigMode = function (camera) { + var isStereoscopicHoriz = camera.cameraRigMode === _camera__WEBPACK_IMPORTED_MODULE_0__["Camera"].RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || camera.cameraRigMode === _camera__WEBPACK_IMPORTED_MODULE_0__["Camera"].RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED; + camera._rigCameras[0]._rigPostProcess = new _PostProcesses_passPostProcess__WEBPACK_IMPORTED_MODULE_1__["PassPostProcess"](camera.name + "_passthru", 1.0, camera._rigCameras[0]); + camera._rigCameras[1]._rigPostProcess = new _PostProcesses_stereoscopicInterlacePostProcess__WEBPACK_IMPORTED_MODULE_2__["StereoscopicInterlacePostProcess"](camera.name + "_stereoInterlace", camera._rigCameras, isStereoscopicHoriz); +}; + + +/***/ }), + +/***/ "./Cameras/RigModes/vrRigMode.ts": +/*!***************************************!*\ + !*** ./Cameras/RigModes/vrRigMode.ts ***! + \***************************************/ +/*! no exports provided */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _camera__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../camera */ "./Cameras/camera.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _PostProcesses_vrDistortionCorrectionPostProcess__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../PostProcesses/vrDistortionCorrectionPostProcess */ "./PostProcesses/vrDistortionCorrectionPostProcess.ts"); +/* harmony import */ var _PostProcesses_vrMultiviewToSingleviewPostProcess__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../PostProcesses/vrMultiviewToSingleviewPostProcess */ "./PostProcesses/vrMultiviewToSingleviewPostProcess.ts"); +/* harmony import */ var _VR_vrCameraMetrics__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../VR/vrCameraMetrics */ "./Cameras/VR/vrCameraMetrics.ts"); +/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Misc/logger */ "./Misc/logger.ts"); + + + + + + +_camera__WEBPACK_IMPORTED_MODULE_0__["Camera"]._setVRRigMode = function (camera, rigParams) { + var metrics = rigParams.vrCameraMetrics || _VR_vrCameraMetrics__WEBPACK_IMPORTED_MODULE_4__["VRCameraMetrics"].GetDefault(); + camera._rigCameras[0]._cameraRigParams.vrMetrics = metrics; + camera._rigCameras[0].viewport = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Viewport"](0, 0, 0.5, 1.0); + camera._rigCameras[0]._cameraRigParams.vrWorkMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"](); + camera._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix; + camera._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix; + camera._rigCameras[0].getProjectionMatrix = camera._rigCameras[0]._getVRProjectionMatrix; + camera._rigCameras[1]._cameraRigParams.vrMetrics = metrics; + camera._rigCameras[1].viewport = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Viewport"](0.5, 0, 0.5, 1.0); + camera._rigCameras[1]._cameraRigParams.vrWorkMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"](); + camera._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix; + camera._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix; + camera._rigCameras[1].getProjectionMatrix = camera._rigCameras[1]._getVRProjectionMatrix; + // For multiview on a webVR camera + // First multiview will be rendered to camera._multiviewTexture + // Then this postprocess will run on each eye to copy the right texture to each eye + if (metrics.multiviewEnabled) { + if (!camera.getScene().getEngine().getCaps().multiview) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_5__["Logger"].Warn("Multiview is not supported, falling back to standard rendering"); + metrics.multiviewEnabled = false; + } + else { + camera._useMultiviewToSingleView = true; + camera._rigPostProcess = new _PostProcesses_vrMultiviewToSingleviewPostProcess__WEBPACK_IMPORTED_MODULE_3__["VRMultiviewToSingleviewPostProcess"]("VRMultiviewToSingleview", camera, metrics.postProcessScaleFactor); + } + } + if (metrics.compensateDistortion) { + camera._rigCameras[0]._rigPostProcess = new _PostProcesses_vrDistortionCorrectionPostProcess__WEBPACK_IMPORTED_MODULE_2__["VRDistortionCorrectionPostProcess"]("VR_Distort_Compensation_Left", camera._rigCameras[0], false, metrics); + camera._rigCameras[1]._rigPostProcess = new _PostProcesses_vrDistortionCorrectionPostProcess__WEBPACK_IMPORTED_MODULE_2__["VRDistortionCorrectionPostProcess"]("VR_Distort_Compensation_Right", camera._rigCameras[1], true, metrics); + } +}; + + +/***/ }), + +/***/ "./Cameras/RigModes/webVRRigMode.ts": +/*!******************************************!*\ + !*** ./Cameras/RigModes/webVRRigMode.ts ***! + \******************************************/ +/*! no exports provided */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _camera__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../camera */ "./Cameras/camera.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); + + +_camera__WEBPACK_IMPORTED_MODULE_0__["Camera"]._setWebVRRigMode = function (camera, rigParams) { + if (rigParams.vrDisplay) { + var leftEye = rigParams.vrDisplay.getEyeParameters('left'); + var rightEye = rigParams.vrDisplay.getEyeParameters('right'); + //Left eye + camera._rigCameras[0].viewport = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Viewport"](0, 0, 0.5, 1.0); + camera._rigCameras[0].setCameraRigParameter("left", true); + //leaving this for future reference + camera._rigCameras[0].setCameraRigParameter("specs", rigParams.specs); + camera._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye); + camera._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData); + camera._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera); + camera._rigCameras[0]._cameraRigParams.vrWorkMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"](); + camera._rigCameras[0].getProjectionMatrix = camera._getWebVRProjectionMatrix; + camera._rigCameras[0].parent = camera; + camera._rigCameras[0]._getViewMatrix = camera._getWebVRViewMatrix; + //Right eye + camera._rigCameras[1].viewport = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Viewport"](0.5, 0, 0.5, 1.0); + camera._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye); + camera._rigCameras[1].setCameraRigParameter("specs", rigParams.specs); + camera._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData); + camera._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera); + camera._rigCameras[1]._cameraRigParams.vrWorkMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"](); + camera._rigCameras[1].getProjectionMatrix = camera._getWebVRProjectionMatrix; + camera._rigCameras[1].parent = camera; + camera._rigCameras[1]._getViewMatrix = camera._getWebVRViewMatrix; + } +}; + + +/***/ }), + +/***/ "./Cameras/Stereoscopic/anaglyphArcRotateCamera.ts": +/*!*********************************************************!*\ + !*** ./Cameras/Stereoscopic/anaglyphArcRotateCamera.ts ***! + \*********************************************************/ +/*! exports provided: AnaglyphArcRotateCamera */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnaglyphArcRotateCamera", function() { return AnaglyphArcRotateCamera; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Cameras/camera */ "./Cameras/camera.ts"); +/* harmony import */ var _Cameras_arcRotateCamera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/arcRotateCamera */ "./Cameras/arcRotateCamera.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../node */ "./node.ts"); +/* harmony import */ var _RigModes_stereoscopicAnaglyphRigMode__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../RigModes/stereoscopicAnaglyphRigMode */ "./Cameras/RigModes/stereoscopicAnaglyphRigMode.ts"); + + + + + +// Side effect import to define the stereoscopic mode. + +_node__WEBPACK_IMPORTED_MODULE_4__["Node"].AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) { + return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(), options.interaxial_distance, scene); }; +}); +/** + * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera) + * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras + */ +var AnaglyphArcRotateCamera = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](AnaglyphArcRotateCamera, _super); + /** + * Creates a new AnaglyphArcRotateCamera + * @param name defines camera name + * @param alpha defines alpha angle (in radians) + * @param beta defines beta angle (in radians) + * @param radius defines radius + * @param target defines camera target + * @param interaxialDistance defines distance between each color axis + * @param scene defines the hosting scene + */ + function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) { + var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this; + _this.interaxialDistance = interaxialDistance; + _this.setCameraRigMode(_Cameras_camera__WEBPACK_IMPORTED_MODULE_1__["Camera"].RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance }); + return _this; + } + /** + * Gets camera class name + * @returns AnaglyphArcRotateCamera + */ + AnaglyphArcRotateCamera.prototype.getClassName = function () { + return "AnaglyphArcRotateCamera"; + }; + return AnaglyphArcRotateCamera; +}(_Cameras_arcRotateCamera__WEBPACK_IMPORTED_MODULE_2__["ArcRotateCamera"])); + + + +/***/ }), + +/***/ "./Cameras/Stereoscopic/anaglyphFreeCamera.ts": +/*!****************************************************!*\ + !*** ./Cameras/Stereoscopic/anaglyphFreeCamera.ts ***! + \****************************************************/ +/*! exports provided: AnaglyphFreeCamera */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnaglyphFreeCamera", function() { return AnaglyphFreeCamera; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Cameras/camera */ "./Cameras/camera.ts"); +/* harmony import */ var _Cameras_freeCamera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/freeCamera */ "./Cameras/freeCamera.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../node */ "./node.ts"); +/* harmony import */ var _RigModes_stereoscopicAnaglyphRigMode__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../RigModes/stereoscopicAnaglyphRigMode */ "./Cameras/RigModes/stereoscopicAnaglyphRigMode.ts"); + + + + + +// Side effect import to define the stereoscopic mode. + +_node__WEBPACK_IMPORTED_MODULE_4__["Node"].AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) { + return function () { return new AnaglyphFreeCamera(name, _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(), options.interaxial_distance, scene); }; +}); +/** + * Camera used to simulate anaglyphic rendering (based on FreeCamera) + * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras + */ +var AnaglyphFreeCamera = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](AnaglyphFreeCamera, _super); + /** + * Creates a new AnaglyphFreeCamera + * @param name defines camera name + * @param position defines initial position + * @param interaxialDistance defines distance between each color axis + * @param scene defines the hosting scene + */ + function AnaglyphFreeCamera(name, position, interaxialDistance, scene) { + var _this = _super.call(this, name, position, scene) || this; + _this.interaxialDistance = interaxialDistance; + _this.setCameraRigMode(_Cameras_camera__WEBPACK_IMPORTED_MODULE_1__["Camera"].RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance }); + return _this; + } + /** + * Gets camera class name + * @returns AnaglyphFreeCamera + */ + AnaglyphFreeCamera.prototype.getClassName = function () { + return "AnaglyphFreeCamera"; + }; + return AnaglyphFreeCamera; +}(_Cameras_freeCamera__WEBPACK_IMPORTED_MODULE_2__["FreeCamera"])); + + + +/***/ }), + +/***/ "./Cameras/Stereoscopic/anaglyphGamepadCamera.ts": +/*!*******************************************************!*\ + !*** ./Cameras/Stereoscopic/anaglyphGamepadCamera.ts ***! + \*******************************************************/ +/*! exports provided: AnaglyphGamepadCamera */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnaglyphGamepadCamera", function() { return AnaglyphGamepadCamera; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Cameras/camera */ "./Cameras/camera.ts"); +/* harmony import */ var _Cameras_gamepadCamera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/gamepadCamera */ "./Cameras/gamepadCamera.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../node */ "./node.ts"); +/* harmony import */ var _RigModes_stereoscopicAnaglyphRigMode__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../RigModes/stereoscopicAnaglyphRigMode */ "./Cameras/RigModes/stereoscopicAnaglyphRigMode.ts"); + + + + + +// Side effect import to define the stereoscopic mode. + +_node__WEBPACK_IMPORTED_MODULE_4__["Node"].AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) { + return function () { return new AnaglyphGamepadCamera(name, _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(), options.interaxial_distance, scene); }; +}); +/** + * Camera used to simulate anaglyphic rendering (based on GamepadCamera) + * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras + */ +var AnaglyphGamepadCamera = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](AnaglyphGamepadCamera, _super); + /** + * Creates a new AnaglyphGamepadCamera + * @param name defines camera name + * @param position defines initial position + * @param interaxialDistance defines distance between each color axis + * @param scene defines the hosting scene + */ + function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) { + var _this = _super.call(this, name, position, scene) || this; + _this.interaxialDistance = interaxialDistance; + _this.setCameraRigMode(_Cameras_camera__WEBPACK_IMPORTED_MODULE_1__["Camera"].RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance }); + return _this; + } + /** + * Gets camera class name + * @returns AnaglyphGamepadCamera + */ + AnaglyphGamepadCamera.prototype.getClassName = function () { + return "AnaglyphGamepadCamera"; + }; + return AnaglyphGamepadCamera; +}(_Cameras_gamepadCamera__WEBPACK_IMPORTED_MODULE_2__["GamepadCamera"])); + + + +/***/ }), + +/***/ "./Cameras/Stereoscopic/anaglyphUniversalCamera.ts": +/*!*********************************************************!*\ + !*** ./Cameras/Stereoscopic/anaglyphUniversalCamera.ts ***! + \*********************************************************/ +/*! exports provided: AnaglyphUniversalCamera */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnaglyphUniversalCamera", function() { return AnaglyphUniversalCamera; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Cameras/camera */ "./Cameras/camera.ts"); +/* harmony import */ var _Cameras_universalCamera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/universalCamera */ "./Cameras/universalCamera.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../node */ "./node.ts"); +/* harmony import */ var _RigModes_stereoscopicAnaglyphRigMode__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../RigModes/stereoscopicAnaglyphRigMode */ "./Cameras/RigModes/stereoscopicAnaglyphRigMode.ts"); + + + + + +// Side effect import to define the stereoscopic mode. + +_node__WEBPACK_IMPORTED_MODULE_4__["Node"].AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) { + return function () { return new AnaglyphUniversalCamera(name, _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(), options.interaxial_distance, scene); }; +}); +/** + * Camera used to simulate anaglyphic rendering (based on UniversalCamera) + * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras + */ +var AnaglyphUniversalCamera = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](AnaglyphUniversalCamera, _super); + /** + * Creates a new AnaglyphUniversalCamera + * @param name defines camera name + * @param position defines initial position + * @param interaxialDistance defines distance between each color axis + * @param scene defines the hosting scene + */ + function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) { + var _this = _super.call(this, name, position, scene) || this; + _this.interaxialDistance = interaxialDistance; + _this.setCameraRigMode(_Cameras_camera__WEBPACK_IMPORTED_MODULE_1__["Camera"].RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance }); + return _this; + } + /** + * Gets camera class name + * @returns AnaglyphUniversalCamera + */ + AnaglyphUniversalCamera.prototype.getClassName = function () { + return "AnaglyphUniversalCamera"; + }; + return AnaglyphUniversalCamera; +}(_Cameras_universalCamera__WEBPACK_IMPORTED_MODULE_2__["UniversalCamera"])); + + + +/***/ }), + +/***/ "./Cameras/Stereoscopic/index.ts": +/*!***************************************!*\ + !*** ./Cameras/Stereoscopic/index.ts ***! + \***************************************/ +/*! exports provided: AnaglyphArcRotateCamera, AnaglyphFreeCamera, AnaglyphGamepadCamera, AnaglyphUniversalCamera, StereoscopicArcRotateCamera, StereoscopicFreeCamera, StereoscopicGamepadCamera, StereoscopicUniversalCamera */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _anaglyphArcRotateCamera__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./anaglyphArcRotateCamera */ "./Cameras/Stereoscopic/anaglyphArcRotateCamera.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnaglyphArcRotateCamera", function() { return _anaglyphArcRotateCamera__WEBPACK_IMPORTED_MODULE_0__["AnaglyphArcRotateCamera"]; }); + +/* harmony import */ var _anaglyphFreeCamera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./anaglyphFreeCamera */ "./Cameras/Stereoscopic/anaglyphFreeCamera.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnaglyphFreeCamera", function() { return _anaglyphFreeCamera__WEBPACK_IMPORTED_MODULE_1__["AnaglyphFreeCamera"]; }); + +/* harmony import */ var _anaglyphGamepadCamera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./anaglyphGamepadCamera */ "./Cameras/Stereoscopic/anaglyphGamepadCamera.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnaglyphGamepadCamera", function() { return _anaglyphGamepadCamera__WEBPACK_IMPORTED_MODULE_2__["AnaglyphGamepadCamera"]; }); + +/* harmony import */ var _anaglyphUniversalCamera__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./anaglyphUniversalCamera */ "./Cameras/Stereoscopic/anaglyphUniversalCamera.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnaglyphUniversalCamera", function() { return _anaglyphUniversalCamera__WEBPACK_IMPORTED_MODULE_3__["AnaglyphUniversalCamera"]; }); + +/* harmony import */ var _stereoscopicArcRotateCamera__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./stereoscopicArcRotateCamera */ "./Cameras/Stereoscopic/stereoscopicArcRotateCamera.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StereoscopicArcRotateCamera", function() { return _stereoscopicArcRotateCamera__WEBPACK_IMPORTED_MODULE_4__["StereoscopicArcRotateCamera"]; }); + +/* harmony import */ var _stereoscopicFreeCamera__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./stereoscopicFreeCamera */ "./Cameras/Stereoscopic/stereoscopicFreeCamera.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StereoscopicFreeCamera", function() { return _stereoscopicFreeCamera__WEBPACK_IMPORTED_MODULE_5__["StereoscopicFreeCamera"]; }); + +/* harmony import */ var _stereoscopicGamepadCamera__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./stereoscopicGamepadCamera */ "./Cameras/Stereoscopic/stereoscopicGamepadCamera.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StereoscopicGamepadCamera", function() { return _stereoscopicGamepadCamera__WEBPACK_IMPORTED_MODULE_6__["StereoscopicGamepadCamera"]; }); + +/* harmony import */ var _stereoscopicUniversalCamera__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./stereoscopicUniversalCamera */ "./Cameras/Stereoscopic/stereoscopicUniversalCamera.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StereoscopicUniversalCamera", function() { return _stereoscopicUniversalCamera__WEBPACK_IMPORTED_MODULE_7__["StereoscopicUniversalCamera"]; }); + + + + + + + + + + + +/***/ }), + +/***/ "./Cameras/Stereoscopic/stereoscopicArcRotateCamera.ts": +/*!*************************************************************!*\ + !*** ./Cameras/Stereoscopic/stereoscopicArcRotateCamera.ts ***! + \*************************************************************/ +/*! exports provided: StereoscopicArcRotateCamera */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StereoscopicArcRotateCamera", function() { return StereoscopicArcRotateCamera; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Cameras/camera */ "./Cameras/camera.ts"); +/* harmony import */ var _Cameras_arcRotateCamera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/arcRotateCamera */ "./Cameras/arcRotateCamera.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../node */ "./node.ts"); +/* harmony import */ var _RigModes_stereoscopicRigMode__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../RigModes/stereoscopicRigMode */ "./Cameras/RigModes/stereoscopicRigMode.ts"); + + + + + +// Side effect import to define the stereoscopic mode. + +_node__WEBPACK_IMPORTED_MODULE_4__["Node"].AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) { + return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); }; +}); +/** + * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera) + * @see http://doc.babylonjs.com/features/cameras + */ +var StereoscopicArcRotateCamera = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](StereoscopicArcRotateCamera, _super); + /** + * Creates a new StereoscopicArcRotateCamera + * @param name defines camera name + * @param alpha defines alpha angle (in radians) + * @param beta defines beta angle (in radians) + * @param radius defines radius + * @param target defines camera target + * @param interaxialDistance defines distance between each color axis + * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under + * @param scene defines the hosting scene + */ + function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) { + var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this; + _this.interaxialDistance = interaxialDistance; + _this.isStereoscopicSideBySide = isStereoscopicSideBySide; + _this.setCameraRigMode(isStereoscopicSideBySide ? _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__["Camera"].RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__["Camera"].RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance }); + return _this; + } + /** + * Gets camera class name + * @returns StereoscopicArcRotateCamera + */ + StereoscopicArcRotateCamera.prototype.getClassName = function () { + return "StereoscopicArcRotateCamera"; + }; + return StereoscopicArcRotateCamera; +}(_Cameras_arcRotateCamera__WEBPACK_IMPORTED_MODULE_2__["ArcRotateCamera"])); + + + +/***/ }), + +/***/ "./Cameras/Stereoscopic/stereoscopicFreeCamera.ts": +/*!********************************************************!*\ + !*** ./Cameras/Stereoscopic/stereoscopicFreeCamera.ts ***! + \********************************************************/ +/*! exports provided: StereoscopicFreeCamera */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StereoscopicFreeCamera", function() { return StereoscopicFreeCamera; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Cameras/camera */ "./Cameras/camera.ts"); +/* harmony import */ var _Cameras_freeCamera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/freeCamera */ "./Cameras/freeCamera.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../node */ "./node.ts"); +/* harmony import */ var _RigModes_stereoscopicRigMode__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../RigModes/stereoscopicRigMode */ "./Cameras/RigModes/stereoscopicRigMode.ts"); + + + + + +// Side effect import to define the stereoscopic mode. + +_node__WEBPACK_IMPORTED_MODULE_4__["Node"].AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) { + return function () { return new StereoscopicFreeCamera(name, _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); }; +}); +/** + * Camera used to simulate stereoscopic rendering (based on FreeCamera) + * @see http://doc.babylonjs.com/features/cameras + */ +var StereoscopicFreeCamera = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](StereoscopicFreeCamera, _super); + /** + * Creates a new StereoscopicFreeCamera + * @param name defines camera name + * @param position defines initial position + * @param interaxialDistance defines distance between each color axis + * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under + * @param scene defines the hosting scene + */ + function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) { + var _this = _super.call(this, name, position, scene) || this; + _this.interaxialDistance = interaxialDistance; + _this.isStereoscopicSideBySide = isStereoscopicSideBySide; + _this.setCameraRigMode(isStereoscopicSideBySide ? _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__["Camera"].RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__["Camera"].RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance }); + return _this; + } + /** + * Gets camera class name + * @returns StereoscopicFreeCamera + */ + StereoscopicFreeCamera.prototype.getClassName = function () { + return "StereoscopicFreeCamera"; + }; + return StereoscopicFreeCamera; +}(_Cameras_freeCamera__WEBPACK_IMPORTED_MODULE_2__["FreeCamera"])); + + + +/***/ }), + +/***/ "./Cameras/Stereoscopic/stereoscopicGamepadCamera.ts": +/*!***********************************************************!*\ + !*** ./Cameras/Stereoscopic/stereoscopicGamepadCamera.ts ***! + \***********************************************************/ +/*! exports provided: StereoscopicGamepadCamera */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StereoscopicGamepadCamera", function() { return StereoscopicGamepadCamera; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Cameras/camera */ "./Cameras/camera.ts"); +/* harmony import */ var _Cameras_gamepadCamera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/gamepadCamera */ "./Cameras/gamepadCamera.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../node */ "./node.ts"); +/* harmony import */ var _RigModes_stereoscopicRigMode__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../RigModes/stereoscopicRigMode */ "./Cameras/RigModes/stereoscopicRigMode.ts"); + + + + + +// Side effect import to define the stereoscopic mode. + +_node__WEBPACK_IMPORTED_MODULE_4__["Node"].AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) { + return function () { return new StereoscopicGamepadCamera(name, _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); }; +}); +/** + * Camera used to simulate stereoscopic rendering (based on GamepadCamera) + * @see http://doc.babylonjs.com/features/cameras + */ +var StereoscopicGamepadCamera = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](StereoscopicGamepadCamera, _super); + /** + * Creates a new StereoscopicGamepadCamera + * @param name defines camera name + * @param position defines initial position + * @param interaxialDistance defines distance between each color axis + * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under + * @param scene defines the hosting scene + */ + function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) { + var _this = _super.call(this, name, position, scene) || this; + _this.interaxialDistance = interaxialDistance; + _this.isStereoscopicSideBySide = isStereoscopicSideBySide; + _this.setCameraRigMode(isStereoscopicSideBySide ? _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__["Camera"].RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__["Camera"].RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance }); + return _this; + } + /** + * Gets camera class name + * @returns StereoscopicGamepadCamera + */ + StereoscopicGamepadCamera.prototype.getClassName = function () { + return "StereoscopicGamepadCamera"; + }; + return StereoscopicGamepadCamera; +}(_Cameras_gamepadCamera__WEBPACK_IMPORTED_MODULE_2__["GamepadCamera"])); + + + +/***/ }), + +/***/ "./Cameras/Stereoscopic/stereoscopicUniversalCamera.ts": +/*!*************************************************************!*\ + !*** ./Cameras/Stereoscopic/stereoscopicUniversalCamera.ts ***! + \*************************************************************/ +/*! exports provided: StereoscopicUniversalCamera */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StereoscopicUniversalCamera", function() { return StereoscopicUniversalCamera; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Cameras/camera */ "./Cameras/camera.ts"); +/* harmony import */ var _Cameras_universalCamera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/universalCamera */ "./Cameras/universalCamera.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../node */ "./node.ts"); +/* harmony import */ var _RigModes_stereoscopicRigMode__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../RigModes/stereoscopicRigMode */ "./Cameras/RigModes/stereoscopicRigMode.ts"); + + + + + +// Side effect import to define the stereoscopic mode. + +_node__WEBPACK_IMPORTED_MODULE_4__["Node"].AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) { + return function () { return new StereoscopicUniversalCamera(name, _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); }; +}); +/** + * Camera used to simulate stereoscopic rendering (based on UniversalCamera) + * @see http://doc.babylonjs.com/features/cameras + */ +var StereoscopicUniversalCamera = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](StereoscopicUniversalCamera, _super); + /** + * Creates a new StereoscopicUniversalCamera + * @param name defines camera name + * @param position defines initial position + * @param interaxialDistance defines distance between each color axis + * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under + * @param scene defines the hosting scene + */ + function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) { + var _this = _super.call(this, name, position, scene) || this; + _this.interaxialDistance = interaxialDistance; + _this.isStereoscopicSideBySide = isStereoscopicSideBySide; + _this.setCameraRigMode(isStereoscopicSideBySide ? _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__["Camera"].RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__["Camera"].RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance }); + return _this; + } + /** + * Gets camera class name + * @returns StereoscopicUniversalCamera + */ + StereoscopicUniversalCamera.prototype.getClassName = function () { + return "StereoscopicUniversalCamera"; + }; + return StereoscopicUniversalCamera; +}(_Cameras_universalCamera__WEBPACK_IMPORTED_MODULE_2__["UniversalCamera"])); + + + +/***/ }), + +/***/ "./Cameras/VR/index.ts": +/*!*****************************!*\ + !*** ./Cameras/VR/index.ts ***! + \*****************************/ +/*! exports provided: VRCameraMetrics, VRDeviceOrientationArcRotateCamera, VRDeviceOrientationFreeCamera, VRDeviceOrientationGamepadCamera, OnAfterEnteringVRObservableEvent, VRExperienceHelper, WebVRFreeCamera */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _vrCameraMetrics__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./vrCameraMetrics */ "./Cameras/VR/vrCameraMetrics.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRCameraMetrics", function() { return _vrCameraMetrics__WEBPACK_IMPORTED_MODULE_0__["VRCameraMetrics"]; }); + +/* harmony import */ var _vrDeviceOrientationArcRotateCamera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./vrDeviceOrientationArcRotateCamera */ "./Cameras/VR/vrDeviceOrientationArcRotateCamera.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRDeviceOrientationArcRotateCamera", function() { return _vrDeviceOrientationArcRotateCamera__WEBPACK_IMPORTED_MODULE_1__["VRDeviceOrientationArcRotateCamera"]; }); + +/* harmony import */ var _vrDeviceOrientationFreeCamera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./vrDeviceOrientationFreeCamera */ "./Cameras/VR/vrDeviceOrientationFreeCamera.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRDeviceOrientationFreeCamera", function() { return _vrDeviceOrientationFreeCamera__WEBPACK_IMPORTED_MODULE_2__["VRDeviceOrientationFreeCamera"]; }); + +/* harmony import */ var _vrDeviceOrientationGamepadCamera__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./vrDeviceOrientationGamepadCamera */ "./Cameras/VR/vrDeviceOrientationGamepadCamera.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRDeviceOrientationGamepadCamera", function() { return _vrDeviceOrientationGamepadCamera__WEBPACK_IMPORTED_MODULE_3__["VRDeviceOrientationGamepadCamera"]; }); + +/* harmony import */ var _vrExperienceHelper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./vrExperienceHelper */ "./Cameras/VR/vrExperienceHelper.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OnAfterEnteringVRObservableEvent", function() { return _vrExperienceHelper__WEBPACK_IMPORTED_MODULE_4__["OnAfterEnteringVRObservableEvent"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRExperienceHelper", function() { return _vrExperienceHelper__WEBPACK_IMPORTED_MODULE_4__["VRExperienceHelper"]; }); + +/* harmony import */ var _webVRCamera__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./webVRCamera */ "./Cameras/VR/webVRCamera.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebVRFreeCamera", function() { return _webVRCamera__WEBPACK_IMPORTED_MODULE_5__["WebVRFreeCamera"]; }); + + + + + + + + + +/***/ }), + +/***/ "./Cameras/VR/vrCameraMetrics.ts": +/*!***************************************!*\ + !*** ./Cameras/VR/vrCameraMetrics.ts ***! + \***************************************/ +/*! exports provided: VRCameraMetrics */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VRCameraMetrics", function() { return VRCameraMetrics; }); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); + +/** + * This represents all the required metrics to create a VR camera. + * @see http://doc.babylonjs.com/babylon101/cameras#device-orientation-camera + */ +var VRCameraMetrics = /** @class */ (function () { + function VRCameraMetrics() { + /** + * Define if the current vr camera should compensate the distortion of the lense or not. + */ + this.compensateDistortion = true; + /** + * Defines if multiview should be enabled when rendering (Default: false) + */ + this.multiviewEnabled = false; + } + Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", { + /** + * Gets the rendering aspect ratio based on the provided resolutions. + */ + get: function () { + return this.hResolution / (2 * this.vResolution); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", { + /** + * Gets the aspect ratio based on the FOV, scale factors, and real screen sizes. + */ + get: function () { + return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance))); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", { + /** + * @hidden + */ + get: function () { + var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2); + var h = (4 * meters) / this.hScreenSize; + return _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].Translation(h, 0, 0); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", { + /** + * @hidden + */ + get: function () { + var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2); + var h = (4 * meters) / this.hScreenSize; + return _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].Translation(-h, 0, 0); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", { + /** + * @hidden + */ + get: function () { + return _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].Translation(0.5 * this.interpupillaryDistance, 0, 0); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", { + /** + * @hidden + */ + get: function () { + return _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].Translation(-0.5 * this.interpupillaryDistance, 0, 0); + }, + enumerable: true, + configurable: true + }); + /** + * Get the default VRMetrics based on the most generic setup. + * @returns the default vr metrics + */ + VRCameraMetrics.GetDefault = function () { + var result = new VRCameraMetrics(); + result.hResolution = 1280; + result.vResolution = 800; + result.hScreenSize = 0.149759993; + result.vScreenSize = 0.0935999975; + result.vScreenCenter = 0.0467999987; + result.eyeToScreenDistance = 0.0410000011; + result.lensSeparationDistance = 0.0635000020; + result.interpupillaryDistance = 0.0640000030; + result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0]; + result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0]; + result.postProcessScaleFactor = 1.714605507808412; + result.lensCenterOffset = 0.151976421; + return result; + }; + return VRCameraMetrics; +}()); + + + +/***/ }), + +/***/ "./Cameras/VR/vrDeviceOrientationArcRotateCamera.ts": +/*!**********************************************************!*\ + !*** ./Cameras/VR/vrDeviceOrientationArcRotateCamera.ts ***! + \**********************************************************/ +/*! exports provided: VRDeviceOrientationArcRotateCamera */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VRDeviceOrientationArcRotateCamera", function() { return VRDeviceOrientationArcRotateCamera; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Cameras/camera */ "./Cameras/camera.ts"); +/* harmony import */ var _Cameras_arcRotateCamera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/arcRotateCamera */ "./Cameras/arcRotateCamera.ts"); +/* harmony import */ var _vrCameraMetrics__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./vrCameraMetrics */ "./Cameras/VR/vrCameraMetrics.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../node */ "./node.ts"); +/* harmony import */ var _Inputs_arcRotateCameraVRDeviceOrientationInput__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Inputs/arcRotateCameraVRDeviceOrientationInput */ "./Cameras/Inputs/arcRotateCameraVRDeviceOrientationInput.ts"); +/* harmony import */ var _RigModes_vrRigMode__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../RigModes/vrRigMode */ "./Cameras/RigModes/vrRigMode.ts"); + + + + + + + +// Side effect import to define the stereoscopic mode. + +_node__WEBPACK_IMPORTED_MODULE_5__["Node"].AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) { + return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"].Zero(), scene); }; +}); +/** + * Camera used to simulate VR rendering (based on ArcRotateCamera) + * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras + */ +var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](VRDeviceOrientationArcRotateCamera, _super); + /** + * Creates a new VRDeviceOrientationArcRotateCamera + * @param name defines camera name + * @param alpha defines the camera rotation along the logitudinal axis + * @param beta defines the camera rotation along the latitudinal axis + * @param radius defines the camera distance from its target + * @param target defines the camera target + * @param scene defines the scene the camera belongs to + * @param compensateDistortion defines if the camera needs to compensate the lens distorsion + * @param vrCameraMetrics defines the vr metrics associated to the camera + */ + function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) { + if (compensateDistortion === void 0) { compensateDistortion = true; } + if (vrCameraMetrics === void 0) { vrCameraMetrics = _vrCameraMetrics__WEBPACK_IMPORTED_MODULE_3__["VRCameraMetrics"].GetDefault(); } + var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this; + vrCameraMetrics.compensateDistortion = compensateDistortion; + _this.setCameraRigMode(_Cameras_camera__WEBPACK_IMPORTED_MODULE_1__["Camera"].RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics }); + _this.inputs.addVRDeviceOrientation(); + return _this; + } + /** + * Gets camera class name + * @returns VRDeviceOrientationArcRotateCamera + */ + VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () { + return "VRDeviceOrientationArcRotateCamera"; + }; + return VRDeviceOrientationArcRotateCamera; +}(_Cameras_arcRotateCamera__WEBPACK_IMPORTED_MODULE_2__["ArcRotateCamera"])); + + + +/***/ }), + +/***/ "./Cameras/VR/vrDeviceOrientationFreeCamera.ts": +/*!*****************************************************!*\ + !*** ./Cameras/VR/vrDeviceOrientationFreeCamera.ts ***! + \*****************************************************/ +/*! exports provided: VRDeviceOrientationFreeCamera */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VRDeviceOrientationFreeCamera", function() { return VRDeviceOrientationFreeCamera; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Cameras/camera */ "./Cameras/camera.ts"); +/* harmony import */ var _Cameras_deviceOrientationCamera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/deviceOrientationCamera */ "./Cameras/deviceOrientationCamera.ts"); +/* harmony import */ var _vrCameraMetrics__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./vrCameraMetrics */ "./Cameras/VR/vrCameraMetrics.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../node */ "./node.ts"); +/* harmony import */ var _RigModes_vrRigMode__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../RigModes/vrRigMode */ "./Cameras/RigModes/vrRigMode.ts"); + + + + + + +// Side effect import to define the stereoscopic mode. + +_node__WEBPACK_IMPORTED_MODULE_5__["Node"].AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) { + return function () { return new VRDeviceOrientationFreeCamera(name, _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"].Zero(), scene); }; +}); +/** + * Camera used to simulate VR rendering (based on FreeCamera) + * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras + */ +var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](VRDeviceOrientationFreeCamera, _super); + /** + * Creates a new VRDeviceOrientationFreeCamera + * @param name defines camera name + * @param position defines the start position of the camera + * @param scene defines the scene the camera belongs to + * @param compensateDistortion defines if the camera needs to compensate the lens distorsion + * @param vrCameraMetrics defines the vr metrics associated to the camera + */ + function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) { + if (compensateDistortion === void 0) { compensateDistortion = true; } + if (vrCameraMetrics === void 0) { vrCameraMetrics = _vrCameraMetrics__WEBPACK_IMPORTED_MODULE_3__["VRCameraMetrics"].GetDefault(); } + var _this = _super.call(this, name, position, scene) || this; + vrCameraMetrics.compensateDistortion = compensateDistortion; + _this.setCameraRigMode(_Cameras_camera__WEBPACK_IMPORTED_MODULE_1__["Camera"].RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics }); + return _this; + } + /** + * Gets camera class name + * @returns VRDeviceOrientationFreeCamera + */ + VRDeviceOrientationFreeCamera.prototype.getClassName = function () { + return "VRDeviceOrientationFreeCamera"; + }; + return VRDeviceOrientationFreeCamera; +}(_Cameras_deviceOrientationCamera__WEBPACK_IMPORTED_MODULE_2__["DeviceOrientationCamera"])); + + + +/***/ }), + +/***/ "./Cameras/VR/vrDeviceOrientationGamepadCamera.ts": +/*!********************************************************!*\ + !*** ./Cameras/VR/vrDeviceOrientationGamepadCamera.ts ***! + \********************************************************/ +/*! exports provided: VRDeviceOrientationGamepadCamera */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VRDeviceOrientationGamepadCamera", function() { return VRDeviceOrientationGamepadCamera; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _vrDeviceOrientationFreeCamera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./vrDeviceOrientationFreeCamera */ "./Cameras/VR/vrDeviceOrientationFreeCamera.ts"); +/* harmony import */ var _vrCameraMetrics__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./vrCameraMetrics */ "./Cameras/VR/vrCameraMetrics.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../node */ "./node.ts"); +/* harmony import */ var _Gamepads_gamepadSceneComponent__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Gamepads/gamepadSceneComponent */ "./Gamepads/gamepadSceneComponent.ts"); + + + + + + +_node__WEBPACK_IMPORTED_MODULE_4__["Node"].AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) { + return function () { return new VRDeviceOrientationGamepadCamera(name, _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(), scene); }; +}); +/** + * Camera used to simulate VR rendering (based on VRDeviceOrientationFreeCamera) + * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras + */ +var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](VRDeviceOrientationGamepadCamera, _super); + /** + * Creates a new VRDeviceOrientationGamepadCamera + * @param name defines camera name + * @param position defines the start position of the camera + * @param scene defines the scene the camera belongs to + * @param compensateDistortion defines if the camera needs to compensate the lens distorsion + * @param vrCameraMetrics defines the vr metrics associated to the camera + */ + function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) { + if (compensateDistortion === void 0) { compensateDistortion = true; } + if (vrCameraMetrics === void 0) { vrCameraMetrics = _vrCameraMetrics__WEBPACK_IMPORTED_MODULE_2__["VRCameraMetrics"].GetDefault(); } + var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this; + _this.inputs.addGamepad(); + return _this; + } + /** + * Gets camera class name + * @returns VRDeviceOrientationGamepadCamera + */ + VRDeviceOrientationGamepadCamera.prototype.getClassName = function () { + return "VRDeviceOrientationGamepadCamera"; + }; + return VRDeviceOrientationGamepadCamera; +}(_vrDeviceOrientationFreeCamera__WEBPACK_IMPORTED_MODULE_1__["VRDeviceOrientationFreeCamera"])); + + + +/***/ }), + +/***/ "./Cameras/VR/vrExperienceHelper.ts": +/*!******************************************!*\ + !*** ./Cameras/VR/vrExperienceHelper.ts ***! + \******************************************/ +/*! exports provided: OnAfterEnteringVRObservableEvent, VRExperienceHelper */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OnAfterEnteringVRObservableEvent", function() { return OnAfterEnteringVRObservableEvent; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VRExperienceHelper", function() { return VRExperienceHelper; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/logger */ "./Misc/logger.ts"); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _Cameras_freeCamera__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Cameras/freeCamera */ "./Cameras/freeCamera.ts"); +/* harmony import */ var _Cameras_targetCamera__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Cameras/targetCamera */ "./Cameras/targetCamera.ts"); +/* harmony import */ var _Cameras_deviceOrientationCamera__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Cameras/deviceOrientationCamera */ "./Cameras/deviceOrientationCamera.ts"); +/* harmony import */ var _Cameras_VR_vrDeviceOrientationFreeCamera__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../Cameras/VR/vrDeviceOrientationFreeCamera */ "./Cameras/VR/vrDeviceOrientationFreeCamera.ts"); +/* harmony import */ var _Cameras_VR_webVRCamera__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../Cameras/VR/webVRCamera */ "./Cameras/VR/webVRCamera.ts"); +/* harmony import */ var _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../Events/pointerEvents */ "./Events/pointerEvents.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../../Gamepads/gamepad */ "./Gamepads/gamepad.ts"); +/* harmony import */ var _Gamepads_Controllers_poseEnabledController__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../../Gamepads/Controllers/poseEnabledController */ "./Gamepads/Controllers/poseEnabledController.ts"); +/* harmony import */ var _Gamepads_Controllers_webVRController__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../../Gamepads/Controllers/webVRController */ "./Gamepads/Controllers/webVRController.ts"); +/* harmony import */ var _Gamepads_xboxGamepad__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../../Gamepads/xboxGamepad */ "./Gamepads/xboxGamepad.ts"); +/* harmony import */ var _Meshes_mesh__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../../Meshes/mesh */ "./Meshes/mesh.ts"); +/* harmony import */ var _Culling_ray__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../../Culling/ray */ "./Culling/ray.ts"); +/* harmony import */ var _Materials_imageProcessingConfiguration__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../../Materials/imageProcessingConfiguration */ "./Materials/imageProcessingConfiguration.ts"); +/* harmony import */ var _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../../Materials/standardMaterial */ "./Materials/standardMaterial.ts"); +/* harmony import */ var _Materials_Textures_dynamicTexture__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../../Materials/Textures/dynamicTexture */ "./Materials/Textures/dynamicTexture.ts"); +/* harmony import */ var _PostProcesses_imageProcessingPostProcess__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../../PostProcesses/imageProcessingPostProcess */ "./PostProcesses/imageProcessingPostProcess.ts"); +/* harmony import */ var _Animations_easing__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../../Animations/easing */ "./Animations/easing.ts"); +/* harmony import */ var _Animations_animation__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ../../Animations/animation */ "./Animations/animation.ts"); +/* harmony import */ var _Cameras_VR_vrCameraMetrics__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ../../Cameras/VR/vrCameraMetrics */ "./Cameras/VR/vrCameraMetrics.ts"); +/* harmony import */ var _Meshes_Builders_groundBuilder__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ../../Meshes/Builders/groundBuilder */ "./Meshes/Builders/groundBuilder.ts"); +/* harmony import */ var _Meshes_Builders_torusBuilder__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ../../Meshes/Builders/torusBuilder */ "./Meshes/Builders/torusBuilder.ts"); +/* harmony import */ var _Meshes_Builders_cylinderBuilder__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ../../Meshes/Builders/cylinderBuilder */ "./Meshes/Builders/cylinderBuilder.ts"); +/* harmony import */ var _Gamepads_gamepadSceneComponent__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ../../Gamepads/gamepadSceneComponent */ "./Gamepads/gamepadSceneComponent.ts"); +/* harmony import */ var _Animations_animatable__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ../../Animations/animatable */ "./Animations/animatable.ts"); + + + + + + + + + + + + + + + + + + + + + + + + + + + + +var VRExperienceHelperGazer = /** @class */ (function () { + function VRExperienceHelperGazer(scene, gazeTrackerToClone) { + if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; } + this.scene = scene; + /** @hidden */ + this._pointerDownOnMeshAsked = false; + /** @hidden */ + this._isActionableMesh = false; + /** @hidden */ + this._teleportationRequestInitiated = false; + /** @hidden */ + this._teleportationBackRequestInitiated = false; + /** @hidden */ + this._rotationRightAsked = false; + /** @hidden */ + this._rotationLeftAsked = false; + /** @hidden */ + this._dpadPressed = true; + /** @hidden */ + this._activePointer = false; + this._id = VRExperienceHelperGazer._idCounter++; + // Gaze tracker + if (!gazeTrackerToClone) { + this._gazeTracker = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_14__["Mesh"].CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false); + this._gazeTracker.bakeCurrentTransformIntoVertices(); + this._gazeTracker.isPickable = false; + this._gazeTracker.isVisible = false; + var targetMat = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_17__["StandardMaterial"]("targetMat", scene); + targetMat.specularColor = _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Color3"].Black(); + targetMat.emissiveColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Color3"](0.7, 0.7, 0.7); + targetMat.backFaceCulling = false; + this._gazeTracker.material = targetMat; + } + else { + this._gazeTracker = gazeTrackerToClone.clone("gazeTracker"); + } + } + /** @hidden */ + VRExperienceHelperGazer.prototype._getForwardRay = function (length) { + return new _Culling_ray__WEBPACK_IMPORTED_MODULE_15__["Ray"](_Maths_math__WEBPACK_IMPORTED_MODULE_9__["Vector3"].Zero(), new _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Vector3"](0, 0, length)); + }; + /** @hidden */ + VRExperienceHelperGazer.prototype._selectionPointerDown = function () { + this._pointerDownOnMeshAsked = true; + if (this._currentHit) { + this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id }); + } + }; + /** @hidden */ + VRExperienceHelperGazer.prototype._selectionPointerUp = function () { + if (this._currentHit) { + this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id }); + } + this._pointerDownOnMeshAsked = false; + }; + /** @hidden */ + VRExperienceHelperGazer.prototype._activatePointer = function () { + this._activePointer = true; + }; + /** @hidden */ + VRExperienceHelperGazer.prototype._deactivatePointer = function () { + this._activePointer = false; + }; + /** @hidden */ + VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) { + if (distance === void 0) { distance = 100; } + }; + VRExperienceHelperGazer.prototype.dispose = function () { + this._interactionsEnabled = false; + this._teleportationEnabled = false; + if (this._gazeTracker) { + this._gazeTracker.dispose(); + } + }; + VRExperienceHelperGazer._idCounter = 0; + return VRExperienceHelperGazer; +}()); +var VRExperienceHelperControllerGazer = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](VRExperienceHelperControllerGazer, _super); + function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) { + var _this = _super.call(this, scene, gazeTrackerToClone) || this; + _this.webVRController = webVRController; + // Laser pointer + _this._laserPointer = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_14__["Mesh"].CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false); + var laserPointerMaterial = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_17__["StandardMaterial"]("laserPointerMat", scene); + laserPointerMaterial.emissiveColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Color3"](0.7, 0.7, 0.7); + laserPointerMaterial.alpha = 0.6; + _this._laserPointer.material = laserPointerMaterial; + _this._laserPointer.rotation.x = Math.PI / 2; + _this._laserPointer.position.z = -0.5; + _this._laserPointer.isVisible = false; + _this._laserPointer.isPickable = false; + if (!webVRController.mesh) { + // Create an empty mesh that is used prior to loading the high quality model + var preloadMesh = new _Meshes_mesh__WEBPACK_IMPORTED_MODULE_14__["Mesh"]("preloadControllerMesh", scene); + var preloadPointerPose = new _Meshes_mesh__WEBPACK_IMPORTED_MODULE_14__["Mesh"](_Gamepads_Controllers_poseEnabledController__WEBPACK_IMPORTED_MODULE_11__["PoseEnabledController"].POINTING_POSE, scene); + preloadPointerPose.rotation.x = -0.7; + preloadMesh.addChild(preloadPointerPose); + webVRController.attachToMesh(preloadMesh); + } + _this._setLaserPointerParent(webVRController.mesh); + _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) { + _this._setLaserPointerParent(mesh); + }); + return _this; + } + VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) { + return this.webVRController.getForwardRay(length); + }; + /** @hidden */ + VRExperienceHelperControllerGazer.prototype._activatePointer = function () { + _super.prototype._activatePointer.call(this); + this._laserPointer.isVisible = true; + }; + /** @hidden */ + VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () { + _super.prototype._deactivatePointer.call(this); + this._laserPointer.isVisible = false; + }; + /** @hidden */ + VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) { + this._laserPointer.material.emissiveColor = color; + }; + /** @hidden */ + VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) { + var makeNotPick = function (root) { + root.isPickable = false; + root.getChildMeshes().forEach(function (c) { + makeNotPick(c); + }); + }; + makeNotPick(mesh); + var meshChildren = mesh.getChildren(undefined, false); + var laserParent = mesh; + this.webVRController._pointingPoseNode = null; + for (var i = 0; i < meshChildren.length; i++) { + if (meshChildren[i].name && meshChildren[i].name.indexOf(_Gamepads_Controllers_poseEnabledController__WEBPACK_IMPORTED_MODULE_11__["PoseEnabledController"].POINTING_POSE) >= 0) { + laserParent = meshChildren[i]; + this.webVRController._pointingPoseNode = laserParent; + break; + } + } + this._laserPointer.parent = laserParent; + }; + VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) { + if (distance === void 0) { distance = 100; } + this._laserPointer.scaling.y = distance; + this._laserPointer.position.z = -distance / 2; + }; + VRExperienceHelperControllerGazer.prototype.dispose = function () { + _super.prototype.dispose.call(this); + this._laserPointer.dispose(); + if (this._meshAttachedObserver) { + this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver); + } + }; + return VRExperienceHelperControllerGazer; +}(VRExperienceHelperGazer)); +var VRExperienceHelperCameraGazer = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](VRExperienceHelperCameraGazer, _super); + function VRExperienceHelperCameraGazer(getCamera, scene) { + var _this = _super.call(this, scene) || this; + _this.getCamera = getCamera; + return _this; + } + VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) { + var camera = this.getCamera(); + if (camera) { + return camera.getForwardRay(length); + } + else { + return new _Culling_ray__WEBPACK_IMPORTED_MODULE_15__["Ray"](_Maths_math__WEBPACK_IMPORTED_MODULE_9__["Vector3"].Zero(), _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Vector3"].Forward()); + } + }; + return VRExperienceHelperCameraGazer; +}(VRExperienceHelperGazer)); +/** + * Event containing information after VR has been entered + */ +var OnAfterEnteringVRObservableEvent = /** @class */ (function () { + function OnAfterEnteringVRObservableEvent() { + } + return OnAfterEnteringVRObservableEvent; +}()); + +/** + * Helps to quickly add VR support to an existing scene. + * See http://doc.babylonjs.com/how_to/webvr_helper + */ +var VRExperienceHelper = /** @class */ (function () { + /** + * Instantiates a VRExperienceHelper. + * Helps to quickly add VR support to an existing scene. + * @param scene The scene the VRExperienceHelper belongs to. + * @param webVROptions Options to modify the vr experience helper's behavior. + */ + function VRExperienceHelper(scene, + /** Options to modify the vr experience helper's behavior. */ + webVROptions) { + var _this = this; + if (webVROptions === void 0) { webVROptions = {}; } + this.webVROptions = webVROptions; + // Can the system support WebVR, even if a headset isn't plugged in? + this._webVRsupported = false; + // If WebVR is supported, is a headset plugged in and are we ready to present? + this._webVRready = false; + // Are we waiting for the requestPresent callback to complete? + this._webVRrequesting = false; + // Are we presenting to the headset right now? (this is the vrDevice state) + this._webVRpresenting = false; + // Are we presenting in the fullscreen fallback? + this._fullscreenVRpresenting = false; + /** + * Observable raised right before entering VR. + */ + this.onEnteringVRObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); + /** + * Observable raised when entering VR has completed. + */ + this.onAfterEnteringVRObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); + /** + * Observable raised when exiting VR. + */ + this.onExitingVRObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); + /** + * Observable raised when controller mesh is loaded. + */ + this.onControllerMeshLoadedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); + this._useCustomVRButton = false; + this._teleportationRequested = false; + this._teleportActive = false; + this._floorMeshesCollection = []; + this._rotationAllowed = true; + this._teleportBackwardsVector = new _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Vector3"](0, -1, -1); + this._isDefaultTeleportationTarget = true; + this._teleportationFillColor = "#444444"; + this._teleportationBorderColor = "#FFFFFF"; + this._rotationAngle = 0; + this._haloCenter = new _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Vector3"](0, 0, 0); + this._padSensibilityUp = 0.65; + this._padSensibilityDown = 0.35; + this._leftController = null; + this._rightController = null; + /** + * Observable raised when a new mesh is selected based on meshSelectionPredicate + */ + this.onNewMeshSelected = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); + /** + * Observable raised when a new mesh is picked based on meshSelectionPredicate + */ + this.onNewMeshPicked = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); + /** + * Observable raised before camera teleportation + */ + this.onBeforeCameraTeleport = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); + /** + * Observable raised after camera teleportation + */ + this.onAfterCameraTeleport = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); + /** + * Observable raised when current selected mesh gets unselected + */ + this.onSelectedMeshUnselected = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); + /** + * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept. + */ + this.teleportationEnabled = true; + this._teleportationInitialized = false; + this._interactionsEnabled = false; + this._interactionsRequested = false; + this._displayGaze = true; + this._displayLaserPointer = true; + /** + * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes + */ + this.updateGazeTrackerScale = true; + /** + * If the gaze trackers color should be updated when selecting meshes + */ + this.updateGazeTrackerColor = true; + /** + * Defines wether or not Pointer lock should be requested when switching to + * full screen. + */ + this.requestPointerLockOnFullScreen = true; + this._onResize = function () { + _this.moveButtonToBottomRight(); + if (_this._fullscreenVRpresenting && _this._webVRready) { + _this.exitVR(); + } + }; + this._onFullscreenChange = function () { + var anyDoc = document; + if (anyDoc.fullscreen !== undefined) { + _this._fullscreenVRpresenting = document.fullscreen; + } + else if (anyDoc.mozFullScreen !== undefined) { + _this._fullscreenVRpresenting = anyDoc.mozFullScreen; + } + else if (anyDoc.webkitIsFullScreen !== undefined) { + _this._fullscreenVRpresenting = anyDoc.webkitIsFullScreen; + } + else if (anyDoc.msIsFullScreen !== undefined) { + _this._fullscreenVRpresenting = anyDoc.msIsFullScreen; + } + else if (document.msFullscreenElement !== undefined) { + _this._fullscreenVRpresenting = document.msFullscreenElement; + } + if (!_this._fullscreenVRpresenting && _this._canvas) { + _this.exitVR(); + if (!_this._useCustomVRButton) { + _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px"; + _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px"; + } + } + }; + this._cachedAngularSensibility = { angularSensibilityX: null, angularSensibilityY: null, angularSensibility: null }; + this.beforeRender = function () { + if (_this._leftController && _this._leftController._activePointer) { + _this._castRayAndSelectObject(_this._leftController); + } + if (_this._rightController && _this._rightController._activePointer) { + _this._castRayAndSelectObject(_this._rightController); + } + if (_this._noControllerIsActive) { + _this._castRayAndSelectObject(_this._cameraGazer); + } + else { + _this._cameraGazer._gazeTracker.isVisible = false; + } + }; + this._onNewGamepadConnected = function (gamepad) { + if (gamepad.type !== _Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_10__["Gamepad"].POSE_ENABLED) { + if (gamepad.leftStick) { + gamepad.onleftstickchanged(function (stickValues) { + if (_this._teleportationInitialized && _this.teleportationEnabled) { + // Listening to classic/xbox gamepad only if no VR controller is active + if ((!_this._leftController && !_this._rightController) || + ((_this._leftController && !_this._leftController._activePointer) && + (_this._rightController && !_this._rightController._activePointer))) { + _this._checkTeleportWithRay(stickValues, _this._cameraGazer); + _this._checkTeleportBackwards(stickValues, _this._cameraGazer); + } + } + }); + } + if (gamepad.rightStick) { + gamepad.onrightstickchanged(function (stickValues) { + if (_this._teleportationInitialized) { + _this._checkRotate(stickValues, _this._cameraGazer); + } + }); + } + if (gamepad.type === _Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_10__["Gamepad"].XBOX) { + gamepad.onbuttondown(function (buttonPressed) { + if (_this._interactionsEnabled && buttonPressed === _Gamepads_xboxGamepad__WEBPACK_IMPORTED_MODULE_13__["Xbox360Button"].A) { + _this._cameraGazer._selectionPointerDown(); + } + }); + gamepad.onbuttonup(function (buttonPressed) { + if (_this._interactionsEnabled && buttonPressed === _Gamepads_xboxGamepad__WEBPACK_IMPORTED_MODULE_13__["Xbox360Button"].A) { + _this._cameraGazer._selectionPointerUp(); + } + }); + } + } + else { + var webVRController = gamepad; + var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker); + if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) { + _this._rightController = controller; + } + else { + _this._leftController = controller; + } + _this._tryEnableInteractionOnController(controller); + } + }; + // This only succeeds if the controller's mesh exists for the controller so this must be called whenever new controller is connected or when mesh is loaded + this._tryEnableInteractionOnController = function (controller) { + if (_this._interactionsRequested && !controller._interactionsEnabled) { + _this._enableInteractionOnController(controller); + } + if (_this._teleportationRequested && !controller._teleportationEnabled) { + _this._enableTeleportationOnController(controller); + } + }; + this._onNewGamepadDisconnected = function (gamepad) { + if (gamepad instanceof _Gamepads_Controllers_webVRController__WEBPACK_IMPORTED_MODULE_12__["WebVRController"]) { + if (gamepad.hand === "left" && _this._leftController != null) { + _this._leftController.dispose(); + _this._leftController = null; + } + if (gamepad.hand === "right" && _this._rightController != null) { + _this._rightController.dispose(); + _this._rightController = null; + } + } + }; + this._workingVector = _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Vector3"].Zero(); + this._workingQuaternion = _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Quaternion"].Identity(); + this._workingMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Matrix"].Identity(); + this._scene = scene; + this._canvas = scene.getEngine().getRenderingCanvas(); + // Parse options + if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) { + webVROptions.createFallbackVRDeviceOrientationFreeCamera = true; + } + if (webVROptions.createDeviceOrientationCamera === undefined) { + webVROptions.createDeviceOrientationCamera = true; + } + if (webVROptions.laserToggle === undefined) { + webVROptions.laserToggle = true; + } + if (webVROptions.defaultHeight === undefined) { + webVROptions.defaultHeight = 1.7; + } + if (webVROptions.useCustomVRButton) { + this._useCustomVRButton = true; + if (webVROptions.customVRButton) { + this._btnVR = webVROptions.customVRButton; + } + } + if (webVROptions.rayLength) { + this._rayLength = webVROptions.rayLength; + } + this._defaultHeight = webVROptions.defaultHeight; + if (webVROptions.positionScale) { + this._rayLength *= webVROptions.positionScale; + this._defaultHeight *= webVROptions.positionScale; + } + this._hasEnteredVR = false; + // Set position + if (this._scene.activeCamera) { + this._position = this._scene.activeCamera.position.clone(); + } + else { + this._position = new _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Vector3"](0, this._defaultHeight, 0); + } + // Set non-vr camera + if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) { + this._deviceOrientationCamera = new _Cameras_deviceOrientationCamera__WEBPACK_IMPORTED_MODULE_5__["DeviceOrientationCamera"]("deviceOrientationVRHelper", this._position.clone(), scene); + // Copy data from existing camera + if (this._scene.activeCamera) { + this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ; + this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ; + // Set rotation from previous camera + if (this._scene.activeCamera instanceof _Cameras_targetCamera__WEBPACK_IMPORTED_MODULE_4__["TargetCamera"] && this._scene.activeCamera.rotation) { + var targetCamera = this._scene.activeCamera; + if (targetCamera.rotationQuaternion) { + this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion); + } + else { + this._deviceOrientationCamera.rotationQuaternion.copyFrom(_Maths_math__WEBPACK_IMPORTED_MODULE_9__["Quaternion"].RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z)); + } + this._deviceOrientationCamera.rotation = targetCamera.rotation.clone(); + } + } + this._scene.activeCamera = this._deviceOrientationCamera; + if (this._canvas) { + this._scene.activeCamera.attachControl(this._canvas); + } + } + else { + this._existingCamera = this._scene.activeCamera; + } + // Create VR cameras + if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) { + if (webVROptions.useMultiview) { + if (!webVROptions.vrDeviceOrientationCameraMetrics) { + webVROptions.vrDeviceOrientationCameraMetrics = _Cameras_VR_vrCameraMetrics__WEBPACK_IMPORTED_MODULE_22__["VRCameraMetrics"].GetDefault(); + } + webVROptions.vrDeviceOrientationCameraMetrics.multiviewEnabled = true; + } + this._vrDeviceOrientationCamera = new _Cameras_VR_vrDeviceOrientationFreeCamera__WEBPACK_IMPORTED_MODULE_6__["VRDeviceOrientationFreeCamera"]("VRDeviceOrientationVRHelper", this._position, this._scene, true, webVROptions.vrDeviceOrientationCameraMetrics); + this._vrDeviceOrientationCamera.angularSensibility = Number.MAX_VALUE; + } + this._webVRCamera = new _Cameras_VR_webVRCamera__WEBPACK_IMPORTED_MODULE_7__["WebVRFreeCamera"]("WebVRHelper", this._position, this._scene, webVROptions); + this._webVRCamera.useStandingMatrix(); + this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene); + // Create default button + if (!this._useCustomVRButton) { + this._btnVR = document.createElement("BUTTON"); + this._btnVR.className = "babylonVRicon"; + this._btnVR.id = "babylonVRiconbtn"; + this._btnVR.title = "Click to switch to VR"; + var css = ".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url(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) }"; + css += ".babylonVRicon.vrdisplaypresenting { display: none; }"; + // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR) + // css += ".babylonVRicon.vrdisplaysupported { }"; + // css += ".babylonVRicon.vrdisplayready { }"; + // css += ".babylonVRicon.vrdisplayrequesting { }"; + var style = document.createElement('style'); + style.appendChild(document.createTextNode(css)); + document.getElementsByTagName('head')[0].appendChild(style); + this.moveButtonToBottomRight(); + } + // VR button click event + if (this._btnVR) { + this._btnVR.addEventListener("click", function () { + if (!_this.isInVRMode) { + _this.enterVR(); + } + else { + _this.exitVR(); + } + }); + } + // Window events + window.addEventListener("resize", this._onResize); + document.addEventListener("fullscreenchange", this._onFullscreenChange, false); + document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false); + document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false); + document.addEventListener("msfullscreenchange", this._onFullscreenChange, false); + document.onmsfullscreenchange = this._onFullscreenChange; + // Display vr button when headset is connected + if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) { + this.displayVRButton(); + } + else { + this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) { + if (e.vrDisplay) { + _this.displayVRButton(); + } + }); + } + // Exiting VR mode using 'ESC' key on desktop + this._onKeyDown = function (event) { + if (event.keyCode === 27 && _this.isInVRMode) { + _this.exitVR(); + } + }; + document.addEventListener("keydown", this._onKeyDown); + // Exiting VR mode double tapping the touch screen + this._scene.onPrePointerObservable.add(function () { + if (_this.isInVRMode) { + _this.exitVR(); + if (_this._fullscreenVRpresenting) { + _this._scene.getEngine().exitFullscreen(); + } + } + }, _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_8__["PointerEventTypes"].POINTERDOUBLETAP, false); + // Listen for WebVR display changes + this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); }; + this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); }; + this._onVRRequestPresentStart = function () { + _this._webVRrequesting = true; + _this.updateButtonVisibility(); + }; + this._onVRRequestPresentComplete = function () { + _this._webVRrequesting = false; + _this.updateButtonVisibility(); + }; + scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged); + scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart); + scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete); + window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange); + scene.onDisposeObservable.add(function () { + _this.dispose(); + }); + // Gamepad connection events + this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); }); + this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected); + this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected); + this.updateButtonVisibility(); + //create easing functions + this._circleEase = new _Animations_easing__WEBPACK_IMPORTED_MODULE_20__["CircleEase"](); + this._circleEase.setEasingMode(_Animations_easing__WEBPACK_IMPORTED_MODULE_20__["EasingFunction"].EASINGMODE_EASEINOUT); + // Allow clicking in the vrDeviceOrientationCamera + scene.onPointerObservable.add(function (e) { + if (_this._interactionsEnabled) { + if (scene.activeCamera === _this.vrDeviceOrientationCamera && e.event.pointerType === "mouse") { + if (e.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_8__["PointerEventTypes"].POINTERDOWN) { + _this._cameraGazer._selectionPointerDown(); + } + else if (e.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_8__["PointerEventTypes"].POINTERUP) { + _this._cameraGazer._selectionPointerUp(); + } + } + } + }); + if (this.webVROptions.floorMeshes) { + this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes }); + } + } + Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", { + /** Return this.onEnteringVRObservable + * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly + */ + get: function () { + return this.onEnteringVRObservable; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", { + /** Return this.onExitingVRObservable + * Note: This one is for backward compatibility. Please use onExitingVRObservable directly + */ + get: function () { + return this.onExitingVRObservable; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", { + /** Return this.onControllerMeshLoadedObservable + * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly + */ + get: function () { + return this.onControllerMeshLoadedObservable; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", { + /** + * The mesh used to display where the user is going to teleport. + */ + get: function () { + return this._teleportationTarget; + }, + /** + * Sets the mesh to be used to display where the user is going to teleport. + */ + set: function (value) { + if (value) { + value.name = "teleportationTarget"; + this._isDefaultTeleportationTarget = false; + this._teleportationTarget = value; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", { + /** + * The mesh used to display where the user is selecting, this mesh will be cloned and set as the gazeTracker for the left and right controller + * when set bakeCurrentTransformIntoVertices will be called on the mesh. + * See http://doc.babylonjs.com/resources/baking_transformations + */ + get: function () { + return this._cameraGazer._gazeTracker; + }, + set: function (value) { + if (value) { + // Dispose of existing meshes + if (this._cameraGazer._gazeTracker) { + this._cameraGazer._gazeTracker.dispose(); + } + if (this._leftController && this._leftController._gazeTracker) { + this._leftController._gazeTracker.dispose(); + } + if (this._rightController && this._rightController._gazeTracker) { + this._rightController._gazeTracker.dispose(); + } + // Set and create gaze trackers on head and controllers + this._cameraGazer._gazeTracker = value; + this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices(); + this._cameraGazer._gazeTracker.isPickable = false; + this._cameraGazer._gazeTracker.isVisible = false; + this._cameraGazer._gazeTracker.name = "gazeTracker"; + if (this._leftController) { + this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker"); + } + if (this._rightController) { + this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker"); + } + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", { + /** + * The gaze tracking mesh corresponding to the left controller + */ + get: function () { + if (this._leftController) { + return this._leftController._gazeTracker; + } + return null; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", { + /** + * The gaze tracking mesh corresponding to the right controller + */ + get: function () { + if (this._rightController) { + return this._rightController._gazeTracker; + } + return null; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", { + /** + * If the ray of the gaze should be displayed. + */ + get: function () { + return this._displayGaze; + }, + /** + * Sets if the ray of the gaze should be displayed. + */ + set: function (value) { + this._displayGaze = value; + if (!value) { + this._cameraGazer._gazeTracker.isVisible = false; + if (this._leftController) { + this._leftController._gazeTracker.isVisible = false; + } + if (this._rightController) { + this._rightController._gazeTracker.isVisible = false; + } + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", { + /** + * If the ray of the LaserPointer should be displayed. + */ + get: function () { + return this._displayLaserPointer; + }, + /** + * Sets if the ray of the LaserPointer should be displayed. + */ + set: function (value) { + this._displayLaserPointer = value; + if (!value) { + if (this._rightController) { + this._rightController._deactivatePointer(); + this._rightController._gazeTracker.isVisible = false; + } + if (this._leftController) { + this._leftController._deactivatePointer(); + this._leftController._gazeTracker.isVisible = false; + } + } + else { + if (this._rightController) { + this._rightController._activatePointer(); + } + if (this._leftController) { + this._leftController._activatePointer(); + } + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", { + /** + * The deviceOrientationCamera used as the camera when not in VR. + */ + get: function () { + return this._deviceOrientationCamera; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", { + /** + * Based on the current WebVR support, returns the current VR camera used. + */ + get: function () { + if (this._webVRready) { + return this._webVRCamera; + } + else { + return this._scene.activeCamera; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", { + /** + * The webVRCamera which is used when in VR. + */ + get: function () { + return this._webVRCamera; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", { + /** + * The deviceOrientationCamera that is used as a fallback when vr device is not connected. + */ + get: function () { + return this._vrDeviceOrientationCamera; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", { + get: function () { + var result = this._cameraGazer._teleportationRequestInitiated + || (this._leftController !== null && this._leftController._teleportationRequestInitiated) + || (this._rightController !== null && this._rightController._teleportationRequestInitiated); + return result; + }, + enumerable: true, + configurable: true + }); + // Raised when one of the controller has loaded successfully its associated default mesh + VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) { + if (this._leftController && this._leftController.webVRController == webVRController) { + if (webVRController.mesh) { + this._leftController._setLaserPointerParent(webVRController.mesh); + } + } + if (this._rightController && this._rightController.webVRController == webVRController) { + if (webVRController.mesh) { + this._rightController._setLaserPointerParent(webVRController.mesh); + } + } + try { + this.onControllerMeshLoadedObservable.notifyObservers(webVRController); + } + catch (err) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn("Error in your custom logic onControllerMeshLoaded: " + err); + } + }; + Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", { + /** + * Gets a value indicating if we are currently in VR mode. + */ + get: function () { + return this._webVRpresenting || this._fullscreenVRpresenting; + }, + enumerable: true, + configurable: true + }); + VRExperienceHelper.prototype.onVrDisplayPresentChange = function () { + var vrDisplay = this._scene.getEngine().getVRDevice(); + if (vrDisplay) { + var wasPresenting = this._webVRpresenting; + this._webVRpresenting = vrDisplay.isPresenting; + if (wasPresenting && !this._webVRpresenting) { + this.exitVR(); + } + } + else { + _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?'); + } + this.updateButtonVisibility(); + }; + VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) { + this._webVRsupported = eventArgs.vrSupported; + this._webVRready = !!eventArgs.vrDisplay; + this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting; + this.updateButtonVisibility(); + }; + VRExperienceHelper.prototype.moveButtonToBottomRight = function () { + if (this._canvas && !this._useCustomVRButton) { + this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px"; + this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px"; + } + }; + VRExperienceHelper.prototype.displayVRButton = function () { + if (!this._useCustomVRButton && !this._btnVRDisplayed) { + document.body.appendChild(this._btnVR); + this._btnVRDisplayed = true; + } + }; + VRExperienceHelper.prototype.updateButtonVisibility = function () { + if (!this._btnVR || this._useCustomVRButton) { + return; + } + this._btnVR.className = "babylonVRicon"; + if (this.isInVRMode) { + this._btnVR.className += " vrdisplaypresenting"; + } + else { + if (this._webVRready) { + this._btnVR.className += " vrdisplayready"; + } + if (this._webVRsupported) { + this._btnVR.className += " vrdisplaysupported"; + } + if (this._webVRrequesting) { + this._btnVR.className += " vrdisplayrequesting"; + } + } + }; + /** + * Attempt to enter VR. If a headset is connected and ready, will request present on that. + * Otherwise, will use the fullscreen API. + */ + VRExperienceHelper.prototype.enterVR = function () { + var _this = this; + if (this.onEnteringVRObservable) { + try { + this.onEnteringVRObservable.notifyObservers(this); + } + catch (err) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn("Error in your custom logic onEnteringVR: " + err); + } + } + if (this._scene.activeCamera) { + this._position = this._scene.activeCamera.position.clone(); + if (this.vrDeviceOrientationCamera) { + this.vrDeviceOrientationCamera.rotation = _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Quaternion"].FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles(); + this.vrDeviceOrientationCamera.angularSensibility = 2000; + } + if (this.webVRCamera) { + var currentYRotation = this.webVRCamera.deviceRotationQuaternion.toEulerAngles().y; + var desiredYRotation = _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Quaternion"].FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles().y; + var delta = desiredYRotation - currentYRotation; + var currentGlobalRotation = this.webVRCamera.rotationQuaternion.toEulerAngles().y; + this.webVRCamera.rotationQuaternion = _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Quaternion"].FromEulerAngles(0, currentGlobalRotation + delta, 0); + } + // make sure that we return to the last active camera + this._existingCamera = this._scene.activeCamera; + // Remove and cache angular sensability to avoid camera rotation when in VR + if (this._existingCamera.angularSensibilityX) { + this._cachedAngularSensibility.angularSensibilityX = this._existingCamera.angularSensibilityX; + this._existingCamera.angularSensibilityX = Number.MAX_VALUE; + } + if (this._existingCamera.angularSensibilityY) { + this._cachedAngularSensibility.angularSensibilityY = this._existingCamera.angularSensibilityY; + this._existingCamera.angularSensibilityY = Number.MAX_VALUE; + } + if (this._existingCamera.angularSensibility) { + this._cachedAngularSensibility.angularSensibility = this._existingCamera.angularSensibility; + this._existingCamera.angularSensibility = Number.MAX_VALUE; + } + } + if (this._webVRrequesting) { + return; + } + // If WebVR is supported and a headset is connected + if (this._webVRready) { + if (!this._webVRpresenting) { + this._scene.getEngine().onVRRequestPresentComplete.addOnce(function (result) { + _this.onAfterEnteringVRObservable.notifyObservers({ success: result }); + }); + this._webVRCamera.position = this._position; + this._scene.activeCamera = this._webVRCamera; + } + } + else if (this._vrDeviceOrientationCamera) { + this._vrDeviceOrientationCamera.position = this._position; + if (this._scene.activeCamera) { + this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ; + } + this._scene.activeCamera = this._vrDeviceOrientationCamera; + this._scene.getEngine().enterFullscreen(this.requestPointerLockOnFullScreen); + this.updateButtonVisibility(); + this._vrDeviceOrientationCamera.onViewMatrixChangedObservable.addOnce(function () { + _this.onAfterEnteringVRObservable.notifyObservers({ success: true }); + }); + } + if (this._scene.activeCamera && this._canvas) { + this._scene.activeCamera.attachControl(this._canvas); + } + if (this._interactionsEnabled) { + this._scene.registerBeforeRender(this.beforeRender); + } + if (this._displayLaserPointer) { + [this._leftController, this._rightController].forEach(function (controller) { + if (controller) { + controller._activatePointer(); + } + }); + } + this._hasEnteredVR = true; + }; + /** + * Attempt to exit VR, or fullscreen. + */ + VRExperienceHelper.prototype.exitVR = function () { + if (this._hasEnteredVR) { + if (this.onExitingVRObservable) { + try { + this.onExitingVRObservable.notifyObservers(this); + } + catch (err) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn("Error in your custom logic onExitingVR: " + err); + } + } + if (this._webVRpresenting) { + this._scene.getEngine().disableVR(); + } + if (this._scene.activeCamera) { + this._position = this._scene.activeCamera.position.clone(); + } + if (this.vrDeviceOrientationCamera) { + this.vrDeviceOrientationCamera.angularSensibility = Number.MAX_VALUE; + } + if (this._deviceOrientationCamera) { + this._deviceOrientationCamera.position = this._position; + this._scene.activeCamera = this._deviceOrientationCamera; + if (this._canvas) { + this._scene.activeCamera.attachControl(this._canvas); + } + // Restore angular sensibility + if (this._cachedAngularSensibility.angularSensibilityX) { + this._deviceOrientationCamera.angularSensibilityX = this._cachedAngularSensibility.angularSensibilityX; + this._cachedAngularSensibility.angularSensibilityX = null; + } + if (this._cachedAngularSensibility.angularSensibilityY) { + this._deviceOrientationCamera.angularSensibilityY = this._cachedAngularSensibility.angularSensibilityY; + this._cachedAngularSensibility.angularSensibilityY = null; + } + if (this._cachedAngularSensibility.angularSensibility) { + this._deviceOrientationCamera.angularSensibility = this._cachedAngularSensibility.angularSensibility; + this._cachedAngularSensibility.angularSensibility = null; + } + } + else if (this._existingCamera) { + this._existingCamera.position = this._position; + this._scene.activeCamera = this._existingCamera; + // Restore angular sensibility + if (this._cachedAngularSensibility.angularSensibilityX) { + this._existingCamera.angularSensibilityX = this._cachedAngularSensibility.angularSensibilityX; + this._cachedAngularSensibility.angularSensibilityX = null; + } + if (this._cachedAngularSensibility.angularSensibilityY) { + this._existingCamera.angularSensibilityY = this._cachedAngularSensibility.angularSensibilityY; + this._cachedAngularSensibility.angularSensibilityY = null; + } + if (this._cachedAngularSensibility.angularSensibility) { + this._existingCamera.angularSensibility = this._cachedAngularSensibility.angularSensibility; + this._cachedAngularSensibility.angularSensibility = null; + } + } + this.updateButtonVisibility(); + if (this._interactionsEnabled) { + this._scene.unregisterBeforeRender(this.beforeRender); + this._cameraGazer._gazeTracker.isVisible = false; + if (this._leftController) { + this._leftController._gazeTracker.isVisible = false; + } + if (this._rightController) { + this._rightController._gazeTracker.isVisible = false; + } + } + // resize to update width and height when exiting vr exits fullscreen + this._scene.getEngine().resize(); + [this._leftController, this._rightController].forEach(function (controller) { + if (controller) { + controller._deactivatePointer(); + } + }); + this._hasEnteredVR = false; + // Update engine state to re enable non-vr camera input + var engine = this._scene.getEngine(); + if (engine._onVrDisplayPresentChange) { + engine._onVrDisplayPresentChange(); + } + } + }; + Object.defineProperty(VRExperienceHelper.prototype, "position", { + /** + * The position of the vr experience helper. + */ + get: function () { + return this._position; + }, + /** + * Sets the position of the vr experience helper. + */ + set: function (value) { + this._position = value; + if (this._scene.activeCamera) { + this._scene.activeCamera.position = value; + } + }, + enumerable: true, + configurable: true + }); + /** + * Enables controllers and user interactions such as selecting and object or clicking on an object. + */ + VRExperienceHelper.prototype.enableInteractions = function () { + var _this = this; + if (!this._interactionsEnabled) { + this._interactionsRequested = true; + if (this._leftController) { + this._enableInteractionOnController(this._leftController); + } + if (this._rightController) { + this._enableInteractionOnController(this._rightController); + } + this.raySelectionPredicate = function (mesh) { + return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName); + }; + this.meshSelectionPredicate = function () { + return true; + }; + this._raySelectionPredicate = function (mesh) { + if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1 + && mesh.name.indexOf("teleportationTarget") === -1 + && mesh.name.indexOf("torusTeleportation") === -1)) { + return _this.raySelectionPredicate(mesh); + } + return false; + }; + this._interactionsEnabled = true; + } + }; + Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", { + get: function () { + return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer); + }, + enumerable: true, + configurable: true + }); + VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) { + for (var i = 0; i < this._floorMeshesCollection.length; i++) { + if (this._floorMeshesCollection[i].id === mesh.id) { + return true; + } + } + if (this._floorMeshName && mesh.name === this._floorMeshName) { + return true; + } + return false; + }; + /** + * Adds a floor mesh to be used for teleportation. + * @param floorMesh the mesh to be used for teleportation. + */ + VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) { + if (!this._floorMeshesCollection) { + return; + } + if (this._floorMeshesCollection.indexOf(floorMesh) > -1) { + return; + } + this._floorMeshesCollection.push(floorMesh); + }; + /** + * Removes a floor mesh from being used for teleportation. + * @param floorMesh the mesh to be removed. + */ + VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) { + if (!this._floorMeshesCollection) { + return; + } + var meshIndex = this._floorMeshesCollection.indexOf(floorMesh); + if (meshIndex !== -1) { + this._floorMeshesCollection.splice(meshIndex, 1); + } + }; + /** + * Enables interactions and teleportation using the VR controllers and gaze. + * @param vrTeleportationOptions options to modify teleportation behavior. + */ + VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) { + if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; } + if (!this._teleportationInitialized) { + this._teleportationRequested = true; + this.enableInteractions(); + if (vrTeleportationOptions.floorMeshName) { + this._floorMeshName = vrTeleportationOptions.floorMeshName; + } + if (vrTeleportationOptions.floorMeshes) { + this._floorMeshesCollection = vrTeleportationOptions.floorMeshes; + } + if (this._leftController != null) { + this._enableTeleportationOnController(this._leftController); + } + if (this._rightController != null) { + this._enableTeleportationOnController(this._rightController); + } + // Creates an image processing post process for the vignette not relying + // on the main scene configuration for image processing to reduce setup and spaces + // (gamma/linear) conflicts. + var imageProcessingConfiguration = new _Materials_imageProcessingConfiguration__WEBPACK_IMPORTED_MODULE_16__["ImageProcessingConfiguration"](); + imageProcessingConfiguration.vignetteColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Color4"](0, 0, 0, 0); + imageProcessingConfiguration.vignetteEnabled = true; + this._postProcessMove = new _PostProcesses_imageProcessingPostProcess__WEBPACK_IMPORTED_MODULE_19__["ImageProcessingPostProcess"]("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration); + this._webVRCamera.detachPostProcess(this._postProcessMove); + this._teleportationInitialized = true; + if (this._isDefaultTeleportationTarget) { + this._createTeleportationCircles(); + this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor); + } + } + }; + VRExperienceHelper.prototype._enableInteractionOnController = function (controller) { + var _this = this; + var controllerMesh = controller.webVRController.mesh; + if (controllerMesh) { + controller._interactionsEnabled = true; + if (this.isInVRMode && this._displayLaserPointer) { + controller._activatePointer(); + } + if (this.webVROptions.laserToggle) { + controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) { + // Enabling / disabling laserPointer + if (_this._displayLaserPointer && stateObject.value === 1) { + if (controller._activePointer) { + controller._deactivatePointer(); + } + else { + controller._activatePointer(); + } + if (_this.displayGaze) { + controller._gazeTracker.isVisible = controller._activePointer; + } + } + }); + } + controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) { + var gazer = controller; + if (_this._noControllerIsActive) { + gazer = _this._cameraGazer; + } + if (!gazer._pointerDownOnMeshAsked) { + if (stateObject.value > _this._padSensibilityUp) { + gazer._selectionPointerDown(); + } + } + else if (stateObject.value < _this._padSensibilityDown) { + gazer._selectionPointerUp(); + } + }); + } + }; + VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) { + // Dont teleport if another gaze already requested teleportation + if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) { + return; + } + if (!gazer._teleportationRequestInitiated) { + if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) { + gazer._activatePointer(); + gazer._teleportationRequestInitiated = true; + } + } + else { + // Listening to the proper controller values changes to confirm teleportation + if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) { + if (this._teleportActive) { + this.teleportCamera(this._haloCenter); + } + gazer._teleportationRequestInitiated = false; + } + } + }; + VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) { + // Only rotate when user is not currently selecting a teleportation location + if (gazer._teleportationRequestInitiated) { + return; + } + if (!gazer._rotationLeftAsked) { + if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) { + gazer._rotationLeftAsked = true; + if (this._rotationAllowed) { + this._rotateCamera(false); + } + } + } + else { + if (stateObject.x > -this._padSensibilityDown) { + gazer._rotationLeftAsked = false; + } + } + if (!gazer._rotationRightAsked) { + if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) { + gazer._rotationRightAsked = true; + if (this._rotationAllowed) { + this._rotateCamera(true); + } + } + } + else { + if (stateObject.x < this._padSensibilityDown) { + gazer._rotationRightAsked = false; + } + } + }; + VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) { + // Only teleport backwards when user is not currently selecting a teleportation location + if (gazer._teleportationRequestInitiated) { + return; + } + // Teleport backwards + if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) { + if (!gazer._teleportationBackRequestInitiated) { + if (!this.currentVRCamera) { + return; + } + // Get rotation and position of the current camera + var rotation = _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Quaternion"].FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix()); + var position = this.currentVRCamera.position; + // If the camera has device position, use that instead + if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) { + rotation = this.currentVRCamera.deviceRotationQuaternion; + position = this.currentVRCamera.devicePosition; + } + // Get matrix with only the y rotation of the device rotation + rotation.toEulerAnglesToRef(this._workingVector); + this._workingVector.z = 0; + this._workingVector.x = 0; + _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Quaternion"].RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion); + this._workingQuaternion.toRotationMatrix(this._workingMatrix); + // Rotate backwards ray by device rotation to cast at the ground behind the user + _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Vector3"].TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector); + // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff + var ray = new _Culling_ray__WEBPACK_IMPORTED_MODULE_15__["Ray"](position, this._workingVector); + var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate); + if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) { + this.teleportCamera(hit.pickedPoint); + } + gazer._teleportationBackRequestInitiated = true; + } + } + else { + gazer._teleportationBackRequestInitiated = false; + } + }; + VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) { + var _this = this; + var controllerMesh = controller.webVRController.mesh; + if (controllerMesh) { + if (!controller._interactionsEnabled) { + this._enableInteractionOnController(controller); + } + controller._interactionsEnabled = true; + controller._teleportationEnabled = true; + if (controller.webVRController.controllerType === _Gamepads_Controllers_poseEnabledController__WEBPACK_IMPORTED_MODULE_11__["PoseEnabledControllerType"].VIVE) { + controller._dpadPressed = false; + controller.webVRController.onPadStateChangedObservable.add(function (stateObject) { + controller._dpadPressed = stateObject.pressed; + if (!controller._dpadPressed) { + controller._rotationLeftAsked = false; + controller._rotationRightAsked = false; + controller._teleportationBackRequestInitiated = false; + } + }); + } + controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) { + if (_this.teleportationEnabled) { + _this._checkTeleportBackwards(stateObject, controller); + _this._checkTeleportWithRay(stateObject, controller); + } + _this._checkRotate(stateObject, controller); + }); + } + }; + VRExperienceHelper.prototype._createTeleportationCircles = function () { + this._teleportationTarget = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_14__["Mesh"].CreateGround("teleportationTarget", 2, 2, 2, this._scene); + this._teleportationTarget.isPickable = false; + var length = 512; + var dynamicTexture = new _Materials_Textures_dynamicTexture__WEBPACK_IMPORTED_MODULE_18__["DynamicTexture"]("DynamicTexture", length, this._scene, true); + dynamicTexture.hasAlpha = true; + var context = dynamicTexture.getContext(); + var centerX = length / 2; + var centerY = length / 2; + var radius = 200; + context.beginPath(); + context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false); + context.fillStyle = this._teleportationFillColor; + context.fill(); + context.lineWidth = 10; + context.strokeStyle = this._teleportationBorderColor; + context.stroke(); + context.closePath(); + dynamicTexture.update(); + var teleportationCircleMaterial = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_17__["StandardMaterial"]("TextPlaneMaterial", this._scene); + teleportationCircleMaterial.diffuseTexture = dynamicTexture; + this._teleportationTarget.material = teleportationCircleMaterial; + var torus = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_14__["Mesh"].CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false); + torus.isPickable = false; + torus.parent = this._teleportationTarget; + var animationInnerCircle = new _Animations_animation__WEBPACK_IMPORTED_MODULE_21__["Animation"]("animationInnerCircle", "position.y", 30, _Animations_animation__WEBPACK_IMPORTED_MODULE_21__["Animation"].ANIMATIONTYPE_FLOAT, _Animations_animation__WEBPACK_IMPORTED_MODULE_21__["Animation"].ANIMATIONLOOPMODE_CYCLE); + var keys = []; + keys.push({ + frame: 0, + value: 0 + }); + keys.push({ + frame: 30, + value: 0.4 + }); + keys.push({ + frame: 60, + value: 0 + }); + animationInnerCircle.setKeys(keys); + var easingFunction = new _Animations_easing__WEBPACK_IMPORTED_MODULE_20__["SineEase"](); + easingFunction.setEasingMode(_Animations_easing__WEBPACK_IMPORTED_MODULE_20__["EasingFunction"].EASINGMODE_EASEINOUT); + animationInnerCircle.setEasingFunction(easingFunction); + torus.animations = []; + torus.animations.push(animationInnerCircle); + this._scene.beginAnimation(torus, 0, 60, true); + this._hideTeleportationTarget(); + }; + VRExperienceHelper.prototype._displayTeleportationTarget = function () { + this._teleportActive = true; + if (this._teleportationInitialized) { + this._teleportationTarget.isVisible = true; + if (this._isDefaultTeleportationTarget) { + this._teleportationTarget.getChildren()[0].isVisible = true; + } + } + }; + VRExperienceHelper.prototype._hideTeleportationTarget = function () { + this._teleportActive = false; + if (this._teleportationInitialized) { + this._teleportationTarget.isVisible = false; + if (this._isDefaultTeleportationTarget) { + this._teleportationTarget.getChildren()[0].isVisible = false; + } + } + }; + VRExperienceHelper.prototype._rotateCamera = function (right) { + var _this = this; + if (!(this.currentVRCamera instanceof _Cameras_freeCamera__WEBPACK_IMPORTED_MODULE_3__["FreeCamera"])) { + return; + } + if (right) { + this._rotationAngle++; + } + else { + this._rotationAngle--; + } + this.currentVRCamera.animations = []; + var target = _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Quaternion"].FromRotationMatrix(_Maths_math__WEBPACK_IMPORTED_MODULE_9__["Matrix"].RotationY(Math.PI / 4 * this._rotationAngle)); + var animationRotation = new _Animations_animation__WEBPACK_IMPORTED_MODULE_21__["Animation"]("animationRotation", "rotationQuaternion", 90, _Animations_animation__WEBPACK_IMPORTED_MODULE_21__["Animation"].ANIMATIONTYPE_QUATERNION, _Animations_animation__WEBPACK_IMPORTED_MODULE_21__["Animation"].ANIMATIONLOOPMODE_CONSTANT); + var animationRotationKeys = []; + animationRotationKeys.push({ + frame: 0, + value: this.currentVRCamera.rotationQuaternion + }); + animationRotationKeys.push({ + frame: 6, + value: target + }); + animationRotation.setKeys(animationRotationKeys); + animationRotation.setEasingFunction(this._circleEase); + this.currentVRCamera.animations.push(animationRotation); + this._postProcessMove.animations = []; + var animationPP = new _Animations_animation__WEBPACK_IMPORTED_MODULE_21__["Animation"]("animationPP", "vignetteWeight", 90, _Animations_animation__WEBPACK_IMPORTED_MODULE_21__["Animation"].ANIMATIONTYPE_FLOAT, _Animations_animation__WEBPACK_IMPORTED_MODULE_21__["Animation"].ANIMATIONLOOPMODE_CONSTANT); + var vignetteWeightKeys = []; + vignetteWeightKeys.push({ + frame: 0, + value: 0 + }); + vignetteWeightKeys.push({ + frame: 3, + value: 4 + }); + vignetteWeightKeys.push({ + frame: 6, + value: 0 + }); + animationPP.setKeys(vignetteWeightKeys); + animationPP.setEasingFunction(this._circleEase); + this._postProcessMove.animations.push(animationPP); + var animationPP2 = new _Animations_animation__WEBPACK_IMPORTED_MODULE_21__["Animation"]("animationPP2", "vignetteStretch", 90, _Animations_animation__WEBPACK_IMPORTED_MODULE_21__["Animation"].ANIMATIONTYPE_FLOAT, _Animations_animation__WEBPACK_IMPORTED_MODULE_21__["Animation"].ANIMATIONLOOPMODE_CONSTANT); + var vignetteStretchKeys = []; + vignetteStretchKeys.push({ + frame: 0, + value: 0 + }); + vignetteStretchKeys.push({ + frame: 3, + value: 10 + }); + vignetteStretchKeys.push({ + frame: 6, + value: 0 + }); + animationPP2.setKeys(vignetteStretchKeys); + animationPP2.setEasingFunction(this._circleEase); + this._postProcessMove.animations.push(animationPP2); + this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0; + this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0; + this._postProcessMove.samples = 4; + this._webVRCamera.attachPostProcess(this._postProcessMove); + this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () { + _this._webVRCamera.detachPostProcess(_this._postProcessMove); + }); + this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1); + }; + VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) { + if (hit.pickedPoint) { + if (gazer._teleportationRequestInitiated) { + this._displayTeleportationTarget(); + this._haloCenter.copyFrom(hit.pickedPoint); + this._teleportationTarget.position.copyFrom(hit.pickedPoint); + } + var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray); + if (pickNormal) { + var axis1 = _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Vector3"].Cross(_Maths_math__WEBPACK_IMPORTED_MODULE_9__["Axis"].Y, pickNormal); + var axis2 = _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Vector3"].Cross(pickNormal, axis1); + _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Vector3"].RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation); + } + this._teleportationTarget.position.y += 0.1; + } + }; + /** + * Teleports the users feet to the desired location + * @param location The location where the user's feet should be placed + */ + VRExperienceHelper.prototype.teleportCamera = function (location) { + var _this = this; + if (!(this.currentVRCamera instanceof _Cameras_freeCamera__WEBPACK_IMPORTED_MODULE_3__["FreeCamera"])) { + return; + } + // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the + // offset of the headset from the anchor. + if (this.webVRCamera.leftCamera) { + this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition); + this._workingVector.subtractInPlace(this.webVRCamera.position); + location.subtractToRef(this._workingVector, this._workingVector); + } + else { + this._workingVector.copyFrom(location); + } + // Add height to account for user's height offset + if (this.isInVRMode) { + this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor; + } + else { + this._workingVector.y += this._defaultHeight; + } + this.onBeforeCameraTeleport.notifyObservers(this._workingVector); + // Create animation from the camera's position to the new location + this.currentVRCamera.animations = []; + var animationCameraTeleportation = new _Animations_animation__WEBPACK_IMPORTED_MODULE_21__["Animation"]("animationCameraTeleportation", "position", 90, _Animations_animation__WEBPACK_IMPORTED_MODULE_21__["Animation"].ANIMATIONTYPE_VECTOR3, _Animations_animation__WEBPACK_IMPORTED_MODULE_21__["Animation"].ANIMATIONLOOPMODE_CONSTANT); + var animationCameraTeleportationKeys = [{ + frame: 0, + value: this.currentVRCamera.position + }, + { + frame: 11, + value: this._workingVector + } + ]; + animationCameraTeleportation.setKeys(animationCameraTeleportationKeys); + animationCameraTeleportation.setEasingFunction(this._circleEase); + this.currentVRCamera.animations.push(animationCameraTeleportation); + this._postProcessMove.animations = []; + var animationPP = new _Animations_animation__WEBPACK_IMPORTED_MODULE_21__["Animation"]("animationPP", "vignetteWeight", 90, _Animations_animation__WEBPACK_IMPORTED_MODULE_21__["Animation"].ANIMATIONTYPE_FLOAT, _Animations_animation__WEBPACK_IMPORTED_MODULE_21__["Animation"].ANIMATIONLOOPMODE_CONSTANT); + var vignetteWeightKeys = []; + vignetteWeightKeys.push({ + frame: 0, + value: 0 + }); + vignetteWeightKeys.push({ + frame: 5, + value: 8 + }); + vignetteWeightKeys.push({ + frame: 11, + value: 0 + }); + animationPP.setKeys(vignetteWeightKeys); + this._postProcessMove.animations.push(animationPP); + var animationPP2 = new _Animations_animation__WEBPACK_IMPORTED_MODULE_21__["Animation"]("animationPP2", "vignetteStretch", 90, _Animations_animation__WEBPACK_IMPORTED_MODULE_21__["Animation"].ANIMATIONTYPE_FLOAT, _Animations_animation__WEBPACK_IMPORTED_MODULE_21__["Animation"].ANIMATIONLOOPMODE_CONSTANT); + var vignetteStretchKeys = []; + vignetteStretchKeys.push({ + frame: 0, + value: 0 + }); + vignetteStretchKeys.push({ + frame: 5, + value: 10 + }); + vignetteStretchKeys.push({ + frame: 11, + value: 0 + }); + animationPP2.setKeys(vignetteStretchKeys); + this._postProcessMove.animations.push(animationPP2); + this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0; + this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0; + this._webVRCamera.attachPostProcess(this._postProcessMove); + this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () { + _this._webVRCamera.detachPostProcess(_this._postProcessMove); + }); + this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () { + _this.onAfterCameraTeleport.notifyObservers(_this._workingVector); + }); + this._hideTeleportationTarget(); + }; + VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) { + if (normal) { + var angle = Math.acos(_Maths_math__WEBPACK_IMPORTED_MODULE_9__["Vector3"].Dot(normal, ray.direction)); + if (angle < Math.PI / 2) { + normal.scaleInPlace(-1); + } + } + return normal; + }; + VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) { + if (!(this.currentVRCamera instanceof _Cameras_freeCamera__WEBPACK_IMPORTED_MODULE_3__["FreeCamera"])) { + return; + } + var ray = gazer._getForwardRay(this._rayLength); + var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate); + if (hit) { + // Populate the contrllers mesh that can be used for drag/drop + if (gazer._laserPointer) { + hit.originMesh = gazer._laserPointer.parent; + } + this._scene.simulatePointerMove(hit, { pointerId: gazer._id }); + } + gazer._currentHit = hit; + // Moving the gazeTracker on the mesh face targetted + if (hit && hit.pickedPoint) { + if (this._displayGaze) { + var multiplier = 1; + gazer._gazeTracker.isVisible = true; + if (gazer._isActionableMesh) { + multiplier = 3; + } + if (this.updateGazeTrackerScale) { + gazer._gazeTracker.scaling.x = hit.distance * multiplier; + gazer._gazeTracker.scaling.y = hit.distance * multiplier; + gazer._gazeTracker.scaling.z = hit.distance * multiplier; + } + var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray); + // To avoid z-fighting + var deltaFighting = 0.002; + if (pickNormal) { + var axis1 = _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Vector3"].Cross(_Maths_math__WEBPACK_IMPORTED_MODULE_9__["Axis"].Y, pickNormal); + var axis2 = _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Vector3"].Cross(pickNormal, axis1); + _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Vector3"].RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation); + } + gazer._gazeTracker.position.copyFrom(hit.pickedPoint); + if (gazer._gazeTracker.position.x < 0) { + gazer._gazeTracker.position.x += deltaFighting; + } + else { + gazer._gazeTracker.position.x -= deltaFighting; + } + if (gazer._gazeTracker.position.y < 0) { + gazer._gazeTracker.position.y += deltaFighting; + } + else { + gazer._gazeTracker.position.y -= deltaFighting; + } + if (gazer._gazeTracker.position.z < 0) { + gazer._gazeTracker.position.z += deltaFighting; + } + else { + gazer._gazeTracker.position.z -= deltaFighting; + } + } + // Changing the size of the laser pointer based on the distance from the targetted point + gazer._updatePointerDistance(hit.distance); + } + else { + gazer._updatePointerDistance(); + gazer._gazeTracker.isVisible = false; + } + if (hit && hit.pickedMesh) { + // The object selected is the floor, we're in a teleportation scenario + if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) { + // Moving the teleportation area to this targetted point + //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected + if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) { + this._notifySelectedMeshUnselected(gazer._currentMeshSelected); + } + gazer._currentMeshSelected = null; + if (gazer._teleportationRequestInitiated) { + this._moveTeleportationSelectorTo(hit, gazer, ray); + } + return; + } + // If not, we're in a selection scenario + //this._teleportationAllowed = false; + if (hit.pickedMesh !== gazer._currentMeshSelected) { + if (this.meshSelectionPredicate(hit.pickedMesh)) { + this.onNewMeshPicked.notifyObservers(hit); + gazer._currentMeshSelected = hit.pickedMesh; + if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) { + this.changeGazeColor(new _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Color3"](0, 0, 1)); + this.changeLaserColor(new _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Color3"](0.2, 0.2, 1)); + gazer._isActionableMesh = true; + } + else { + this.changeGazeColor(new _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Color3"](0.7, 0.7, 0.7)); + this.changeLaserColor(new _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Color3"](0.7, 0.7, 0.7)); + gazer._isActionableMesh = false; + } + try { + this.onNewMeshSelected.notifyObservers(hit.pickedMesh); + } + catch (err) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn("Error in your custom logic onNewMeshSelected: " + err); + } + } + else { + this._notifySelectedMeshUnselected(gazer._currentMeshSelected); + gazer._currentMeshSelected = null; + this.changeGazeColor(new _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Color3"](0.7, 0.7, 0.7)); + this.changeLaserColor(new _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Color3"](0.7, 0.7, 0.7)); + } + } + } + else { + this._notifySelectedMeshUnselected(gazer._currentMeshSelected); + gazer._currentMeshSelected = null; + //this._teleportationAllowed = false; + this.changeGazeColor(new _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Color3"](0.7, 0.7, 0.7)); + this.changeLaserColor(new _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Color3"](0.7, 0.7, 0.7)); + } + }; + VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) { + if (mesh) { + this.onSelectedMeshUnselected.notifyObservers(mesh); + } + }; + /** + * Sets the color of the laser ray from the vr controllers. + * @param color new color for the ray. + */ + VRExperienceHelper.prototype.changeLaserColor = function (color) { + if (this._leftController) { + this._leftController._setLaserPointerColor(color); + } + if (this._rightController) { + this._rightController._setLaserPointerColor(color); + } + }; + /** + * Sets the color of the ray from the vr headsets gaze. + * @param color new color for the ray. + */ + VRExperienceHelper.prototype.changeGazeColor = function (color) { + if (!this.updateGazeTrackerColor) { + return; + } + if (!this._cameraGazer._gazeTracker.material) { + return; + } + this._cameraGazer._gazeTracker.material.emissiveColor = color; + if (this._leftController) { + this._leftController._gazeTracker.material.emissiveColor = color; + } + if (this._rightController) { + this._rightController._gazeTracker.material.emissiveColor = color; + } + }; + /** + * Exits VR and disposes of the vr experience helper + */ + VRExperienceHelper.prototype.dispose = function () { + if (this.isInVRMode) { + this.exitVR(); + } + if (this._postProcessMove) { + this._postProcessMove.dispose(); + } + if (this._webVRCamera) { + this._webVRCamera.dispose(); + } + if (this._vrDeviceOrientationCamera) { + this._vrDeviceOrientationCamera.dispose(); + } + if (!this._useCustomVRButton && this._btnVR.parentNode) { + document.body.removeChild(this._btnVR); + } + if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) { + this._deviceOrientationCamera.dispose(); + } + if (this._cameraGazer) { + this._cameraGazer.dispose(); + } + if (this._leftController) { + this._leftController.dispose(); + } + if (this._rightController) { + this._rightController.dispose(); + } + if (this._teleportationTarget) { + this._teleportationTarget.dispose(); + } + this._floorMeshesCollection = []; + document.removeEventListener("keydown", this._onKeyDown); + window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange); + window.removeEventListener("resize", this._onResize); + document.removeEventListener("fullscreenchange", this._onFullscreenChange); + document.removeEventListener("mozfullscreenchange", this._onFullscreenChange); + document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange); + document.removeEventListener("msfullscreenchange", this._onFullscreenChange); + document.onmsfullscreenchange = null; + this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged); + this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart); + this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete); + window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange); + this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected); + this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected); + this._scene.unregisterBeforeRender(this.beforeRender); + }; + /** + * Gets the name of the VRExperienceHelper class + * @returns "VRExperienceHelper" + */ + VRExperienceHelper.prototype.getClassName = function () { + return "VRExperienceHelper"; + }; + return VRExperienceHelper; +}()); + + + +/***/ }), + +/***/ "./Cameras/VR/webVRCamera.ts": +/*!***********************************!*\ + !*** ./Cameras/VR/webVRCamera.ts ***! + \***********************************/ +/*! exports provided: WebVRFreeCamera */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WebVRFreeCamera", function() { return WebVRFreeCamera; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _Cameras_freeCamera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/freeCamera */ "./Cameras/freeCamera.ts"); +/* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Cameras/camera */ "./Cameras/camera.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Gamepads/gamepad */ "./Gamepads/gamepad.ts"); +/* harmony import */ var _Gamepads_Controllers_poseEnabledController__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../Gamepads/Controllers/poseEnabledController */ "./Gamepads/Controllers/poseEnabledController.ts"); +/* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../node */ "./node.ts"); +/* harmony import */ var _Lights_hemisphericLight__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../Lights/hemisphericLight */ "./Lights/hemisphericLight.ts"); +/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../../Misc/logger */ "./Misc/logger.ts"); +/* harmony import */ var _PostProcesses_vrMultiviewToSingleviewPostProcess__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../../PostProcesses/vrMultiviewToSingleviewPostProcess */ "./PostProcesses/vrMultiviewToSingleviewPostProcess.ts"); +/* harmony import */ var _RigModes_webVRRigMode__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../RigModes/webVRRigMode */ "./Cameras/RigModes/webVRRigMode.ts"); +/* harmony import */ var _Engines_Extensions_engine_webVR__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../../Engines/Extensions/engine.webVR */ "./Engines/Extensions/engine.webVR.ts"); + + + + + + + + + + + +// Side effect import to define the stereoscopic mode. + +// Side effect import to add webvr support to engine + +_node__WEBPACK_IMPORTED_MODULE_7__["Node"].AddNodeConstructor("WebVRFreeCamera", function (name, scene) { + return function () { return new WebVRFreeCamera(name, _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"].Zero(), scene); }; +}); +_node__WEBPACK_IMPORTED_MODULE_7__["Node"].AddNodeConstructor("WebVRGamepadCamera", function (name, scene) { + return function () { return new WebVRFreeCamera(name, _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"].Zero(), scene); }; +}); +/** + * This represents a WebVR camera. + * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift. + * @example http://doc.babylonjs.com/how_to/webvr_camera + */ +var WebVRFreeCamera = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](WebVRFreeCamera, _super); + /** + * Instantiates a WebVRFreeCamera. + * @param name The name of the WebVRFreeCamera + * @param position The starting anchor position for the camera + * @param scene The scene the camera belongs to + * @param webVROptions a set of customizable options for the webVRCamera + */ + function WebVRFreeCamera(name, position, scene, webVROptions) { + if (webVROptions === void 0) { webVROptions = {}; } + var _this = _super.call(this, name, position, scene) || this; + _this.webVROptions = webVROptions; + /** + * @hidden + * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay + */ + _this._vrDevice = null; + /** + * The rawPose of the vrDevice. + */ + _this.rawPose = null; + _this._specsVersion = "1.1"; + _this._attached = false; + _this._descendants = []; + // Represents device position and rotation in room space. Should only be used to help calculate babylon space values + _this._deviceRoomPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"].Zero(); + /** @hidden */ + _this._deviceRoomRotationQuaternion = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Quaternion"].Identity(); + _this._standingMatrix = null; + /** + * Represents device position in babylon space. + */ + _this.devicePosition = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"].Zero(); + /** + * Represents device rotation in babylon space. + */ + _this.deviceRotationQuaternion = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Quaternion"].Identity(); + /** + * The scale of the device to be used when translating from device space to babylon space. + */ + _this.deviceScaleFactor = 1; + _this._deviceToWorld = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"].Identity(); + _this._worldToDevice = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"].Identity(); + /** + * References to the webVR controllers for the vrDevice. + */ + _this.controllers = []; + /** + * Emits an event when a controller is attached. + */ + _this.onControllersAttachedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + /** + * Emits an event when a controller's mesh has been loaded; + */ + _this.onControllerMeshLoadedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + /** + * Emits an event when the HMD's pose has been updated. + */ + _this.onPoseUpdatedFromDeviceObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + _this._poseSet = false; + /** + * If the rig cameras be used as parent instead of this camera. + */ + _this.rigParenting = true; + _this._defaultHeight = undefined; + _this._htmlElementAttached = null; + _this._detachIfAttached = function () { + var vrDisplay = _this.getEngine().getVRDevice(); + if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) { + _this.detachControl(_this._htmlElementAttached); + } + }; + _this._workingVector = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"].Zero(); + _this._oneVector = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"].One(); + _this._workingMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"].Identity(); + _this._tmpMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"](); + _this._cache.position = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"].Zero(); + if (webVROptions.defaultHeight) { + _this._defaultHeight = webVROptions.defaultHeight; + _this.position.y = _this._defaultHeight; + } + _this.minZ = 0.1; + //legacy support - the compensation boolean was removed. + if (arguments.length === 5) { + _this.webVROptions = arguments[4]; + } + // default webVR options + if (_this.webVROptions.trackPosition == undefined) { + _this.webVROptions.trackPosition = true; + } + if (_this.webVROptions.controllerMeshes == undefined) { + _this.webVROptions.controllerMeshes = true; + } + if (_this.webVROptions.defaultLightingOnControllers == undefined) { + _this.webVROptions.defaultLightingOnControllers = true; + } + _this.rotationQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Quaternion"](); + if (_this.webVROptions && _this.webVROptions.positionScale) { + _this.deviceScaleFactor = _this.webVROptions.positionScale; + } + //enable VR + var engine = _this.getEngine(); + _this._onVREnabled = function (success) { if (success) { + _this.initControllers(); + } }; + engine.onVRRequestPresentComplete.add(_this._onVREnabled); + engine.initWebVR().add(function (event) { + if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) { + return; + } + _this._vrDevice = event.vrDisplay; + //reset the rig parameters. + _this.setCameraRigMode(_Cameras_camera__WEBPACK_IMPORTED_MODULE_3__["Camera"].RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion }); + if (_this._attached) { + _this.getEngine().enableVR(); + } + }); + if (typeof (VRFrameData) !== "undefined") { + _this._frameData = new VRFrameData(); + } + if (webVROptions.useMultiview) { + if (!_this.getScene().getEngine().getCaps().multiview) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_9__["Logger"].Warn("Multiview is not supported, falling back to standard rendering"); + _this._useMultiviewToSingleView = false; + } + else { + _this._useMultiviewToSingleView = true; + _this._rigPostProcess = new _PostProcesses_vrMultiviewToSingleviewPostProcess__WEBPACK_IMPORTED_MODULE_10__["VRMultiviewToSingleviewPostProcess"]("VRMultiviewToSingleview", _this, 1.0); + } + } + /** + * The idea behind the following lines: + * objects that have the camera as parent should actually have the rig cameras as a parent. + * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera, + * the second will not show it correctly. + * + * To solve this - each object that has the camera as parent will be added to a protected array. + * When the rig camera renders, it will take this array and set all of those to be its children. + * This way, the right camera will be used as a parent, and the mesh will be rendered correctly. + * Amazing! + */ + scene.onBeforeCameraRenderObservable.add(function (camera) { + if (camera.parent === _this && _this.rigParenting) { + _this._descendants = _this.getDescendants(true, function (n) { + // don't take the cameras or the controllers! + var isController = _this.controllers.some(function (controller) { return controller._mesh === n; }); + var isRigCamera = _this._rigCameras.indexOf(n) !== -1; + return !isController && !isRigCamera; + }); + _this._descendants.forEach(function (node) { + node.parent = camera; + }); + } + }); + scene.onAfterCameraRenderObservable.add(function (camera) { + if (camera.parent === _this && _this.rigParenting) { + _this._descendants.forEach(function (node) { + node.parent = _this; + }); + } + }); + return _this; + } + /** + * Gets the device distance from the ground in meters. + * @returns the distance in meters from the vrDevice to ground in device space. If standing matrix is not supported for the vrDevice 0 is returned. + */ + WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () { + if (this._standingMatrix) { + // Add standing matrix offset to get real offset from ground in room + this._standingMatrix.getTranslationToRef(this._workingVector); + return this._deviceRoomPosition.y + this._workingVector.y; + } + //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero. + return this._defaultHeight || 0; + }; + /** + * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground. + * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported. + */ + WebVRFreeCamera.prototype.useStandingMatrix = function (callback) { + var _this = this; + if (callback === void 0) { callback = function (bool) { }; } + // Use standing matrix if available + this.getEngine().initWebVRAsync().then(function (result) { + if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform || !_this.webVROptions.trackPosition) { + callback(false); + } + else { + _this._standingMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"](); + _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"].FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix); + if (!_this.getScene().useRightHandedSystem) { + if (_this._standingMatrix) { + _this._standingMatrix.toggleModelMatrixHandInPlace(); + } + } + callback(true); + } + }); + }; + /** + * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground. + * @returns A promise with a boolean set to if the standing matrix is supported. + */ + WebVRFreeCamera.prototype.useStandingMatrixAsync = function () { + var _this = this; + return new Promise(function (res) { + _this.useStandingMatrix(function (supported) { + res(supported); + }); + }); + }; + /** + * Disposes the camera + */ + WebVRFreeCamera.prototype.dispose = function () { + this._detachIfAttached(); + this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled); + if (this._updateCacheWhenTrackingDisabledObserver) { + this._scene.onBeforeRenderObservable.remove(this._updateCacheWhenTrackingDisabledObserver); + } + _super.prototype.dispose.call(this); + }; + /** + * Gets a vrController by name. + * @param name The name of the controller to retreive + * @returns the controller matching the name specified or null if not found + */ + WebVRFreeCamera.prototype.getControllerByName = function (name) { + for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) { + var gp = _a[_i]; + if (gp.hand === name) { + return gp; + } + } + return null; + }; + Object.defineProperty(WebVRFreeCamera.prototype, "leftController", { + /** + * The controller corrisponding to the users left hand. + */ + get: function () { + if (!this._leftController) { + this._leftController = this.getControllerByName("left"); + } + return this._leftController; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(WebVRFreeCamera.prototype, "rightController", { + /** + * The controller corrisponding to the users right hand. + */ + get: function () { + if (!this._rightController) { + this._rightController = this.getControllerByName("right"); + } + return this._rightController; + }, + enumerable: true, + configurable: true + }); + /** + * Casts a ray forward from the vrCamera's gaze. + * @param length Length of the ray (default: 100) + * @returns the ray corrisponding to the gaze + */ + WebVRFreeCamera.prototype.getForwardRay = function (length) { + if (length === void 0) { length = 100; } + if (this.leftCamera) { + // Use left eye to avoid computation to compute center on every call + return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera + } + else { + return _super.prototype.getForwardRay.call(this, length); + } + }; + /** + * @hidden + * Updates the camera based on device's frame data + */ + WebVRFreeCamera.prototype._checkInputs = function () { + if (this._vrDevice && this._vrDevice.isPresenting) { + this._vrDevice.getFrameData(this._frameData); + this.updateFromDevice(this._frameData.pose); + } + _super.prototype._checkInputs.call(this); + }; + /** + * Updates the poseControlled values based on the input device pose. + * @param poseData Pose coming from the device + */ + WebVRFreeCamera.prototype.updateFromDevice = function (poseData) { + if (poseData && poseData.orientation) { + this.rawPose = poseData; + this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]); + if (this.getScene().useRightHandedSystem) { + this._deviceRoomRotationQuaternion.z *= -1; + this._deviceRoomRotationQuaternion.w *= -1; + } + if (this.webVROptions.trackPosition && this.rawPose.position) { + this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]); + if (this.getScene().useRightHandedSystem) { + this._deviceRoomPosition.z *= -1; + } + } + this._poseSet = true; + } + }; + /** + * WebVR's attach control will start broadcasting frames to the device. + * Note that in certain browsers (chrome for example) this function must be called + * within a user-interaction callback. Example: + *
 scene.onPointerDown = function() { camera.attachControl(canvas); }
+ * + * @param element html element to attach the vrDevice to + * @param noPreventDefault prevent the default html element operation when attaching the vrDevice + */ + WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) { + _super.prototype.attachControl.call(this, element, noPreventDefault); + this._attached = true; + this._htmlElementAttached = element; + noPreventDefault = _Cameras_camera__WEBPACK_IMPORTED_MODULE_3__["Camera"].ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault; + if (this._vrDevice) { + this.getEngine().enableVR(); + } + window.addEventListener('vrdisplaypresentchange', this._detachIfAttached); + }; + /** + * Detaches the camera from the html element and disables VR + * + * @param element html element to detach from + */ + WebVRFreeCamera.prototype.detachControl = function (element) { + this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver); + this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver); + _super.prototype.detachControl.call(this, element); + this._attached = false; + this.getEngine().disableVR(); + window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached); + }; + /** + * @returns the name of this class + */ + WebVRFreeCamera.prototype.getClassName = function () { + return "WebVRFreeCamera"; + }; + /** + * Calls resetPose on the vrDisplay + * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose + */ + WebVRFreeCamera.prototype.resetToCurrentRotation = function () { + //uses the vrDisplay's "resetPose()". + //pitch and roll won't be affected. + this._vrDevice.resetPose(); + }; + /** + * @hidden + * Updates the rig cameras (left and right eye) + */ + WebVRFreeCamera.prototype._updateRigCameras = function () { + var camLeft = this._rigCameras[0]; + var camRight = this._rigCameras[1]; + camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion); + camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion); + camLeft.position.copyFrom(this._deviceRoomPosition); + camRight.position.copyFrom(this._deviceRoomPosition); + }; + // Remove translation from 6dof headset if trackposition is set to false + WebVRFreeCamera.prototype._correctPositionIfNotTrackPosition = function (matrix, isViewMatrix) { + if (isViewMatrix === void 0) { isViewMatrix = false; } + if (this.rawPose && this.rawPose.position && !this.webVROptions.trackPosition) { + _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"].TranslationToRef(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2], this._tmpMatrix); + if (!isViewMatrix) { + this._tmpMatrix.invert(); + } + this._tmpMatrix.multiplyToRef(matrix, matrix); + } + }; + /** + * @hidden + * Updates the cached values of the camera + * @param ignoreParentClass ignores updating the parent class's cache (default: false) + */ + WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) { + var _this = this; + if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) { + // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition + if (!this.updateCacheCalled) { + // make sure it is only called once per loop. this.update() might cause an infinite loop. + this.updateCacheCalled = true; + this.update(); + } + // Set working vector to the device position in room space rotated by the new rotation + this.rotationQuaternion.toRotationMatrix(this._workingMatrix); + _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"].TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector); + // Subtract this vector from the current device position in world to get the translation for the device world matrix + this.devicePosition.subtractToRef(this._workingVector, this._workingVector); + _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"].ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld); + // Add translation from anchor position + this._deviceToWorld.getTranslationToRef(this._workingVector); + this._workingVector.addInPlace(this.position); + this._workingVector.subtractInPlace(this._cache.position); + this._deviceToWorld.setTranslation(this._workingVector); + // Set an inverted matrix to be used when updating the camera + this._deviceToWorld.invertToRef(this._worldToDevice); + // Update the gamepad to ensure the mesh is updated on the same frame as camera + this.controllers.forEach(function (controller) { + controller._deviceToWorld.copyFrom(_this._deviceToWorld); + _this._correctPositionIfNotTrackPosition(controller._deviceToWorld); + controller.update(); + }); + } + if (!ignoreParentClass) { + _super.prototype._updateCache.call(this); + } + this.updateCacheCalled = false; + }; + /** + * @hidden + * Get current device position in babylon world + */ + WebVRFreeCamera.prototype._computeDevicePosition = function () { + _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"].TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition); + }; + /** + * Updates the current device position and rotation in the babylon world + */ + WebVRFreeCamera.prototype.update = function () { + this._computeDevicePosition(); + // Get current device rotation in babylon world + _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"].FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix); + this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix); + _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Quaternion"].FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion); + if (this._poseSet) { + this.onPoseUpdatedFromDeviceObservable.notifyObservers(null); + } + _super.prototype.update.call(this); + }; + /** + * @hidden + * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix) + * @returns an identity matrix + */ + WebVRFreeCamera.prototype._getViewMatrix = function () { + return _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"].Identity(); + }; + /** + * This function is called by the two RIG cameras. + * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance) + * @hidden + */ + WebVRFreeCamera.prototype._getWebVRViewMatrix = function () { + // Update the parent camera prior to using a child camera to avoid desynchronization + var parentCamera = this._cameraRigParams["parentCamera"]; + parentCamera._updateCache(); + //WebVR 1.1 + var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix; + _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"].FromArrayToRef(viewArray, 0, this._webvrViewMatrix); + if (!this.getScene().useRightHandedSystem) { + this._webvrViewMatrix.toggleModelMatrixHandInPlace(); + } + // update the camera rotation matrix + this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix); + _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"].TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint); + // Computing target and final matrix + this.position.addToRef(this._transformedReferencePoint, this._currentTarget); + // should the view matrix be updated with scale and position offset? + if (parentCamera.deviceScaleFactor !== 1) { + this._webvrViewMatrix.invert(); + // scale the position, if set + if (parentCamera.deviceScaleFactor) { + this._webvrViewMatrix.multiplyAtIndex(12, parentCamera.deviceScaleFactor); + this._webvrViewMatrix.multiplyAtIndex(13, parentCamera.deviceScaleFactor); + this._webvrViewMatrix.multiplyAtIndex(14, parentCamera.deviceScaleFactor); + } + this._webvrViewMatrix.invert(); + } + // Remove translation from 6dof headset if trackposition is set to false + parentCamera._correctPositionIfNotTrackPosition(this._webvrViewMatrix, true); + parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix); + // Compute global position + this._workingMatrix = this._workingMatrix || _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"].Identity(); + this._webvrViewMatrix.invertToRef(this._workingMatrix); + this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix); + this._workingMatrix.getTranslationToRef(this._globalPosition); + this._markSyncedWithParent(); + return this._webvrViewMatrix; + }; + /** @hidden */ + WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () { + var parentCamera = this.parent; + parentCamera._vrDevice.depthNear = parentCamera.minZ; + parentCamera._vrDevice.depthFar = parentCamera.maxZ; + var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix; + _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"].FromArrayToRef(projectionArray, 0, this._projectionMatrix); + //babylon compatible matrix + if (!this.getScene().useRightHandedSystem) { + this._projectionMatrix.toggleProjectionMatrixHandInPlace(); + } + return this._projectionMatrix; + }; + /** + * Initializes the controllers and their meshes + */ + WebVRFreeCamera.prototype.initControllers = function () { + var _this = this; + this.controllers = []; + var manager = this.getScene().gamepadManager; + this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) { + if (gamepad.type === _Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_5__["Gamepad"].POSE_ENABLED) { + var webVrController = gamepad; + if (webVrController.defaultModel) { + webVrController.defaultModel.setEnabled(false); + } + if (webVrController.hand === "right") { + _this._rightController = null; + } + if (webVrController.hand === "left") { + _this._leftController = null; + } + var controllerIndex = _this.controllers.indexOf(webVrController); + if (controllerIndex !== -1) { + _this.controllers.splice(controllerIndex, 1); + } + } + }); + this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) { + if (gamepad.type === _Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_5__["Gamepad"].POSE_ENABLED) { + var webVrController_1 = gamepad; + if (!_this.webVROptions.trackPosition) { + webVrController_1._disableTrackPosition(new _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"](webVrController_1.hand == "left" ? -0.15 : 0.15, -0.5, 0.25)); + // Cache must be updated before rendering controllers to avoid them being one frame behind + if (!_this._updateCacheWhenTrackingDisabledObserver) { + _this._updateCacheWhenTrackingDisabledObserver = _this._scene.onBeforeRenderObservable.add(function () { + _this._updateCache(); + }); + } + } + webVrController_1.deviceScaleFactor = _this.deviceScaleFactor; + webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld); + _this._correctPositionIfNotTrackPosition(webVrController_1._deviceToWorld); + if (_this.webVROptions.controllerMeshes) { + if (webVrController_1.defaultModel) { + webVrController_1.defaultModel.setEnabled(true); + } + else { + // Load the meshes + webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) { + loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor); + _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1); + if (_this.webVROptions.defaultLightingOnControllers) { + if (!_this._lightOnControllers) { + _this._lightOnControllers = new _Lights_hemisphericLight__WEBPACK_IMPORTED_MODULE_8__["HemisphericLight"]("vrControllersLight", new _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"](0, 1, 0), _this.getScene()); + } + var activateLightOnSubMeshes_1 = function (mesh, light) { + var children = mesh.getChildren(); + if (children && children.length !== 0) { + children.forEach(function (mesh) { + light.includedOnlyMeshes.push(mesh); + activateLightOnSubMeshes_1(mesh, light); + }); + } + }; + _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh); + activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers); + } + }); + } + } + webVrController_1.attachToPoseControlledCamera(_this); + // since this is async - sanity check. Is the controller already stored? + if (_this.controllers.indexOf(webVrController_1) === -1) { + //add to the controllers array + _this.controllers.push(webVrController_1); + // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property + // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them... + // So we're overriding setting left & right manually to be sure + var firstViveWandDetected = false; + for (var i = 0; i < _this.controllers.length; i++) { + if (_this.controllers[i].controllerType === _Gamepads_Controllers_poseEnabledController__WEBPACK_IMPORTED_MODULE_6__["PoseEnabledControllerType"].VIVE) { + if (!firstViveWandDetected) { + firstViveWandDetected = true; + _this.controllers[i].hand = "left"; + } + else { + _this.controllers[i].hand = "right"; + } + } + } + //did we find enough controllers? Great! let the developer know. + if (_this.controllers.length >= 2) { + _this.onControllersAttachedObservable.notifyObservers(_this.controllers); + } + } + } + }); + }; + return WebVRFreeCamera; +}(_Cameras_freeCamera__WEBPACK_IMPORTED_MODULE_2__["FreeCamera"])); + + + +/***/ }), + +/***/ "./Cameras/XR/index.ts": +/*!*****************************!*\ + !*** ./Cameras/XR/index.ts ***! + \*****************************/ +/*! exports provided: WebXRCamera, WebXREnterExitUIButton, WebXREnterExitUIOptions, WebXREnterExitUI, WebXRState, WebXRExperienceHelper, WebXRController, WebXRInput, WebXRManagedOutputCanvas, WebXRSessionManager */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _webXRCamera__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./webXRCamera */ "./Cameras/XR/webXRCamera.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRCamera", function() { return _webXRCamera__WEBPACK_IMPORTED_MODULE_0__["WebXRCamera"]; }); + +/* harmony import */ var _webXREnterExitUI__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./webXREnterExitUI */ "./Cameras/XR/webXREnterExitUI.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXREnterExitUIButton", function() { return _webXREnterExitUI__WEBPACK_IMPORTED_MODULE_1__["WebXREnterExitUIButton"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXREnterExitUIOptions", function() { return _webXREnterExitUI__WEBPACK_IMPORTED_MODULE_1__["WebXREnterExitUIOptions"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXREnterExitUI", function() { return _webXREnterExitUI__WEBPACK_IMPORTED_MODULE_1__["WebXREnterExitUI"]; }); + +/* harmony import */ var _webXRExperienceHelper__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./webXRExperienceHelper */ "./Cameras/XR/webXRExperienceHelper.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRState", function() { return _webXRExperienceHelper__WEBPACK_IMPORTED_MODULE_2__["WebXRState"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRExperienceHelper", function() { return _webXRExperienceHelper__WEBPACK_IMPORTED_MODULE_2__["WebXRExperienceHelper"]; }); + +/* harmony import */ var _webXRInput__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./webXRInput */ "./Cameras/XR/webXRInput.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRController", function() { return _webXRInput__WEBPACK_IMPORTED_MODULE_3__["WebXRController"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRInput", function() { return _webXRInput__WEBPACK_IMPORTED_MODULE_3__["WebXRInput"]; }); + +/* harmony import */ var _webXRManagedOutputCanvas__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./webXRManagedOutputCanvas */ "./Cameras/XR/webXRManagedOutputCanvas.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRManagedOutputCanvas", function() { return _webXRManagedOutputCanvas__WEBPACK_IMPORTED_MODULE_4__["WebXRManagedOutputCanvas"]; }); + +/* harmony import */ var _webXRSessionManager__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./webXRSessionManager */ "./Cameras/XR/webXRSessionManager.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRSessionManager", function() { return _webXRSessionManager__WEBPACK_IMPORTED_MODULE_5__["WebXRSessionManager"]; }); + + + + + + + + + +/***/ }), + +/***/ "./Cameras/XR/webXRCamera.ts": +/*!***********************************!*\ + !*** ./Cameras/XR/webXRCamera.ts ***! + \***********************************/ +/*! exports provided: WebXRCamera */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WebXRCamera", function() { return WebXRCamera; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/camera */ "./Cameras/camera.ts"); +/* harmony import */ var _Cameras_freeCamera__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Cameras/freeCamera */ "./Cameras/freeCamera.ts"); +/* harmony import */ var _Cameras_targetCamera__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Cameras/targetCamera */ "./Cameras/targetCamera.ts"); + + + + + +/** + * WebXR Camera which holds the views for the xrSession + * @see https://doc.babylonjs.com/how_to/webxr + */ +var WebXRCamera = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](WebXRCamera, _super); + /** + * Creates a new webXRCamera, this should only be set at the camera after it has been updated by the xrSessionManager + * @param name the name of the camera + * @param scene the scene to add the camera to + */ + function WebXRCamera(name, scene) { + var _this = _super.call(this, name, _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(), scene) || this; + // Initial camera configuration + _this.minZ = 0; + _this.rotationQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Quaternion"](); + _this.cameraRigMode = _Cameras_camera__WEBPACK_IMPORTED_MODULE_2__["Camera"].RIG_MODE_CUSTOM; + _this.updateUpVectorFromRotation = true; + _this._updateNumberOfRigCameras(1); + return _this; + } + WebXRCamera.prototype._updateNumberOfRigCameras = function (viewCount) { + if (viewCount === void 0) { viewCount = 1; } + while (this.rigCameras.length < viewCount) { + var newCamera = new _Cameras_targetCamera__WEBPACK_IMPORTED_MODULE_4__["TargetCamera"]("view: " + this.rigCameras.length, _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(), this.getScene()); + newCamera.minZ = 0; + newCamera.parent = this; + newCamera.rotationQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Quaternion"](); + newCamera.updateUpVectorFromRotation = true; + this.rigCameras.push(newCamera); + } + while (this.rigCameras.length > viewCount) { + var removedCamera = this.rigCameras.pop(); + if (removedCamera) { + removedCamera.dispose(); + } + } + }; + /** @hidden */ + WebXRCamera.prototype._updateForDualEyeDebugging = function (pupilDistance) { + if (pupilDistance === void 0) { pupilDistance = 0.01; } + // Create initial camera rigs + this._updateNumberOfRigCameras(2); + this.rigCameras[0].viewport = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Viewport"](0, 0, 0.5, 1.0); + this.rigCameras[0].position.x = -pupilDistance / 2; + this.rigCameras[0].outputRenderTarget = null; + this.rigCameras[1].viewport = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Viewport"](0.5, 0, 0.5, 1.0); + this.rigCameras[1].position.x = pupilDistance / 2; + this.rigCameras[1].outputRenderTarget = null; + }; + /** + * Updates the cameras position from the current pose information of the XR session + * @param xrSessionManager the session containing pose information + * @returns true if the camera has been updated, false if the session did not contain pose or frame data + */ + WebXRCamera.prototype.updateFromXRSessionManager = function (xrSessionManager) { + var _this = this; + // Ensure all frame data is available + if (!xrSessionManager._currentXRFrame || !xrSessionManager._currentXRFrame.getDevicePose) { + return false; + } + var pose = xrSessionManager._currentXRFrame.getDevicePose(xrSessionManager._frameOfReference); + if (!pose || !pose.poseModelMatrix) { + return false; + } + // Update the parent cameras matrix + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].FromFloat32ArrayToRefScaled(pose.poseModelMatrix, 0, 1, WebXRCamera._TmpMatrix); + if (!this._scene.useRightHandedSystem) { + WebXRCamera._TmpMatrix.toggleModelMatrixHandInPlace(); + } + WebXRCamera._TmpMatrix.getTranslationToRef(this.position); + WebXRCamera._TmpMatrix.getRotationMatrixToRef(WebXRCamera._TmpMatrix); + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Quaternion"].FromRotationMatrixToRef(WebXRCamera._TmpMatrix, this.rotationQuaternion); + this.computeWorldMatrix(); + // Update camera rigs + this._updateNumberOfRigCameras(xrSessionManager._currentXRFrame.views.length); + xrSessionManager._currentXRFrame.views.forEach(function (view, i) { + // Update view/projection matrix + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].FromFloat32ArrayToRefScaled(pose.getViewMatrix(view), 0, 1, _this.rigCameras[i]._computedViewMatrix); + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].FromFloat32ArrayToRefScaled(view.projectionMatrix, 0, 1, _this.rigCameras[i]._projectionMatrix); + if (!_this._scene.useRightHandedSystem) { + _this.rigCameras[i]._computedViewMatrix.toggleModelMatrixHandInPlace(); + _this.rigCameras[i]._projectionMatrix.toggleProjectionMatrixHandInPlace(); + } + // Update viewport + var viewport = xrSessionManager._xrSession.baseLayer.getViewport(view); + var width = xrSessionManager._xrSession.baseLayer.framebufferWidth; + var height = xrSessionManager._xrSession.baseLayer.framebufferHeight; + _this.rigCameras[i].viewport.width = viewport.width / width; + _this.rigCameras[i].viewport.height = viewport.height / height; + _this.rigCameras[i].viewport.x = viewport.x / width; + _this.rigCameras[i].viewport.y = viewport.y / height; + // Set cameras to render to the session's render target + _this.rigCameras[i].outputRenderTarget = xrSessionManager._sessionRenderTargetTexture; + }); + return true; + }; + WebXRCamera._TmpMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"](); + return WebXRCamera; +}(_Cameras_freeCamera__WEBPACK_IMPORTED_MODULE_3__["FreeCamera"])); + + + +/***/ }), + +/***/ "./Cameras/XR/webXREnterExitUI.ts": +/*!****************************************!*\ + !*** ./Cameras/XR/webXREnterExitUI.ts ***! + \****************************************/ +/*! exports provided: WebXREnterExitUIButton, WebXREnterExitUIOptions, WebXREnterExitUI */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WebXREnterExitUIButton", function() { return WebXREnterExitUIButton; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WebXREnterExitUIOptions", function() { return WebXREnterExitUIOptions; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WebXREnterExitUI", function() { return WebXREnterExitUI; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _webXRExperienceHelper__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./webXRExperienceHelper */ "./Cameras/XR/webXRExperienceHelper.ts"); + + + +/** + * Button which can be used to enter a different mode of XR + */ +var WebXREnterExitUIButton = /** @class */ (function () { + /** + * Creates a WebXREnterExitUIButton + * @param element button element + * @param initializationOptions XR initialization options for the button + */ + function WebXREnterExitUIButton( + /** button element */ + element, + /** XR initialization options for the button */ + initializationOptions) { + this.element = element; + this.initializationOptions = initializationOptions; + } + /** + * Overwritable function which can be used to update the button's visuals when the state changes + * @param activeButton the current active button in the UI + */ + WebXREnterExitUIButton.prototype.update = function (activeButton) { + }; + return WebXREnterExitUIButton; +}()); + +/** + * Options to create the webXR UI + */ +var WebXREnterExitUIOptions = /** @class */ (function () { + function WebXREnterExitUIOptions() { + } + return WebXREnterExitUIOptions; +}()); + +/** + * UI to allow the user to enter/exit XR mode + */ +var WebXREnterExitUI = /** @class */ (function () { + function WebXREnterExitUI(scene, options) { + var _this = this; + this.scene = scene; + this._buttons = []; + this._activeButton = null; + /** + * Fired every time the active button is changed. + * + * When xr is entered via a button that launches xr that button will be the callback parameter + * + * When exiting xr the callback parameter will be null) + */ + this.activeButtonChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + this._overlay = document.createElement("div"); + this._overlay.style.cssText = "z-index:11;position: absolute; right: 20px;bottom: 50px;"; + if (options.customButtons) { + this._buttons = options.customButtons; + } + else { + var hmdBtn = document.createElement("button"); + hmdBtn.style.cssText = "color: #868686; border-color: #868686; border-style: solid; margin-left: 10px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-repeat:no-repeat; background-position: center; outline: none;"; + hmdBtn.innerText = "HMD"; + this._buttons.push(new WebXREnterExitUIButton(hmdBtn, { immersive: true, outputContext: options.outputCanvasContext })); + this._buttons[this._buttons.length - 1].update = function (activeButton) { + this.element.style.display = (activeButton === null || activeButton === this) ? "" : "none"; + this.element.innerText = activeButton === this ? "EXIT" : "HMD"; + }; + var windowBtn = document.createElement("button"); + windowBtn.style.cssText = hmdBtn.style.cssText; + windowBtn.innerText = "Window"; + this._buttons.push(new WebXREnterExitUIButton(windowBtn, { immersive: false, environmentIntegration: true, outputContext: options.outputCanvasContext })); + this._buttons[this._buttons.length - 1].update = function (activeButton) { + this.element.style.display = (activeButton === null || activeButton === this) ? "" : "none"; + this.element.innerText = activeButton === this ? "EXIT" : "Window"; + }; + this._updateButtons(null); + } + var renderCanvas = scene.getEngine().getRenderingCanvas(); + if (renderCanvas && renderCanvas.parentNode) { + renderCanvas.parentNode.appendChild(this._overlay); + scene.onDisposeObservable.addOnce(function () { + _this.dispose(); + }); + } + } + /** + * Creates UI to allow the user to enter/exit XR mode + * @param scene the scene to add the ui to + * @param helper the xr experience helper to enter/exit xr with + * @param options options to configure the UI + * @returns the created ui + */ + WebXREnterExitUI.CreateAsync = function (scene, helper, options) { + var _this = this; + var ui = new WebXREnterExitUI(scene, options); + var supportedPromises = ui._buttons.map(function (btn) { + return helper.supportsSessionAsync(btn.initializationOptions); + }); + helper.onStateChangedObservable.add(function (state) { + if (state == _webXRExperienceHelper__WEBPACK_IMPORTED_MODULE_2__["WebXRState"].NOT_IN_XR) { + ui._updateButtons(null); + } + }); + return Promise.all(supportedPromises).then(function (results) { + results.forEach(function (supported, i) { + if (supported) { + ui._overlay.appendChild(ui._buttons[i].element); + ui._buttons[i].element.onclick = function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () { + return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) { + switch (_a.label) { + case 0: + if (!(helper.state == _webXRExperienceHelper__WEBPACK_IMPORTED_MODULE_2__["WebXRState"].IN_XR)) return [3 /*break*/, 2]; + ui._updateButtons(null); + return [4 /*yield*/, helper.exitXRAsync()]; + case 1: + _a.sent(); + return [2 /*return*/]; + case 2: + if (!(helper.state == _webXRExperienceHelper__WEBPACK_IMPORTED_MODULE_2__["WebXRState"].NOT_IN_XR)) return [3 /*break*/, 4]; + ui._updateButtons(ui._buttons[i]); + return [4 /*yield*/, helper.enterXRAsync(ui._buttons[i].initializationOptions, "eye-level")]; + case 3: + _a.sent(); + _a.label = 4; + case 4: return [2 /*return*/]; + } + }); + }); }; + } + }); + return ui; + }); + }; + WebXREnterExitUI.prototype._updateButtons = function (activeButton) { + var _this = this; + this._activeButton = activeButton; + this._buttons.forEach(function (b) { + b.update(_this._activeButton); + }); + this.activeButtonChangedObservable.notifyObservers(this._activeButton); + }; + /** + * Disposes of the object + */ + WebXREnterExitUI.prototype.dispose = function () { + var renderCanvas = this.scene.getEngine().getRenderingCanvas(); + if (renderCanvas && renderCanvas.parentNode && renderCanvas.parentNode.contains(this._overlay)) { + renderCanvas.parentNode.removeChild(this._overlay); + } + this.activeButtonChangedObservable.clear(); + }; + return WebXREnterExitUI; +}()); + + + +/***/ }), + +/***/ "./Cameras/XR/webXRExperienceHelper.ts": +/*!*********************************************!*\ + !*** ./Cameras/XR/webXRExperienceHelper.ts ***! + \*********************************************/ +/*! exports provided: WebXRState, WebXRExperienceHelper */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WebXRState", function() { return WebXRState; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WebXRExperienceHelper", function() { return WebXRExperienceHelper; }); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Meshes/abstractMesh */ "./Meshes/abstractMesh.ts"); +/* harmony import */ var _webXRSessionManager__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./webXRSessionManager */ "./Cameras/XR/webXRSessionManager.ts"); +/* harmony import */ var _webXRCamera__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./webXRCamera */ "./Cameras/XR/webXRCamera.ts"); + + + + + +/** + * States of the webXR experience + */ +var WebXRState; +(function (WebXRState) { + /** + * Transitioning to being in XR mode + */ + WebXRState[WebXRState["ENTERING_XR"] = 0] = "ENTERING_XR"; + /** + * Transitioning to non XR mode + */ + WebXRState[WebXRState["EXITING_XR"] = 1] = "EXITING_XR"; + /** + * In XR mode and presenting + */ + WebXRState[WebXRState["IN_XR"] = 2] = "IN_XR"; + /** + * Not entered XR mode + */ + WebXRState[WebXRState["NOT_IN_XR"] = 3] = "NOT_IN_XR"; +})(WebXRState || (WebXRState = {})); +/** + * Helper class used to enable XR + * @see https://doc.babylonjs.com/how_to/webxr + */ +var WebXRExperienceHelper = /** @class */ (function () { + /** + * Creates a WebXRExperienceHelper + * @param scene The scene the helper should be created in + */ + function WebXRExperienceHelper(scene) { + this.scene = scene; + /** + * The current state of the XR experience (eg. transitioning, in XR or not in XR) + */ + this.state = WebXRState.NOT_IN_XR; + /** + * Fires when the state of the experience helper has changed + */ + this.onStateChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](); + this._nonVRCamera = null; + this._originalSceneAutoClear = true; + this._supported = false; + this.camera = new _webXRCamera__WEBPACK_IMPORTED_MODULE_4__["WebXRCamera"]("", scene); + this._sessionManager = new _webXRSessionManager__WEBPACK_IMPORTED_MODULE_3__["WebXRSessionManager"](scene); + this.container = new _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_2__["AbstractMesh"]("", scene); + this.camera.parent = this.container; + } + WebXRExperienceHelper.prototype._setState = function (val) { + this.state = val; + this.onStateChangedObservable.notifyObservers(this.state); + }; + /** + * Creates the experience helper + * @param scene the scene to attach the experience helper to + * @returns a promise for the experience helper + */ + WebXRExperienceHelper.CreateAsync = function (scene) { + var helper = new WebXRExperienceHelper(scene); + return helper._sessionManager.initializeAsync().then(function () { + helper._supported = true; + return helper; + }).catch(function () { + return helper; + }); + }; + /** + * Exits XR mode and returns the scene to its original state + * @returns promise that resolves after xr mode has exited + */ + WebXRExperienceHelper.prototype.exitXRAsync = function () { + this._setState(WebXRState.EXITING_XR); + return this._sessionManager.exitXRAsync(); + }; + /** + * Enters XR mode (This must be done within a user interaction in most browsers eg. button click) + * @param sessionCreationOptions options for the XR session + * @param frameOfReference frame of reference of the XR session + * @returns promise that resolves after xr mode has entered + */ + WebXRExperienceHelper.prototype.enterXRAsync = function (sessionCreationOptions, frameOfReference) { + var _this = this; + if (!this._supported) { + throw "XR session not supported by this browser"; + } + this._setState(WebXRState.ENTERING_XR); + return this._sessionManager.enterXRAsync(sessionCreationOptions, frameOfReference).then(function () { + // Cache pre xr scene settings + _this._originalSceneAutoClear = _this.scene.autoClear; + _this._nonVRCamera = _this.scene.activeCamera; + // Overwrite current scene settings + _this.scene.autoClear = false; + _this.scene.activeCamera = _this.camera; + _this._sessionManager.onXRFrameObservable.add(function () { + _this.camera.updateFromXRSessionManager(_this._sessionManager); + }); + _this._sessionManager.onXRSessionEnded.addOnce(function () { + // Reset camera rigs output render target to ensure sessions render target is not drawn after it ends + _this.camera.rigCameras.forEach(function (c) { + c.outputRenderTarget = null; + }); + // Restore scene settings + _this.scene.autoClear = _this._originalSceneAutoClear; + _this.scene.activeCamera = _this._nonVRCamera; + _this._sessionManager.onXRFrameObservable.clear(); + _this._setState(WebXRState.NOT_IN_XR); + }); + _this._setState(WebXRState.IN_XR); + }); + }; + /** + * Fires a ray and returns the closest hit in the xr sessions enviornment, useful to place objects in AR + * @param ray ray to cast into the environment + * @returns Promise which resolves with a collision point in the environment if it exists + */ + WebXRExperienceHelper.prototype.environmentPointHitTestAsync = function (ray) { + return this._sessionManager.environmentPointHitTestAsync(ray); + }; + /** + * Updates the global position of the camera by moving the camera's container + * This should be used instead of modifying the camera's position as it will be overwritten by an xrSessions's update frame + * @param position The desired global position of the camera + */ + WebXRExperienceHelper.prototype.setPositionOfCameraUsingContainer = function (position) { + this.camera.globalPosition.subtractToRef(position, WebXRExperienceHelper._TmpVector); + this.container.position.subtractInPlace(WebXRExperienceHelper._TmpVector); + }; + /** + * Rotates the xr camera by rotating the camera's container around the camera's position + * This should be used instead of modifying the camera's rotation as it will be overwritten by an xrSessions's update frame + * @param rotation the desired quaternion rotation to apply to the camera + */ + WebXRExperienceHelper.prototype.rotateCameraByQuaternionUsingContainer = function (rotation) { + if (!this.container.rotationQuaternion) { + this.container.rotationQuaternion = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Quaternion"].FromEulerVector(this.container.rotation); + } + this.container.rotationQuaternion.multiplyInPlace(rotation); + this.container.position.rotateByQuaternionAroundPointToRef(rotation, this.camera.globalPosition, this.container.position); + }; + /** + * Checks if the creation options are supported by the xr session + * @param options creation options + * @returns true if supported + */ + WebXRExperienceHelper.prototype.supportsSessionAsync = function (options) { + if (!this._supported) { + return Promise.resolve(false); + } + return this._sessionManager.supportsSessionAsync(options); + }; + /** + * Disposes of the experience helper + */ + WebXRExperienceHelper.prototype.dispose = function () { + this.camera.dispose(); + this.container.dispose(); + this.onStateChangedObservable.clear(); + this._sessionManager.dispose(); + }; + WebXRExperienceHelper._TmpVector = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"](); + return WebXRExperienceHelper; +}()); + + + +/***/ }), + +/***/ "./Cameras/XR/webXRInput.ts": +/*!**********************************!*\ + !*** ./Cameras/XR/webXRInput.ts ***! + \**********************************/ +/*! exports provided: WebXRController, WebXRInput */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WebXRController", function() { return WebXRController; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WebXRInput", function() { return WebXRInput; }); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Meshes/abstractMesh */ "./Meshes/abstractMesh.ts"); + + +/** + * Represents an XR input + */ +var WebXRController = /** @class */ (function () { + /** + * Creates the controller + * @see https://doc.babylonjs.com/how_to/webxr + * @param scene the scene which the controller should be associated to + */ + function WebXRController(scene) { + this.pointer = new _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_1__["AbstractMesh"]("controllerPointer", scene); + } + /** + * Disposes of the object + */ + WebXRController.prototype.dispose = function () { + if (this.grip) { + this.grip.dispose(); + } + this.pointer.dispose(); + }; + return WebXRController; +}()); + +/** + * XR input used to track XR inputs such as controllers/rays + */ +var WebXRInput = /** @class */ (function () { + /** + * Initializes the WebXRInput + * @param helper experience helper which the input should be created for + */ + function WebXRInput(helper) { + var _this = this; + this.helper = helper; + /** + * XR controllers being tracked + */ + this.controllers = []; + this._tmpMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"](); + this._frameObserver = helper._sessionManager.onXRFrameObservable.add(function () { + if (!helper._sessionManager._currentXRFrame || !helper._sessionManager._currentXRFrame.getDevicePose) { + return; + } + var xrFrame = helper._sessionManager._currentXRFrame; + var inputSources = helper._sessionManager._xrSession.getInputSources(); + inputSources.forEach(function (input, i) { + var inputPose = xrFrame.getInputPose(input, helper._sessionManager._frameOfReference); + if (inputPose) { + if (_this.controllers.length <= i) { + _this.controllers.push(new WebXRController(helper.container.getScene())); + } + var controller = _this.controllers[i]; + // Manage the grip if it exists + if (inputPose.gripMatrix) { + if (!controller.grip) { + controller.grip = new _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_1__["AbstractMesh"]("controllerGrip", helper.container.getScene()); + } + _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].FromFloat32ArrayToRefScaled(inputPose.gripMatrix, 0, 1, _this._tmpMatrix); + if (!controller.grip.getScene().useRightHandedSystem) { + _this._tmpMatrix.toggleModelMatrixHandInPlace(); + } + if (!controller.grip.rotationQuaternion) { + controller.grip.rotationQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"](); + } + _this._tmpMatrix.decompose(controller.grip.scaling, controller.grip.rotationQuaternion, controller.grip.position); + } + // Manager pointer of controller + _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].FromFloat32ArrayToRefScaled(inputPose.targetRay.transformMatrix, 0, 1, _this._tmpMatrix); + if (!controller.pointer.getScene().useRightHandedSystem) { + _this._tmpMatrix.toggleModelMatrixHandInPlace(); + } + if (!controller.pointer.rotationQuaternion) { + controller.pointer.rotationQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"](); + } + _this._tmpMatrix.decompose(controller.pointer.scaling, controller.pointer.rotationQuaternion, controller.pointer.position); + } + }); + }); + } + /** + * Disposes of the object + */ + WebXRInput.prototype.dispose = function () { + this.controllers.forEach(function (c) { + c.dispose(); + }); + this.helper._sessionManager.onXRFrameObservable.remove(this._frameObserver); + }; + return WebXRInput; +}()); + + + +/***/ }), + +/***/ "./Cameras/XR/webXRManagedOutputCanvas.ts": +/*!************************************************!*\ + !*** ./Cameras/XR/webXRManagedOutputCanvas.ts ***! + \************************************************/ +/*! exports provided: WebXRManagedOutputCanvas */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WebXRManagedOutputCanvas", function() { return WebXRManagedOutputCanvas; }); +/* harmony import */ var _webXRExperienceHelper__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./webXRExperienceHelper */ "./Cameras/XR/webXRExperienceHelper.ts"); + +/** + * Creates a canvas that is added/removed from the webpage when entering/exiting XR + */ +var WebXRManagedOutputCanvas = /** @class */ (function () { + /** + * Initializes the canvas to be added/removed upon entering/exiting xr + * @param helper the xr experience helper used to trigger adding/removing of the canvas + * @param canvas The canvas to be added/removed (If not specified a full screen canvas will be created) + */ + function WebXRManagedOutputCanvas(helper, canvas) { + var _this = this; + this._canvas = null; + /** + * xrpresent context of the canvas which can be used to display/mirror xr content + */ + this.canvasContext = null; + if (!canvas) { + canvas = document.createElement('canvas'); + canvas.style.cssText = "position:absolute; bottom:0px;right:0px;z-index:10;width:100%;height:100%;background-color: #000000;"; + } + this._setManagedOutputCanvas(canvas); + helper.onStateChangedObservable.add(function (stateInfo) { + if (stateInfo == _webXRExperienceHelper__WEBPACK_IMPORTED_MODULE_0__["WebXRState"].ENTERING_XR) { + // The canvas is added to the screen before entering XR because currently the xr session must be initialized while the canvas is added render properly + _this._addCanvas(); + } + else if (helper.state == _webXRExperienceHelper__WEBPACK_IMPORTED_MODULE_0__["WebXRState"].NOT_IN_XR) { + _this._removeCanvas(); + } + }); + } + /** + * Disposes of the object + */ + WebXRManagedOutputCanvas.prototype.dispose = function () { + this._removeCanvas(); + this._setManagedOutputCanvas(null); + }; + WebXRManagedOutputCanvas.prototype._setManagedOutputCanvas = function (canvas) { + this._removeCanvas(); + if (!canvas) { + this._canvas = null; + this.canvasContext = null; + } + else { + this._canvas = canvas; + this.canvasContext = this._canvas.getContext('xrpresent'); + } + }; + WebXRManagedOutputCanvas.prototype._addCanvas = function () { + if (this._canvas) { + document.body.appendChild(this._canvas); + } + }; + WebXRManagedOutputCanvas.prototype._removeCanvas = function () { + if (this._canvas && document.body.contains(this._canvas)) { + document.body.removeChild(this._canvas); + } + }; + return WebXRManagedOutputCanvas; +}()); + + + +/***/ }), + +/***/ "./Cameras/XR/webXRSessionManager.ts": +/*!*******************************************!*\ + !*** ./Cameras/XR/webXRSessionManager.ts ***! + \*******************************************/ +/*! exports provided: WebXRSessionManager */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WebXRSessionManager", function() { return WebXRSessionManager; }); +/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Misc/logger */ "./Misc/logger.ts"); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Materials/Textures/internalTexture */ "./Materials/Textures/internalTexture.ts"); +/* harmony import */ var _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Materials/Textures/renderTargetTexture */ "./Materials/Textures/renderTargetTexture.ts"); + + + + + +/** + * Manages an XRSession + * @see https://doc.babylonjs.com/how_to/webxr + */ +var WebXRSessionManager = /** @class */ (function () { + /** + * Constructs a WebXRSessionManager, this must be initialized within a user action before usage + * @param scene The scene which the session should be created for + */ + function WebXRSessionManager(scene) { + this.scene = scene; + /** + * Fires every time a new xrFrame arrives which can be used to update the camera + */ + this.onXRFrameObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + /** + * Fires when the xr session is ended either by the device or manually done + */ + this.onXRSessionEnded = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + /** @hidden */ + this._sessionRenderTargetTexture = null; + this._tmpMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"](); + } + /** + * Initializes the manager + * After initialization enterXR can be called to start an XR session + * @returns Promise which resolves after it is initialized + */ + WebXRSessionManager.prototype.initializeAsync = function () { + var _this = this; + _Misc_logger__WEBPACK_IMPORTED_MODULE_0__["Logger"].Warn("The WebXR APIs are still under development and are subject to change in the future."); + // Check if the browser supports webXR + this._xrNavigator = navigator; + if (!this._xrNavigator.xr) { + return Promise.reject("webXR not supported by this browser"); + } + // Request the webXR device + return this._xrNavigator.xr.requestDevice().then(function (device) { + _this._xrDevice = device; + return _this.scene.getEngine()._gl.setCompatibleXRDevice(_this._xrDevice); + }); + }; + /** + * Enters XR with the desired XR session options, this must be done with a user action (eg. button click event) + * @param sessionCreationOptions xr options to create the session with + * @param frameOfReferenceType option to configure how the xr pose is expressed + * @returns Promise which resolves after it enters XR + */ + WebXRSessionManager.prototype.enterXRAsync = function (sessionCreationOptions, frameOfReferenceType) { + var _this = this; + // initialize session + return this._xrDevice.requestSession(sessionCreationOptions).then(function (session) { + _this._xrSession = session; + // handle when the session is ended (By calling session.end or device ends its own session eg. pressing home button on phone) + _this._xrSession.addEventListener("end", function () { + // Remove render target texture and notify frame obervers + _this._sessionRenderTargetTexture = null; + // Restore frame buffer to avoid clear on xr framebuffer after session end + _this.scene.getEngine().restoreDefaultFramebuffer(); + // Need to restart render loop as after the session is ended the last request for new frame will never call callback + _this.scene.getEngine().customAnimationFrameRequester = null; + _this.onXRSessionEnded.notifyObservers(null); + _this.scene.getEngine()._renderLoop(); + }, { once: true }); + _this._xrSession.baseLayer = new XRWebGLLayer(_this._xrSession, _this.scene.getEngine()._gl); + return _this._xrSession.requestFrameOfReference(frameOfReferenceType); + }).then(function (frameOfRef) { + _this._frameOfReference = frameOfRef; + // Tell the engine's render loop to be driven by the xr session's refresh rate and provide xr pose information + _this.scene.getEngine().customAnimationFrameRequester = { + requestAnimationFrame: _this._xrSession.requestAnimationFrame.bind(_this._xrSession), + renderFunction: function (timestamp, xrFrame) { + // Store the XR frame in the manager to be consumed by the XR camera to update pose + _this._currentXRFrame = xrFrame; + _this.onXRFrameObservable.notifyObservers(null); + _this.scene.getEngine()._renderLoop(); + } + }; + // Create render target texture from xr's webgl render target + _this._sessionRenderTargetTexture = WebXRSessionManager._CreateRenderTargetTextureFromSession(_this._xrSession, _this.scene); + // Stop window's animation frame and trigger sessions animation frame + window.cancelAnimationFrame(_this.scene.getEngine()._frameHandler); + _this.scene.getEngine()._renderLoop(); + }); + }; + /** + * Stops the xrSession and restores the renderloop + * @returns Promise which resolves after it exits XR + */ + WebXRSessionManager.prototype.exitXRAsync = function () { + return this._xrSession.end(); + }; + /** + * Fires a ray and returns the closest hit in the xr sessions enviornment, useful to place objects in AR + * @param ray ray to cast into the environment + * @returns Promise which resolves with a collision point in the environment if it exists + */ + WebXRSessionManager.prototype.environmentPointHitTestAsync = function (ray) { + var _this = this; + return new Promise(function (res) { + // Compute left handed inputs to request hit test + var origin = new Float32Array([ray.origin.x, ray.origin.y, ray.origin.z]); + var direction = new Float32Array([ray.direction.x, ray.direction.y, ray.direction.z]); + if (!_this.scene.useRightHandedSystem) { + origin[2] *= -1; + direction[2] *= -1; + } + // Fire hittest + _this._xrSession.requestHitTest(origin, direction, _this._frameOfReference) + .then(function (hits) { + if (hits.length > 0) { + _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"].FromFloat32ArrayToRefScaled(hits[0].hitMatrix, 0, 1.0, _this._tmpMatrix); + var hitPoint = _this._tmpMatrix.getTranslation(); + if (!_this.scene.useRightHandedSystem) { + hitPoint.z *= -1; + } + res(hitPoint); + } + else { + res(null); + } + }).catch(function () { + res(null); + }); + }); + }; + /** + * Checks if a session would be supported for the creation options specified + * @param options creation options to check if they are supported + * @returns true if supported + */ + WebXRSessionManager.prototype.supportsSessionAsync = function (options) { + return this._xrDevice.supportsSession(options).then(function () { + return true; + }).catch(function () { + return false; + }); + }; + /** + * @hidden + * Converts the render layer of xrSession to a render target + * @param session session to create render target for + * @param scene scene the new render target should be created for + */ + WebXRSessionManager._CreateRenderTargetTextureFromSession = function (session, scene) { + // Create internal texture + var internalTexture = new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_3__["InternalTexture"](scene.getEngine(), _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_3__["InternalTexture"].DATASOURCE_UNKNOWN, true); + internalTexture.width = session.baseLayer.framebufferWidth; + internalTexture.height = session.baseLayer.framebufferHeight; + internalTexture._framebuffer = session.baseLayer.framebuffer; + // Create render target texture from the internal texture + var renderTargetTexture = new _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_4__["RenderTargetTexture"]("XR renderTargetTexture", { width: internalTexture.width, height: internalTexture.height }, scene, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, true); + renderTargetTexture._texture = internalTexture; + return renderTargetTexture; + }; + /** + * Disposes of the session manager + */ + WebXRSessionManager.prototype.dispose = function () { + this.onXRFrameObservable.clear(); + this.onXRSessionEnded.clear(); + }; + return WebXRSessionManager; +}()); + + + +/***/ }), + +/***/ "./Cameras/arcRotateCamera.ts": +/*!************************************!*\ + !*** ./Cameras/arcRotateCamera.ts ***! + \************************************/ +/*! exports provided: ArcRotateCamera */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCamera", function() { return ArcRotateCamera; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../node */ "./node.ts"); +/* harmony import */ var _Meshes_mesh__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Meshes/mesh */ "./Meshes/mesh.ts"); +/* harmony import */ var _Behaviors_Cameras_autoRotationBehavior__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Behaviors/Cameras/autoRotationBehavior */ "./Behaviors/Cameras/autoRotationBehavior.ts"); +/* harmony import */ var _Behaviors_Cameras_bouncingBehavior__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Behaviors/Cameras/bouncingBehavior */ "./Behaviors/Cameras/bouncingBehavior.ts"); +/* harmony import */ var _Behaviors_Cameras_framingBehavior__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Behaviors/Cameras/framingBehavior */ "./Behaviors/Cameras/framingBehavior.ts"); +/* harmony import */ var _camera__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./camera */ "./Cameras/camera.ts"); +/* harmony import */ var _targetCamera__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./targetCamera */ "./Cameras/targetCamera.ts"); +/* harmony import */ var _Cameras_arcRotateCameraInputsManager__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../Cameras/arcRotateCameraInputsManager */ "./Cameras/arcRotateCameraInputsManager.ts"); + + + + + + + + + + + + +_node__WEBPACK_IMPORTED_MODULE_4__["Node"].AddNodeConstructor("ArcRotateCamera", function (name, scene) { + return function () { return new ArcRotateCamera(name, 0, 0, 1.0, _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(), scene); }; +}); +/** + * This represents an orbital type of camera. + * + * This camera always points towards a given target position and can be rotated around that target with the target as the centre of rotation. It can be controlled with cursors and mouse, or with touch events. + * Think of this camera as one orbiting its target position, or more imaginatively as a spy satellite orbiting the earth. Its position relative to the target (earth) can be set by three parameters, alpha (radians) the longitudinal rotation, beta (radians) the latitudinal rotation and radius the distance from the target position. + * @see http://doc.babylonjs.com/babylon101/cameras#arc-rotate-camera + */ +var ArcRotateCamera = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ArcRotateCamera, _super); + /** + * Instantiates a new ArcRotateCamera in a given scene + * @param name Defines the name of the camera + * @param alpha Defines the camera rotation along the logitudinal axis + * @param beta Defines the camera rotation along the latitudinal axis + * @param radius Defines the camera distance from its target + * @param target Defines the camera target + * @param scene Defines the scene the camera belongs to + * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined + */ + function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) { + if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; } + var _this = _super.call(this, name, _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(), scene, setActiveOnSceneIfNoneActive) || this; + _this._upVector = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Up(); + /** + * Current inertia value on the longitudinal axis. + * The bigger this number the longer it will take for the camera to stop. + */ + _this.inertialAlphaOffset = 0; + /** + * Current inertia value on the latitudinal axis. + * The bigger this number the longer it will take for the camera to stop. + */ + _this.inertialBetaOffset = 0; + /** + * Current inertia value on the radius axis. + * The bigger this number the longer it will take for the camera to stop. + */ + _this.inertialRadiusOffset = 0; + /** + * Minimum allowed angle on the longitudinal axis. + * This can help limiting how the Camera is able to move in the scene. + */ + _this.lowerAlphaLimit = null; + /** + * Maximum allowed angle on the longitudinal axis. + * This can help limiting how the Camera is able to move in the scene. + */ + _this.upperAlphaLimit = null; + /** + * Minimum allowed angle on the latitudinal axis. + * This can help limiting how the Camera is able to move in the scene. + */ + _this.lowerBetaLimit = 0.01; + /** + * Maximum allowed angle on the latitudinal axis. + * This can help limiting how the Camera is able to move in the scene. + */ + _this.upperBetaLimit = Math.PI - 0.01; + /** + * Minimum allowed distance of the camera to the target (The camera can not get closer). + * This can help limiting how the Camera is able to move in the scene. + */ + _this.lowerRadiusLimit = null; + /** + * Maximum allowed distance of the camera to the target (The camera can not get further). + * This can help limiting how the Camera is able to move in the scene. + */ + _this.upperRadiusLimit = null; + /** + * Defines the current inertia value used during panning of the camera along the X axis. + */ + _this.inertialPanningX = 0; + /** + * Defines the current inertia value used during panning of the camera along the Y axis. + */ + _this.inertialPanningY = 0; + /** + * Defines the distance used to consider the camera in pan mode vs pinch/zoom. + * Basically if your fingers moves away from more than this distance you will be considered + * in pinch mode. + */ + _this.pinchToPanMaxDistance = 20; + /** + * Defines the maximum distance the camera can pan. + * This could help keeping the cammera always in your scene. + */ + _this.panningDistanceLimit = null; + /** + * Defines the target of the camera before paning. + */ + _this.panningOriginTarget = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(); + /** + * Defines the value of the inertia used during panning. + * 0 would mean stop inertia and one would mean no decelleration at all. + */ + _this.panningInertia = 0.9; + //-- end properties for backward compatibility for inputs + /** + * Defines how much the radius should be scaled while zomming on a particular mesh (through the zoomOn function) + */ + _this.zoomOnFactor = 1; + /** + * Defines a screen offset for the camera position. + */ + _this.targetScreenOffset = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector2"].Zero(); + /** + * Allows the camera to be completely reversed. + * If false the camera can not arrive upside down. + */ + _this.allowUpsideDown = true; + /** + * Define if double tap/click is used to restore the previously saved state of the camera. + */ + _this.useInputToRestoreState = true; + /** @hidden */ + _this._viewMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"](); + /** + * Defines the allowed panning axis. + */ + _this.panningAxis = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](1, 1, 0); + /** + * Observable triggered when the mesh target has been changed on the camera. + */ + _this.onMeshTargetChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); + /** + * Defines whether the camera should check collision with the objects oh the scene. + * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#how-can-i-do-this + */ + _this.checkCollisions = false; + /** + * Defines the collision radius of the camera. + * This simulates a sphere around the camera. + * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera + */ + _this.collisionRadius = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0.5, 0.5, 0.5); + _this._previousPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(); + _this._collisionVelocity = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(); + _this._newPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(); + _this._computationVector = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(); + _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) { + if (collidedMesh === void 0) { collidedMesh = null; } + if (!collidedMesh) { + _this._previousPosition.copyFrom(_this._position); + } + else { + _this.setPosition(newPosition); + if (_this.onCollide) { + _this.onCollide(collidedMesh); + } + } + // Recompute because of constraints + var cosa = Math.cos(_this.alpha); + var sina = Math.sin(_this.alpha); + var cosb = Math.cos(_this.beta); + var sinb = Math.sin(_this.beta); + if (sinb === 0) { + sinb = 0.0001; + } + var target = _this._getTargetPosition(); + _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb); + target.addToRef(_this._computationVector, _this._newPosition); + _this._position.copyFrom(_this._newPosition); + var up = _this.upVector; + if (_this.allowUpsideDown && _this.beta < 0) { + up = up.clone(); + up = up.negate(); + } + _this._computeViewMatrix(_this._position, target, up); + _this._viewMatrix.addAtIndex(12, _this.targetScreenOffset.x); + _this._viewMatrix.addAtIndex(13, _this.targetScreenOffset.y); + _this._collisionTriggered = false; + }; + _this._target = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(); + if (target) { + _this.setTarget(target); + } + _this.alpha = alpha; + _this.beta = beta; + _this.radius = radius; + _this.getViewMatrix(); + _this.inputs = new _Cameras_arcRotateCameraInputsManager__WEBPACK_IMPORTED_MODULE_11__["ArcRotateCameraInputsManager"](_this); + _this.inputs.addKeyboard().addMouseWheel().addPointers(); + return _this; + } + Object.defineProperty(ArcRotateCamera.prototype, "target", { + /** + * Defines the target point of the camera. + * The camera looks towards it form the radius distance. + */ + get: function () { + return this._target; + }, + set: function (value) { + this.setTarget(value); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ArcRotateCamera.prototype, "position", { + /** + * Define the current local position of the camera in the scene + */ + get: function () { + return this._position; + }, + set: function (newPosition) { + this.setPosition(newPosition); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ArcRotateCamera.prototype, "upVector", { + get: function () { + return this._upVector; + }, + /** + * The vector the camera should consider as up. (default is Vector3(0, 1, 0) as returned by Vector3.Up()) + * Setting this will copy the given vector to the camera's upVector, and set rotation matrices to and from Y up. + * DO NOT set the up vector using copyFrom or copyFromFloats, as this bypasses setting the above matrices. + */ + set: function (vec) { + if (!this._upToYMatrix) { + this._YToUpMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"](); + this._upToYMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"](); + this._upVector = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(); + } + vec.normalize(); + this._upVector.copyFrom(vec); + this.setMatUp(); + }, + enumerable: true, + configurable: true + }); + /** + * Sets the Y-up to camera up-vector rotation matrix, and the up-vector to Y-up rotation matrix. + */ + ArcRotateCamera.prototype.setMatUp = function () { + // from y-up to custom-up (used in _getViewMatrix) + _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"].RotationAlignToRef(_Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].UpReadOnly, this._upVector, this._YToUpMatrix); + // from custom-up to y-up (used in rebuildAnglesAndRadius) + _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"].RotationAlignToRef(this._upVector, _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].UpReadOnly, this._upToYMatrix); + }; + Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", { + //-- begin properties for backward compatibility for inputs + /** + * Gets or Set the pointer angular sensibility along the X axis or how fast is the camera rotating. + */ + get: function () { + var pointers = this.inputs.attached["pointers"]; + if (pointers) { + return pointers.angularSensibilityX; + } + return 0; + }, + set: function (value) { + var pointers = this.inputs.attached["pointers"]; + if (pointers) { + pointers.angularSensibilityX = value; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", { + /** + * Gets or Set the pointer angular sensibility along the Y axis or how fast is the camera rotating. + */ + get: function () { + var pointers = this.inputs.attached["pointers"]; + if (pointers) { + return pointers.angularSensibilityY; + } + return 0; + }, + set: function (value) { + var pointers = this.inputs.attached["pointers"]; + if (pointers) { + pointers.angularSensibilityY = value; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", { + /** + * Gets or Set the pointer pinch precision or how fast is the camera zooming. + */ + get: function () { + var pointers = this.inputs.attached["pointers"]; + if (pointers) { + return pointers.pinchPrecision; + } + return 0; + }, + set: function (value) { + var pointers = this.inputs.attached["pointers"]; + if (pointers) { + pointers.pinchPrecision = value; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", { + /** + * Gets or Set the pointer pinch delta percentage or how fast is the camera zooming. + * It will be used instead of pinchDeltaPrecision if different from 0. + * It defines the percentage of current camera.radius to use as delta when pinch zoom is used. + */ + get: function () { + var pointers = this.inputs.attached["pointers"]; + if (pointers) { + return pointers.pinchDeltaPercentage; + } + return 0; + }, + set: function (value) { + var pointers = this.inputs.attached["pointers"]; + if (pointers) { + pointers.pinchDeltaPercentage = value; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", { + /** + * Gets or Set the pointer panning sensibility or how fast is the camera moving. + */ + get: function () { + var pointers = this.inputs.attached["pointers"]; + if (pointers) { + return pointers.panningSensibility; + } + return 0; + }, + set: function (value) { + var pointers = this.inputs.attached["pointers"]; + if (pointers) { + pointers.panningSensibility = value; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ArcRotateCamera.prototype, "keysUp", { + /** + * Gets or Set the list of keyboard keys used to control beta angle in a positive direction. + */ + get: function () { + var keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + return keyboard.keysUp; + } + return []; + }, + set: function (value) { + var keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + keyboard.keysUp = value; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ArcRotateCamera.prototype, "keysDown", { + /** + * Gets or Set the list of keyboard keys used to control beta angle in a negative direction. + */ + get: function () { + var keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + return keyboard.keysDown; + } + return []; + }, + set: function (value) { + var keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + keyboard.keysDown = value; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", { + /** + * Gets or Set the list of keyboard keys used to control alpha angle in a negative direction. + */ + get: function () { + var keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + return keyboard.keysLeft; + } + return []; + }, + set: function (value) { + var keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + keyboard.keysLeft = value; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ArcRotateCamera.prototype, "keysRight", { + /** + * Gets or Set the list of keyboard keys used to control alpha angle in a positive direction. + */ + get: function () { + var keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + return keyboard.keysRight; + } + return []; + }, + set: function (value) { + var keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + keyboard.keysRight = value; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", { + /** + * Gets or Set the mouse wheel precision or how fast is the camera zooming. + */ + get: function () { + var mousewheel = this.inputs.attached["mousewheel"]; + if (mousewheel) { + return mousewheel.wheelPrecision; + } + return 0; + }, + set: function (value) { + var mousewheel = this.inputs.attached["mousewheel"]; + if (mousewheel) { + mousewheel.wheelPrecision = value; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", { + /** + * Gets or Set the mouse wheel delta percentage or how fast is the camera zooming. + * It will be used instead of pinchDeltaPrecision if different from 0. + * It defines the percentage of current camera.radius to use as delta when pinch zoom is used. + */ + get: function () { + var mousewheel = this.inputs.attached["mousewheel"]; + if (mousewheel) { + return mousewheel.wheelDeltaPercentage; + } + return 0; + }, + set: function (value) { + var mousewheel = this.inputs.attached["mousewheel"]; + if (mousewheel) { + mousewheel.wheelDeltaPercentage = value; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", { + /** + * Gets the bouncing behavior of the camera if it has been enabled. + * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior + */ + get: function () { + return this._bouncingBehavior; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", { + /** + * Defines if the bouncing behavior of the camera is enabled on the camera. + * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior + */ + get: function () { + return this._bouncingBehavior != null; + }, + set: function (value) { + if (value === this.useBouncingBehavior) { + return; + } + if (value) { + this._bouncingBehavior = new _Behaviors_Cameras_bouncingBehavior__WEBPACK_IMPORTED_MODULE_7__["BouncingBehavior"](); + this.addBehavior(this._bouncingBehavior); + } + else if (this._bouncingBehavior) { + this.removeBehavior(this._bouncingBehavior); + this._bouncingBehavior = null; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", { + /** + * Gets the framing behavior of the camera if it has been enabled. + * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior + */ + get: function () { + return this._framingBehavior; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", { + /** + * Defines if the framing behavior of the camera is enabled on the camera. + * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior + */ + get: function () { + return this._framingBehavior != null; + }, + set: function (value) { + if (value === this.useFramingBehavior) { + return; + } + if (value) { + this._framingBehavior = new _Behaviors_Cameras_framingBehavior__WEBPACK_IMPORTED_MODULE_8__["FramingBehavior"](); + this.addBehavior(this._framingBehavior); + } + else if (this._framingBehavior) { + this.removeBehavior(this._framingBehavior); + this._framingBehavior = null; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", { + /** + * Gets the auto rotation behavior of the camera if it has been enabled. + * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior + */ + get: function () { + return this._autoRotationBehavior; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", { + /** + * Defines if the auto rotation behavior of the camera is enabled on the camera. + * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior + */ + get: function () { + return this._autoRotationBehavior != null; + }, + set: function (value) { + if (value === this.useAutoRotationBehavior) { + return; + } + if (value) { + this._autoRotationBehavior = new _Behaviors_Cameras_autoRotationBehavior__WEBPACK_IMPORTED_MODULE_6__["AutoRotationBehavior"](); + this.addBehavior(this._autoRotationBehavior); + } + else if (this._autoRotationBehavior) { + this.removeBehavior(this._autoRotationBehavior); + this._autoRotationBehavior = null; + } + }, + enumerable: true, + configurable: true + }); + // Cache + /** @hidden */ + ArcRotateCamera.prototype._initCache = function () { + _super.prototype._initCache.call(this); + this._cache._target = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); + this._cache.alpha = undefined; + this._cache.beta = undefined; + this._cache.radius = undefined; + this._cache.targetScreenOffset = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector2"].Zero(); + }; + /** @hidden */ + ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) { + if (!ignoreParentClass) { + _super.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); + }; + ArcRotateCamera.prototype._getTargetPosition = function () { + if (this._targetHost && this._targetHost.getAbsolutePosition) { + var pos = this._targetHost.absolutePosition; + if (this._targetBoundingCenter) { + pos.addToRef(this._targetBoundingCenter, this._target); + } + else { + this._target.copyFrom(pos); + } + } + var lockedTargetPosition = this._getLockedTargetPosition(); + if (lockedTargetPosition) { + return lockedTargetPosition; + } + return this._target; + }; + /** + * Stores the current state of the camera (alpha, beta, radius and target) + * @returns the camera itself + */ + ArcRotateCamera.prototype.storeState = function () { + this._storedAlpha = this.alpha; + this._storedBeta = this.beta; + this._storedRadius = this.radius; + this._storedTarget = this._getTargetPosition().clone(); + return _super.prototype.storeState.call(this); + }; + /** + * @hidden + * Restored camera state. You must call storeState() first + */ + ArcRotateCamera.prototype._restoreStateValues = function () { + if (!_super.prototype._restoreStateValues.call(this)) { + return false; + } + this.alpha = this._storedAlpha; + this.beta = this._storedBeta; + this.radius = this._storedRadius; + this.setTarget(this._storedTarget.clone()); + this.inertialAlphaOffset = 0; + this.inertialBetaOffset = 0; + this.inertialRadiusOffset = 0; + this.inertialPanningX = 0; + this.inertialPanningY = 0; + return true; + }; + // Synchronized + /** @hidden */ + ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () { + if (!_super.prototype._isSynchronizedViewMatrix.call(this)) { + return false; + } + return this._cache._target.equals(this._getTargetPosition()) + && this._cache.alpha === this.alpha + && this._cache.beta === this.beta + && this._cache.radius === this.radius + && this._cache.targetScreenOffset.equals(this.targetScreenOffset); + }; + /** + * Attached controls to the current camera. + * @param element Defines the element the controls should be listened from + * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) + * @param useCtrlForPanning Defines whether ctrl is used for paning within the controls + * @param panningMouseButton Defines whether panning is allowed through mouse click button + */ + ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) { + var _this = this; + if (useCtrlForPanning === void 0) { useCtrlForPanning = true; } + if (panningMouseButton === void 0) { panningMouseButton = 2; } + this._useCtrlForPanning = useCtrlForPanning; + this._panningMouseButton = panningMouseButton; + this.inputs.attachElement(element, noPreventDefault); + this._reset = function () { + _this.inertialAlphaOffset = 0; + _this.inertialBetaOffset = 0; + _this.inertialRadiusOffset = 0; + _this.inertialPanningX = 0; + _this.inertialPanningY = 0; + }; + }; + /** + * Detach the current controls from the camera. + * The camera will stop reacting to inputs. + * @param element Defines the element to stop listening the inputs from + */ + ArcRotateCamera.prototype.detachControl = function (element) { + this.inputs.detachElement(element); + if (this._reset) { + this._reset(); + } + }; + /** @hidden */ + ArcRotateCamera.prototype._checkInputs = function () { + //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called. + if (this._collisionTriggered) { + return; + } + this.inputs.checkInputs(); + // Inertia + if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) { + var inertialAlphaOffset = this.inertialAlphaOffset; + if (this.beta <= 0) { + inertialAlphaOffset *= -1; + } + if (this.getScene().useRightHandedSystem) { + inertialAlphaOffset *= -1; + } + if (this.parent && this.parent._getWorldMatrixDeterminant() < 0) { + inertialAlphaOffset *= -1; + } + this.alpha += inertialAlphaOffset; + this.beta += this.inertialBetaOffset; + this.radius -= this.inertialRadiusOffset; + this.inertialAlphaOffset *= this.inertia; + this.inertialBetaOffset *= this.inertia; + this.inertialRadiusOffset *= this.inertia; + if (Math.abs(this.inertialAlphaOffset) < _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Epsilon"]) { + this.inertialAlphaOffset = 0; + } + if (Math.abs(this.inertialBetaOffset) < _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Epsilon"]) { + this.inertialBetaOffset = 0; + } + if (Math.abs(this.inertialRadiusOffset) < this.speed * _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Epsilon"]) { + this.inertialRadiusOffset = 0; + } + } + // Panning inertia + if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) { + if (!this._localDirection) { + this._localDirection = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(); + this._transformedDirection = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(); + } + this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY); + this._localDirection.multiplyInPlace(this.panningAxis); + this._viewMatrix.invertToRef(this._cameraTransformMatrix); + _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection); + //Eliminate y if map panning is enabled (panningAxis == 1,0,1) + if (!this.panningAxis.y) { + this._transformedDirection.y = 0; + } + if (!this._targetHost) { + if (this.panningDistanceLimit) { + this._transformedDirection.addInPlace(this._target); + var distanceSquared = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].DistanceSquared(this._transformedDirection, this.panningOriginTarget); + if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) { + this._target.copyFrom(this._transformedDirection); + } + } + else { + this._target.addInPlace(this._transformedDirection); + } + } + this.inertialPanningX *= this.panningInertia; + this.inertialPanningY *= this.panningInertia; + if (Math.abs(this.inertialPanningX) < this.speed * _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Epsilon"]) { + this.inertialPanningX = 0; + } + if (Math.abs(this.inertialPanningY) < this.speed * _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Epsilon"]) { + this.inertialPanningY = 0; + } + } + // Limits + this._checkLimits(); + _super.prototype._checkInputs.call(this); + }; + ArcRotateCamera.prototype._checkLimits = function () { + if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) { + if (this.allowUpsideDown && this.beta > Math.PI) { + this.beta = this.beta - (2 * Math.PI); + } + } + else { + if (this.beta < this.lowerBetaLimit) { + this.beta = this.lowerBetaLimit; + } + } + if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) { + if (this.allowUpsideDown && this.beta < -Math.PI) { + this.beta = this.beta + (2 * Math.PI); + } + } + else { + if (this.beta > this.upperBetaLimit) { + this.beta = this.upperBetaLimit; + } + } + if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) { + this.alpha = this.lowerAlphaLimit; + } + if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) { + this.alpha = this.upperAlphaLimit; + } + if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) { + this.radius = this.lowerRadiusLimit; + this.inertialRadiusOffset = 0; + } + if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) { + this.radius = this.upperRadiusLimit; + this.inertialRadiusOffset = 0; + } + }; + /** + * Rebuilds angles (alpha, beta) and radius from the give position and target + */ + ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () { + this._position.subtractToRef(this._getTargetPosition(), this._computationVector); + // need to rotate to Y up equivalent if up vector not Axis.Y + if (this._upVector.x !== 0 || this._upVector.y !== 1.0 || this._upVector.z !== 0) { + _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformCoordinatesToRef(this._computationVector, this._upToYMatrix, this._computationVector); + } + this.radius = this._computationVector.length(); + if (this.radius === 0) { + this.radius = 0.0001; // Just to avoid division by zero + } + // Alpha + if (this._computationVector.x === 0 && this._computationVector.z === 0) { + this.alpha = Math.PI / 2; // avoid division by zero when looking along up axis, and set to acos(0) + } + else { + this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2))); + } + if (this._computationVector.z < 0) { + this.alpha = 2 * Math.PI - this.alpha; + } + // Beta + this.beta = Math.acos(this._computationVector.y / this.radius); + this._checkLimits(); + }; + /** + * Use a position to define the current camera related information like aplha, beta and radius + * @param position Defines the position to set the camera at + */ + ArcRotateCamera.prototype.setPosition = function (position) { + if (this._position.equals(position)) { + return; + } + this._position.copyFrom(position); + this.rebuildAnglesAndRadius(); + }; + /** + * Defines the target the camera should look at. + * This will automatically adapt alpha beta and radius to fit within the new target. + * @param target Defines the new target as a Vector or a mesh + * @param toBoundingCenter In case of a mesh target, defines wether to target the mesh position or its bounding information center + * @param allowSamePosition If false, prevents reapplying the new computed position if it is identical to the current one (optim) + */ + ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) { + if (toBoundingCenter === void 0) { toBoundingCenter = false; } + if (allowSamePosition === void 0) { allowSamePosition = false; } + if (target.getBoundingInfo) { + if (toBoundingCenter) { + this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone(); + } + else { + this._targetBoundingCenter = null; + } + target.computeWorldMatrix(); + this._targetHost = target; + this._target = this._getTargetPosition(); + this.onMeshTargetChangedObservable.notifyObservers(this._targetHost); + } + else { + var newTarget = target; + var currentTarget = this._getTargetPosition(); + if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) { + return; + } + this._targetHost = null; + this._target = newTarget; + this._targetBoundingCenter = null; + this.onMeshTargetChangedObservable.notifyObservers(null); + } + this.rebuildAnglesAndRadius(); + }; + /** @hidden */ + ArcRotateCamera.prototype._getViewMatrix = function () { + // Compute + var cosa = Math.cos(this.alpha); + var sina = Math.sin(this.alpha); + var cosb = Math.cos(this.beta); + var sinb = Math.sin(this.beta); + if (sinb === 0) { + sinb = 0.0001; + } + var target = this._getTargetPosition(); + this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb); + // Rotate according to up vector + if (this._upVector.x !== 0 || this._upVector.y !== 1.0 || this._upVector.z !== 0) { + _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformCoordinatesToRef(this._computationVector, this._YToUpMatrix, this._computationVector); + } + target.addToRef(this._computationVector, this._newPosition); + if (this.getScene().collisionsEnabled && this.checkCollisions) { + var coordinator = this.getScene().collisionCoordinator; + if (!this._collider) { + this._collider = coordinator.createCollider(); + } + this._collider._radius = this.collisionRadius; + this._newPosition.subtractToRef(this._position, this._collisionVelocity); + this._collisionTriggered = true; + coordinator.getNewPosition(this._position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId); + } + else { + this._position.copyFrom(this._newPosition); + var up = this.upVector; + if (this.allowUpsideDown && sinb < 0) { + up = up.clone(); + up = up.negate(); + } + this._computeViewMatrix(this._position, target, up); + this._viewMatrix.addAtIndex(12, this.targetScreenOffset.x); + this._viewMatrix.addAtIndex(13, this.targetScreenOffset.y); + } + this._currentTarget = target; + return this._viewMatrix; + }; + /** + * Zooms on a mesh to be at the min distance where we could see it fully in the current viewport. + * @param meshes Defines the mesh to zoom on + * @param doNotUpdateMaxZ Defines whether or not maxZ should be updated whilst zooming on the mesh (this can happen if the mesh is big and the maxradius pretty small for instance) + */ + ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) { + if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; } + meshes = meshes || this.getScene().meshes; + var minMaxVector = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_5__["Mesh"].MinMax(meshes); + var distance = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Distance(minMaxVector.min, minMaxVector.max); + this.radius = distance * this.zoomOnFactor; + this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ); + }; + /** + * Focus on a mesh or a bounding box. This adapts the target and maxRadius if necessary but does not update the current radius. + * The target will be changed but the radius + * @param meshesOrMinMaxVectorAndDistance Defines the mesh or bounding info to focus on + * @param doNotUpdateMaxZ Defines whether or not maxZ should be updated whilst zooming on the mesh (this can happen if the mesh is big and the maxradius pretty small for instance) + */ + ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) { + if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; } + var meshesOrMinMaxVector; + var distance; + if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes + var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes; + meshesOrMinMaxVector = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_5__["Mesh"].MinMax(meshes); + distance = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max); + } + else { //minMaxVector and distance + var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance; + meshesOrMinMaxVector = minMaxVectorAndDistance; + distance = minMaxVectorAndDistance.distance; + } + this._target = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_5__["Mesh"].Center(meshesOrMinMaxVector); + if (!doNotUpdateMaxZ) { + this.maxZ = distance * 2; + } + }; + /** + * @override + * Override Camera.createRigCamera + */ + ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) { + var alphaShift = 0; + switch (this.cameraRigMode) { + case _camera__WEBPACK_IMPORTED_MODULE_9__["Camera"].RIG_MODE_STEREOSCOPIC_ANAGLYPH: + case _camera__WEBPACK_IMPORTED_MODULE_9__["Camera"].RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL: + case _camera__WEBPACK_IMPORTED_MODULE_9__["Camera"].RIG_MODE_STEREOSCOPIC_OVERUNDER: + case _camera__WEBPACK_IMPORTED_MODULE_9__["Camera"].RIG_MODE_VR: + alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1); + break; + case _camera__WEBPACK_IMPORTED_MODULE_9__["Camera"].RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED: + alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1); + break; + } + var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene()); + rigCam._cameraRigParams = {}; + return rigCam; + }; + /** + * @hidden + * @override + * Override Camera._updateRigCameras + */ + ArcRotateCamera.prototype._updateRigCameras = function () { + var camLeft = this._rigCameras[0]; + var camRight = this._rigCameras[1]; + camLeft.beta = camRight.beta = this.beta; + switch (this.cameraRigMode) { + case _camera__WEBPACK_IMPORTED_MODULE_9__["Camera"].RIG_MODE_STEREOSCOPIC_ANAGLYPH: + case _camera__WEBPACK_IMPORTED_MODULE_9__["Camera"].RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL: + case _camera__WEBPACK_IMPORTED_MODULE_9__["Camera"].RIG_MODE_STEREOSCOPIC_OVERUNDER: + case _camera__WEBPACK_IMPORTED_MODULE_9__["Camera"].RIG_MODE_VR: + camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle; + camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle; + break; + case _camera__WEBPACK_IMPORTED_MODULE_9__["Camera"].RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED: + camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle; + camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle; + break; + } + _super.prototype._updateRigCameras.call(this); + }; + /** + * Destroy the camera and release the current resources hold by it. + */ + ArcRotateCamera.prototype.dispose = function () { + this.inputs.clear(); + _super.prototype.dispose.call(this); + }; + /** + * Gets the current object class name. + * @return the class name + */ + ArcRotateCamera.prototype.getClassName = function () { + return "ArcRotateCamera"; + }; + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ArcRotateCamera.prototype, "alpha", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ArcRotateCamera.prototype, "beta", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ArcRotateCamera.prototype, "radius", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsVector3"])("target") + ], ArcRotateCamera.prototype, "_target", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsVector3"])("upVector") + ], ArcRotateCamera.prototype, "_upVector", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ArcRotateCamera.prototype, "upperBetaLimit", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ArcRotateCamera.prototype, "inertialPanningX", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ArcRotateCamera.prototype, "inertialPanningY", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsVector3"])() + ], ArcRotateCamera.prototype, "panningOriginTarget", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ArcRotateCamera.prototype, "panningInertia", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ArcRotateCamera.prototype, "zoomOnFactor", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ArcRotateCamera.prototype, "targetScreenOffset", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ArcRotateCamera.prototype, "allowUpsideDown", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ArcRotateCamera.prototype, "useInputToRestoreState", void 0); + return ArcRotateCamera; +}(_targetCamera__WEBPACK_IMPORTED_MODULE_10__["TargetCamera"])); + + + +/***/ }), + +/***/ "./Cameras/arcRotateCameraInputsManager.ts": +/*!*************************************************!*\ + !*** ./Cameras/arcRotateCameraInputsManager.ts ***! + \*************************************************/ +/*! exports provided: ArcRotateCameraInputsManager */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraInputsManager", function() { return ArcRotateCameraInputsManager; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Cameras_Inputs_arcRotateCameraPointersInput__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Cameras/Inputs/arcRotateCameraPointersInput */ "./Cameras/Inputs/arcRotateCameraPointersInput.ts"); +/* harmony import */ var _Cameras_Inputs_arcRotateCameraKeyboardMoveInput__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Cameras/Inputs/arcRotateCameraKeyboardMoveInput */ "./Cameras/Inputs/arcRotateCameraKeyboardMoveInput.ts"); +/* harmony import */ var _Cameras_Inputs_arcRotateCameraMouseWheelInput__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Cameras/Inputs/arcRotateCameraMouseWheelInput */ "./Cameras/Inputs/arcRotateCameraMouseWheelInput.ts"); +/* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); + + + + + +/** + * Default Inputs manager for the ArcRotateCamera. + * It groups all the default supported inputs for ease of use. + * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs + */ +var ArcRotateCameraInputsManager = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ArcRotateCameraInputsManager, _super); + /** + * Instantiates a new ArcRotateCameraInputsManager. + * @param camera Defines the camera the inputs belong to + */ + function ArcRotateCameraInputsManager(camera) { + return _super.call(this, camera) || this; + } + /** + * Add mouse wheel input support to the input manager. + * @returns the current input manager + */ + ArcRotateCameraInputsManager.prototype.addMouseWheel = function () { + this.add(new _Cameras_Inputs_arcRotateCameraMouseWheelInput__WEBPACK_IMPORTED_MODULE_3__["ArcRotateCameraMouseWheelInput"]()); + return this; + }; + /** + * Add pointers input support to the input manager. + * @returns the current input manager + */ + ArcRotateCameraInputsManager.prototype.addPointers = function () { + this.add(new _Cameras_Inputs_arcRotateCameraPointersInput__WEBPACK_IMPORTED_MODULE_1__["ArcRotateCameraPointersInput"]()); + return this; + }; + /** + * Add keyboard input support to the input manager. + * @returns the current input manager + */ + ArcRotateCameraInputsManager.prototype.addKeyboard = function () { + this.add(new _Cameras_Inputs_arcRotateCameraKeyboardMoveInput__WEBPACK_IMPORTED_MODULE_2__["ArcRotateCameraKeyboardMoveInput"]()); + return this; + }; + return ArcRotateCameraInputsManager; +}(_Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_4__["CameraInputsManager"])); + + + +/***/ }), + +/***/ "./Cameras/camera.ts": +/*!***************************!*\ + !*** ./Cameras/camera.ts ***! + \***************************/ +/*! exports provided: Camera */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Camera", function() { return Camera; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _Misc_smartArray__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/smartArray */ "./Misc/smartArray.ts"); +/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Misc/tools */ "./Misc/tools.ts"); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../node */ "./node.ts"); +/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts"); +/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Misc/typeStore */ "./Misc/typeStore.ts"); +/* harmony import */ var _Misc_devTools__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Misc/devTools */ "./Misc/devTools.ts"); + + + + + + + + + + +/** + * This is the base class of all the camera used in the application. + * @see http://doc.babylonjs.com/features/cameras + */ +var Camera = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Camera, _super); + /** + * Instantiates a new camera object. + * This should not be used directly but through the inherited cameras: ArcRotate, Free... + * @see http://doc.babylonjs.com/features/cameras + * @param name Defines the name of the camera in the scene + * @param position Defines the position of the camera + * @param scene Defines the scene the camera belongs too + * @param setActiveOnSceneIfNoneActive Defines if the camera should be set as active after creation if no other camera have been defined in the scene + */ + function Camera(name, position, scene, setActiveOnSceneIfNoneActive) { + if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; } + var _this = _super.call(this, name, scene) || this; + /** @hidden */ + _this._position = _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Vector3"].Zero(); + /** + * The vector the camera should consider as up. + * (default is Vector3(0, 1, 0) aka Vector3.Up()) + */ + _this.upVector = _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Vector3"].Up(); + /** + * Define the current limit on the left side for an orthographic camera + * In scene unit + */ + _this.orthoLeft = null; + /** + * Define the current limit on the right side for an orthographic camera + * In scene unit + */ + _this.orthoRight = null; + /** + * Define the current limit on the bottom side for an orthographic camera + * In scene unit + */ + _this.orthoBottom = null; + /** + * Define the current limit on the top side for an orthographic camera + * In scene unit + */ + _this.orthoTop = null; + /** + * Field Of View is set in Radians. (default is 0.8) + */ + _this.fov = 0.8; + /** + * Define the minimum distance the camera can see from. + * This is important to note that the depth buffer are not infinite and the closer it starts + * the more your scene might encounter depth fighting issue. + */ + _this.minZ = 1; + /** + * Define the maximum distance the camera can see to. + * This is important to note that the depth buffer are not infinite and the further it end + * the more your scene might encounter depth fighting issue. + */ + _this.maxZ = 10000.0; + /** + * Define the default inertia of the camera. + * This helps giving a smooth feeling to the camera movement. + */ + _this.inertia = 0.9; + /** + * Define the mode of the camera (Camera.PERSPECTIVE_CAMERA or Camera.PERSPECTIVE_ORTHOGRAPHIC) + */ + _this.mode = Camera.PERSPECTIVE_CAMERA; + /** + * Define wether the camera is intermediate. + * This is useful to not present the output directly to the screen in case of rig without post process for instance + */ + _this.isIntermediate = false; + /** + * Define the viewport of the camera. + * This correspond to the portion of the screen the camera will render to in normalized 0 to 1 unit. + */ + _this.viewport = new _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Viewport"](0, 0, 1.0, 1.0); + /** + * Restricts the camera to viewing objects with the same layerMask. + * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0 + */ + _this.layerMask = 0x0FFFFFFF; + /** + * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED) + */ + _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED; + /** + * Rig mode of the camera. + * This is useful to create the camera with two "eyes" instead of one to create VR or stereoscopic scenes. + * This is normally controlled byt the camera themselves as internal use. + */ + _this.cameraRigMode = Camera.RIG_MODE_NONE; + /** + * Defines the list of custom render target which are rendered to and then used as the input to this camera's render. Eg. display another camera view on a TV in the main scene + * This is pretty helpfull if you wish to make a camera render to a texture you could reuse somewhere + * else in the scene. + */ + _this.customRenderTargets = new Array(); + /** + * When set, the camera will render to this render target instead of the default canvas + */ + _this.outputRenderTarget = null; + /** + * Observable triggered when the camera view matrix has changed. + */ + _this.onViewMatrixChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_4__["Observable"](); + /** + * Observable triggered when the camera Projection matrix has changed. + */ + _this.onProjectionMatrixChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_4__["Observable"](); + /** + * Observable triggered when the inputs have been processed. + */ + _this.onAfterCheckInputsObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_4__["Observable"](); + /** + * Observable triggered when reset has been called and applied to the camera. + */ + _this.onRestoreStateObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_4__["Observable"](); + /** @hidden */ + _this._rigCameras = new Array(); + _this._webvrViewMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Matrix"].Identity(); + /** @hidden */ + _this._skipRendering = false; + /** @hidden */ + _this._projectionMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Matrix"](); + /** @hidden */ + _this._postProcesses = new Array(); + /** @hidden */ + _this._activeMeshes = new _Misc_smartArray__WEBPACK_IMPORTED_MODULE_2__["SmartArray"](256); + _this._globalPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Vector3"].Zero(); + /** @hidden */ + _this._computedViewMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Matrix"].Identity(); + _this._doNotComputeProjectionMatrix = false; + _this._transformMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Matrix"].Zero(); + _this._refreshFrustumPlanes = true; + /** @hidden */ + _this._isCamera = true; + /** @hidden */ + _this._isLeftCamera = false; + /** @hidden */ + _this._isRightCamera = true; + _this.getScene().addCamera(_this); + if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) { + _this.getScene().activeCamera = _this; + } + _this.position = position; + return _this; + } + Object.defineProperty(Camera.prototype, "position", { + /** + * Define the current local position of the camera in the scene + */ + get: function () { + return this._position; + }, + set: function (newPosition) { + this._position = newPosition; + }, + enumerable: true, + configurable: true + }); + /** + * Store current camera state (fov, position, etc..) + * @returns the camera + */ + Camera.prototype.storeState = function () { + this._stateStored = true; + this._storedFov = this.fov; + return this; + }; + /** + * Restores the camera state values if it has been stored. You must call storeState() first + */ + Camera.prototype._restoreStateValues = function () { + if (!this._stateStored) { + return false; + } + this.fov = this._storedFov; + return true; + }; + /** + * Restored camera state. You must call storeState() first. + * @returns true if restored and false otherwise + */ + Camera.prototype.restoreState = function () { + if (this._restoreStateValues()) { + this.onRestoreStateObservable.notifyObservers(this); + return true; + } + return false; + }; + /** + * Gets the class name of the camera. + * @returns the class name + */ + Camera.prototype.getClassName = function () { + return "Camera"; + }; + /** + * Gets a string representation of the camera useful for debug purpose. + * @param fullDetails Defines that a more verboe level of logging is required + * @returns the string representation + */ + Camera.prototype.toString = function (fullDetails) { + var ret = "Name: " + this.name; + ret += ", type: " + this.getClassName(); + if (this.animations) { + for (var i = 0; i < this.animations.length; i++) { + ret += ", animation[0]: " + this.animations[i].toString(fullDetails); + } + } + if (fullDetails) { + } + return ret; + }; + Object.defineProperty(Camera.prototype, "globalPosition", { + /** + * Gets the current world space position of the camera. + */ + get: function () { + return this._globalPosition; + }, + enumerable: true, + configurable: true + }); + /** + * Gets the list of active meshes this frame (meshes no culled or excluded by lod s in the frame) + * @returns the active meshe list + */ + Camera.prototype.getActiveMeshes = function () { + return this._activeMeshes; + }; + /** + * Check wether a mesh is part of the current active mesh list of the camera + * @param mesh Defines the mesh to check + * @returns true if active, false otherwise + */ + Camera.prototype.isActiveMesh = function (mesh) { + return (this._activeMeshes.indexOf(mesh) !== -1); + }; + /** + * Is this camera ready to be used/rendered + * @param completeCheck defines if a complete check (including post processes) has to be done (false by default) + * @return true if the camera is ready + */ + Camera.prototype.isReady = function (completeCheck) { + if (completeCheck === void 0) { completeCheck = false; } + if (completeCheck) { + for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) { + var pp = _a[_i]; + if (pp && !pp.isReady()) { + return false; + } + } + } + return _super.prototype.isReady.call(this, completeCheck); + }; + /** @hidden */ + Camera.prototype._initCache = function () { + _super.prototype._initCache.call(this); + this._cache.position = new _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Vector3"](Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); + this._cache.upVector = new _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Vector3"](Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); + this._cache.mode = undefined; + this._cache.minZ = undefined; + this._cache.maxZ = undefined; + this._cache.fov = undefined; + this._cache.fovMode = undefined; + this._cache.aspectRatio = undefined; + this._cache.orthoLeft = undefined; + this._cache.orthoRight = undefined; + this._cache.orthoBottom = undefined; + this._cache.orthoTop = undefined; + this._cache.renderWidth = undefined; + this._cache.renderHeight = undefined; + }; + /** @hidden */ + Camera.prototype._updateCache = function (ignoreParentClass) { + if (!ignoreParentClass) { + _super.prototype._updateCache.call(this); + } + this._cache.position.copyFrom(this.position); + this._cache.upVector.copyFrom(this.upVector); + }; + /** @hidden */ + Camera.prototype._isSynchronized = function () { + return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix(); + }; + /** @hidden */ + Camera.prototype._isSynchronizedViewMatrix = function () { + if (!_super.prototype._isSynchronized.call(this)) { + return false; + } + return this._cache.position.equals(this.position) + && this._cache.upVector.equals(this.upVector) + && this.isSynchronizedWithParent(); + }; + /** @hidden */ + Camera.prototype._isSynchronizedProjectionMatrix = function () { + var check = this._cache.mode === this.mode + && this._cache.minZ === this.minZ + && this._cache.maxZ === this.maxZ; + if (!check) { + return false; + } + var engine = this.getEngine(); + if (this.mode === Camera.PERSPECTIVE_CAMERA) { + check = this._cache.fov === this.fov + && this._cache.fovMode === this.fovMode + && this._cache.aspectRatio === engine.getAspectRatio(this); + } + else { + check = this._cache.orthoLeft === this.orthoLeft + && this._cache.orthoRight === this.orthoRight + && this._cache.orthoBottom === this.orthoBottom + && this._cache.orthoTop === this.orthoTop + && this._cache.renderWidth === engine.getRenderWidth() + && this._cache.renderHeight === engine.getRenderHeight(); + } + return check; + }; + /** + * Attach the input controls to a specific dom element to get the input from. + * @param element Defines the element the controls should be listened from + * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) + */ + Camera.prototype.attachControl = function (element, noPreventDefault) { + }; + /** + * Detach the current controls from the specified dom element. + * @param element Defines the element to stop listening the inputs from + */ + Camera.prototype.detachControl = function (element) { + }; + /** + * Update the camera state according to the different inputs gathered during the frame. + */ + Camera.prototype.update = function () { + this._checkInputs(); + if (this.cameraRigMode !== Camera.RIG_MODE_NONE) { + this._updateRigCameras(); + } + }; + /** @hidden */ + Camera.prototype._checkInputs = function () { + this.onAfterCheckInputsObservable.notifyObservers(this); + }; + Object.defineProperty(Camera.prototype, "rigCameras", { + /** @hidden */ + get: function () { + return this._rigCameras; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Camera.prototype, "rigPostProcess", { + /** + * Gets the post process used by the rig cameras + */ + get: function () { + return this._rigPostProcess; + }, + enumerable: true, + configurable: true + }); + /** + * Internal, gets the first post proces. + * @returns the first post process to be run on this camera. + */ + Camera.prototype._getFirstPostProcess = function () { + for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) { + if (this._postProcesses[ppIndex] !== null) { + return this._postProcesses[ppIndex]; + } + } + return null; + }; + Camera.prototype._cascadePostProcessesToRigCams = function () { + // invalidate framebuffer + var firstPostProcess = this._getFirstPostProcess(); + if (firstPostProcess) { + firstPostProcess.markTextureDirty(); + } + // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera + for (var i = 0, len = this._rigCameras.length; i < len; i++) { + var cam = this._rigCameras[i]; + var rigPostProcess = cam._rigPostProcess; + // for VR rig, there does not have to be a post process + if (rigPostProcess) { + var isPass = rigPostProcess.getEffectName() === "pass"; + if (isPass) { + // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses + cam.isIntermediate = this._postProcesses.length === 0; + } + cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess); + rigPostProcess.markTextureDirty(); + } + else { + cam._postProcesses = this._postProcesses.slice(0); + } + } + }; + /** + * Attach a post process to the camera. + * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess + * @param postProcess The post process to attach to the camera + * @param insertAt The position of the post process in case several of them are in use in the scene + * @returns the position the post process has been inserted at + */ + Camera.prototype.attachPostProcess = function (postProcess, insertAt) { + if (insertAt === void 0) { insertAt = null; } + if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_7__["Logger"].Error("You're trying to reuse a post process not defined as reusable."); + return 0; + } + if (insertAt == null || insertAt < 0) { + this._postProcesses.push(postProcess); + } + else if (this._postProcesses[insertAt] === null) { + this._postProcesses[insertAt] = postProcess; + } + else { + this._postProcesses.splice(insertAt, 0, postProcess); + } + this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated + return this._postProcesses.indexOf(postProcess); + }; + /** + * Detach a post process to the camera. + * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess + * @param postProcess The post process to detach from the camera + */ + Camera.prototype.detachPostProcess = function (postProcess) { + var idx = this._postProcesses.indexOf(postProcess); + if (idx !== -1) { + this._postProcesses[idx] = null; + } + this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated + }; + /** + * Gets the current world matrix of the camera + */ + Camera.prototype.getWorldMatrix = function () { + if (this._isSynchronizedViewMatrix()) { + return this._worldMatrix; + } + // Getting the the view matrix will also compute the world matrix. + this.getViewMatrix(); + return this._worldMatrix; + }; + /** @hidden */ + Camera.prototype._getViewMatrix = function () { + return _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Matrix"].Identity(); + }; + /** + * Gets the current view matrix of the camera. + * @param force forces the camera to recompute the matrix without looking at the cached state + * @returns the view matrix + */ + Camera.prototype.getViewMatrix = function (force) { + if (!force && this._isSynchronizedViewMatrix()) { + return this._computedViewMatrix; + } + this.updateCache(); + this._computedViewMatrix = this._getViewMatrix(); + this._currentRenderId = this.getScene().getRenderId(); + this._childUpdateId++; + this._refreshFrustumPlanes = true; + if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) { + this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix); + } + // Notify parent camera if rig camera is changed + if (this.parent && this.parent.onViewMatrixChangedObservable) { + this.parent.onViewMatrixChangedObservable.notifyObservers(this.parent); + } + this.onViewMatrixChangedObservable.notifyObservers(this); + this._computedViewMatrix.invertToRef(this._worldMatrix); + return this._computedViewMatrix; + }; + /** + * Freeze the projection matrix. + * It will prevent the cache check of the camera projection compute and can speed up perf + * if no parameter of the camera are meant to change + * @param projection Defines manually a projection if necessary + */ + Camera.prototype.freezeProjectionMatrix = function (projection) { + this._doNotComputeProjectionMatrix = true; + if (projection !== undefined) { + this._projectionMatrix = projection; + } + }; + /** + * Unfreeze the projection matrix if it has previously been freezed by freezeProjectionMatrix. + */ + Camera.prototype.unfreezeProjectionMatrix = function () { + this._doNotComputeProjectionMatrix = false; + }; + /** + * Gets the current projection matrix of the camera. + * @param force forces the camera to recompute the matrix without looking at the cached state + * @returns the projection matrix + */ + Camera.prototype.getProjectionMatrix = function (force) { + if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) { + return this._projectionMatrix; + } + // Cache + this._cache.mode = this.mode; + this._cache.minZ = this.minZ; + this._cache.maxZ = this.maxZ; + // Matrix + this._refreshFrustumPlanes = true; + var engine = this.getEngine(); + var scene = this.getScene(); + if (this.mode === Camera.PERSPECTIVE_CAMERA) { + this._cache.fov = this.fov; + this._cache.fovMode = this.fovMode; + this._cache.aspectRatio = engine.getAspectRatio(this); + if (this.minZ <= 0) { + this.minZ = 0.1; + } + if (scene.useRightHandedSystem) { + _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Matrix"].PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED); + } + else { + _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Matrix"].PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED); + } + } + else { + var halfWidth = engine.getRenderWidth() / 2.0; + var halfHeight = engine.getRenderHeight() / 2.0; + if (scene.useRightHandedSystem) { + _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Matrix"].OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix); + } + else { + _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Matrix"].OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, 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 = engine.getRenderWidth(); + this._cache.renderHeight = engine.getRenderHeight(); + } + this.onProjectionMatrixChangedObservable.notifyObservers(this); + return this._projectionMatrix; + }; + /** + * Gets the transformation matrix (ie. the multiplication of view by projection matrices) + * @returns a Matrix + */ + Camera.prototype.getTransformationMatrix = function () { + this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix); + return this._transformMatrix; + }; + Camera.prototype._updateFrustumPlanes = function () { + if (!this._refreshFrustumPlanes) { + return; + } + this.getTransformationMatrix(); + if (!this._frustumPlanes) { + this._frustumPlanes = _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Frustum"].GetPlanes(this._transformMatrix); + } + else { + _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Frustum"].GetPlanesToRef(this._transformMatrix, this._frustumPlanes); + } + this._refreshFrustumPlanes = false; + }; + /** + * Checks if a cullable object (mesh...) is in the camera frustum + * This checks the bounding box center. See isCompletelyInFrustum for a full bounding check + * @param target The object to check + * @param checkRigCameras If the rig cameras should be checked (eg. with webVR camera both eyes should be checked) (Default: false) + * @returns true if the object is in frustum otherwise false + */ + Camera.prototype.isInFrustum = function (target, checkRigCameras) { + if (checkRigCameras === void 0) { checkRigCameras = false; } + this._updateFrustumPlanes(); + if (checkRigCameras && this.rigCameras.length > 0) { + var result = false; + this.rigCameras.forEach(function (cam) { + cam._updateFrustumPlanes(); + result = result || target.isInFrustum(cam._frustumPlanes); + }); + return result; + } + else { + return target.isInFrustum(this._frustumPlanes); + } + }; + /** + * Checks if a cullable object (mesh...) is in the camera frustum + * Unlike isInFrustum this cheks the full bounding box + * @param target The object to check + * @returns true if the object is in frustum otherwise false + */ + Camera.prototype.isCompletelyInFrustum = function (target) { + this._updateFrustumPlanes(); + return target.isCompletelyInFrustum(this._frustumPlanes); + }; + /** + * Gets a ray in the forward direction from the camera. + * @param length Defines the length of the ray to create + * @param transform Defines the transform to apply to the ray, by default the world matrx is used to create a workd space ray + * @param origin Defines the start point of the ray which defaults to the camera position + * @returns the forward ray + */ + Camera.prototype.getForwardRay = function (length, transform, origin) { + if (length === void 0) { length = 100; } + throw _Misc_devTools__WEBPACK_IMPORTED_MODULE_9__["_DevTools"].WarnImport("Ray"); + }; + /** + * Releases resources associated with this node. + * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default) + * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default) + */ + Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) { + if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; } + // Observables + this.onViewMatrixChangedObservable.clear(); + this.onProjectionMatrixChangedObservable.clear(); + this.onAfterCheckInputsObservable.clear(); + this.onRestoreStateObservable.clear(); + // Inputs + if (this.inputs) { + this.inputs.clear(); + } + // Animations + this.getScene().stopAnimation(this); + // Remove from scene + this.getScene().removeCamera(this); + while (this._rigCameras.length > 0) { + var camera = this._rigCameras.pop(); + if (camera) { + camera.dispose(); + } + } + // Postprocesses + if (this._rigPostProcess) { + this._rigPostProcess.dispose(this); + this._rigPostProcess = null; + this._postProcesses = []; + } + else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) { + this._rigPostProcess = null; + this._postProcesses = []; + } + else { + var i = this._postProcesses.length; + while (--i >= 0) { + var postProcess = this._postProcesses[i]; + if (postProcess) { + postProcess.dispose(this); + } + } + } + // Render targets + var i = this.customRenderTargets.length; + while (--i >= 0) { + this.customRenderTargets[i].dispose(); + } + this.customRenderTargets = []; + // Active Meshes + this._activeMeshes.dispose(); + _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures); + }; + Object.defineProperty(Camera.prototype, "isLeftCamera", { + /** + * Gets the left camera of a rig setup in case of Rigged Camera + */ + get: function () { + return this._isLeftCamera; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Camera.prototype, "isRightCamera", { + /** + * Gets the right camera of a rig setup in case of Rigged Camera + */ + get: function () { + return this._isRightCamera; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Camera.prototype, "leftCamera", { + /** + * Gets the left camera of a rig setup in case of Rigged Camera + */ + get: function () { + if (this._rigCameras.length < 1) { + return null; + } + return this._rigCameras[0]; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Camera.prototype, "rightCamera", { + /** + * Gets the right camera of a rig setup in case of Rigged Camera + */ + get: function () { + if (this._rigCameras.length < 2) { + return null; + } + return this._rigCameras[1]; + }, + enumerable: true, + configurable: true + }); + /** + * Gets the left camera target of a rig setup in case of Rigged Camera + * @returns the target position + */ + Camera.prototype.getLeftTarget = function () { + if (this._rigCameras.length < 1) { + return null; + } + return this._rigCameras[0].getTarget(); + }; + /** + * Gets the right camera target of a rig setup in case of Rigged Camera + * @returns the target position + */ + Camera.prototype.getRightTarget = function () { + if (this._rigCameras.length < 2) { + return null; + } + return this._rigCameras[1].getTarget(); + }; + /** + * @hidden + */ + Camera.prototype.setCameraRigMode = function (mode, rigParams) { + if (this.cameraRigMode === mode) { + return; + } + while (this._rigCameras.length > 0) { + var camera = this._rigCameras.pop(); + if (camera) { + camera.dispose(); + } + } + this.cameraRigMode = mode; + this._cameraRigParams = {}; + //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target, + //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced + this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637; + this._cameraRigParams.stereoHalfAngle = _Misc_tools__WEBPACK_IMPORTED_MODULE_3__["Tools"].ToRadians(this._cameraRigParams.interaxialDistance / 0.0637); + // create the rig cameras, unless none + if (this.cameraRigMode !== Camera.RIG_MODE_NONE) { + var leftCamera = this.createRigCamera(this.name + "_L", 0); + if (leftCamera) { + leftCamera._isLeftCamera = true; + } + var rightCamera = this.createRigCamera(this.name + "_R", 1); + if (rightCamera) { + rightCamera._isRightCamera = true; + } + if (leftCamera && rightCamera) { + this._rigCameras.push(leftCamera); + this._rigCameras.push(rightCamera); + } + } + switch (this.cameraRigMode) { + case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH: + Camera._setStereoscopicAnaglyphRigMode(this); + break; + case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL: + case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED: + case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER: + Camera._setStereoscopicRigMode(this); + break; + case Camera.RIG_MODE_VR: + Camera._setVRRigMode(this, rigParams); + break; + case Camera.RIG_MODE_WEBVR: + Camera._setWebVRRigMode(this, rigParams); + break; + } + this._cascadePostProcessesToRigCams(); + this.update(); + }; + /** @hidden */ + Camera._setStereoscopicRigMode = function (camera) { + throw "Import Cameras/RigModes/stereoscopicRigMode before using stereoscopic rig mode"; + }; + /** @hidden */ + Camera._setStereoscopicAnaglyphRigMode = function (camera) { + throw "Import Cameras/RigModes/stereoscopicAnaglyphRigMode before using stereoscopic anaglyph rig mode"; + }; + /** @hidden */ + Camera._setVRRigMode = function (camera, rigParams) { + throw "Import Cameras/RigModes/vrRigMode before using VR rig mode"; + }; + /** @hidden */ + Camera._setWebVRRigMode = function (camera, rigParams) { + throw "Import Cameras/RigModes/WebVRRigMode before using Web VR rig mode"; + }; + /** @hidden */ + Camera.prototype._getVRProjectionMatrix = function () { + _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Matrix"].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); + return this._projectionMatrix; + }; + Camera.prototype._updateCameraRotationMatrix = function () { + //Here for WebVR + }; + Camera.prototype._updateWebVRCameraRotationMatrix = function () { + //Here for WebVR + }; + /** + * This function MUST be overwritten by the different WebVR cameras available. + * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right. + * @hidden + */ + Camera.prototype._getWebVRProjectionMatrix = function () { + return _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Matrix"].Identity(); + }; + /** + * This function MUST be overwritten by the different WebVR cameras available. + * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right. + * @hidden + */ + Camera.prototype._getWebVRViewMatrix = function () { + return _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Matrix"].Identity(); + }; + /** @hidden */ + Camera.prototype.setCameraRigParameter = function (name, value) { + if (!this._cameraRigParams) { + this._cameraRigParams = {}; + } + this._cameraRigParams[name] = value; + //provisionnally: + if (name === "interaxialDistance") { + this._cameraRigParams.stereoHalfAngle = _Misc_tools__WEBPACK_IMPORTED_MODULE_3__["Tools"].ToRadians(value / 0.0637); + } + }; + /** + * needs to be overridden by children so sub has required properties to be copied + * @hidden + */ + Camera.prototype.createRigCamera = function (name, cameraIndex) { + return null; + }; + /** + * May need to be overridden by children + * @hidden + */ + Camera.prototype._updateRigCameras = function () { + for (var i = 0; i < this._rigCameras.length; i++) { + this._rigCameras[i].minZ = this.minZ; + this._rigCameras[i].maxZ = this.maxZ; + this._rigCameras[i].fov = this.fov; + this._rigCameras[i].upVector.copyFrom(this.upVector); + } + // only update viewport when ANAGLYPH + if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) { + this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport; + } + }; + /** @hidden */ + Camera.prototype._setupInputs = function () { + }; + /** + * Serialiaze the camera setup to a json represention + * @returns the JSON representation + */ + Camera.prototype.serialize = function () { + var serializationObject = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(this); + // Type + serializationObject.type = this.getClassName(); + // Parent + if (this.parent) { + serializationObject.parentId = this.parent.id; + } + if (this.inputs) { + this.inputs.serialize(serializationObject); + } + // Animations + _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].AppendSerializedAnimations(this, serializationObject); + serializationObject.ranges = this.serializeAnimationRanges(); + return serializationObject; + }; + /** + * Clones the current camera. + * @param name The cloned camera name + * @returns the cloned camera + */ + Camera.prototype.clone = function (name) { + return _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this); + }; + /** + * Gets the direction of the camera relative to a given local axis. + * @param localAxis Defines the reference axis to provide a relative direction. + * @return the direction + */ + Camera.prototype.getDirection = function (localAxis) { + var result = _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Vector3"].Zero(); + this.getDirectionToRef(localAxis, result); + return result; + }; + /** + * Gets the direction of the camera relative to a given local axis into a passed vector. + * @param localAxis Defines the reference axis to provide a relative direction. + * @param result Defines the vector to store the result in + */ + Camera.prototype.getDirectionToRef = function (localAxis, result) { + _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Vector3"].TransformNormalToRef(localAxis, this.getWorldMatrix(), result); + }; + /** + * Gets a camera constructor for a given camera type + * @param type The type of the camera to construct (should be equal to one of the camera class name) + * @param name The name of the camera the result will be able to instantiate + * @param scene The scene the result will construct the camera in + * @param interaxial_distance In case of stereoscopic setup, the distance between both eyes + * @param isStereoscopicSideBySide In case of stereoscopic setup, should the sereo be side b side + * @returns a factory method to construc the camera + */ + Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) { + if (interaxial_distance === void 0) { interaxial_distance = 0; } + if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; } + var constructorFunc = _node__WEBPACK_IMPORTED_MODULE_6__["Node"].Construct(type, name, scene, { + interaxial_distance: interaxial_distance, + isStereoscopicSideBySide: isStereoscopicSideBySide + }); + if (constructorFunc) { + return constructorFunc; + } + // Default to universal camera + return function () { return Camera._createDefaultParsedCamera(name, scene); }; + }; + /** + * Compute the world matrix of the camera. + * @returns the camera workd matrix + */ + Camera.prototype.computeWorldMatrix = function () { + return this.getWorldMatrix(); + }; + /** + * Parse a JSON and creates the camera from the parsed information + * @param parsedCamera The JSON to parse + * @param scene The scene to instantiate the camera in + * @returns the newly constructed camera + */ + Camera.Parse = function (parsedCamera, scene) { + var type = parsedCamera.type; + var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide); + var camera = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(construct, parsedCamera, scene); + // Parent + if (parsedCamera.parentId) { + camera._waitingParentId = parsedCamera.parentId; + } + //If camera has an input manager, let it parse inputs settings + if (camera.inputs) { + camera.inputs.parse(parsedCamera); + camera._setupInputs(); + } + if (camera.setPosition) { // need to force position + camera.position.copyFromFloats(0, 0, 0); + camera.setPosition(_Maths_math__WEBPACK_IMPORTED_MODULE_5__["Vector3"].FromArray(parsedCamera.position)); + } + // Target + if (parsedCamera.target) { + if (camera.setTarget) { + camera.setTarget(_Maths_math__WEBPACK_IMPORTED_MODULE_5__["Vector3"].FromArray(parsedCamera.target)); + } + } + // Apply 3d rig, when found + if (parsedCamera.cameraRigMode) { + var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {}; + camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams); + } + // Animations + if (parsedCamera.animations) { + for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) { + var parsedAnimation = parsedCamera.animations[animationIndex]; + var internalClass = _Misc_typeStore__WEBPACK_IMPORTED_MODULE_8__["_TypeStore"].GetClass("BABYLON.Animation"); + if (internalClass) { + camera.animations.push(internalClass.Parse(parsedAnimation)); + } + } + _node__WEBPACK_IMPORTED_MODULE_6__["Node"].ParseAnimationRanges(camera, parsedCamera, scene); + } + if (parsedCamera.autoAnimate) { + scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0); + } + return camera; + }; + /** @hidden */ + Camera._createDefaultParsedCamera = function (name, scene) { + throw _Misc_devTools__WEBPACK_IMPORTED_MODULE_9__["_DevTools"].WarnImport("UniversalCamera"); + }; + /** + * This is the default projection mode used by the cameras. + * It helps recreating a feeling of perspective and better appreciate depth. + * This is the best way to simulate real life cameras. + */ + Camera.PERSPECTIVE_CAMERA = 0; + /** + * This helps creating camera with an orthographic mode. + * Orthographic is commonly used in engineering as a means to produce object specifications that communicate dimensions unambiguously, each line of 1 unit length (cm, meter..whatever) will appear to have the same length everywhere on the drawing. This allows the drafter to dimension only a subset of lines and let the reader know that other lines of that length on the drawing are also that length in reality. Every parallel line in the drawing is also parallel in the object. + */ + Camera.ORTHOGRAPHIC_CAMERA = 1; + /** + * This is the default FOV mode for perspective cameras. + * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum. + */ + Camera.FOVMODE_VERTICAL_FIXED = 0; + /** + * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum. + */ + Camera.FOVMODE_HORIZONTAL_FIXED = 1; + /** + * This specifies ther is no need for a camera rig. + * Basically only one eye is rendered corresponding to the camera. + */ + Camera.RIG_MODE_NONE = 0; + /** + * Simulates a camera Rig with one blue eye and one red eye. + * This can be use with 3d blue and red glasses. + */ + Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10; + /** + * Defines that both eyes of the camera will be rendered side by side with a parallel target. + */ + Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11; + /** + * Defines that both eyes of the camera will be rendered side by side with a none parallel target. + */ + Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12; + /** + * Defines that both eyes of the camera will be rendered over under each other. + */ + Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13; + /** + * Defines that both eyes of the camera should be renderered in a VR mode (carbox). + */ + Camera.RIG_MODE_VR = 20; + /** + * Defines that both eyes of the camera should be renderered in a VR mode (webVR). + */ + Camera.RIG_MODE_WEBVR = 21; + /** + * Custom rig mode allowing rig cameras to be populated manually with any number of cameras + */ + Camera.RIG_MODE_CUSTOM = 22; + /** + * Defines if by default attaching controls should prevent the default javascript event to continue. + */ + Camera.ForceAttachControlToAlwaysPreventDefault = false; + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsVector3"])("position") + ], Camera.prototype, "_position", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsVector3"])() + ], Camera.prototype, "upVector", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], Camera.prototype, "orthoLeft", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], Camera.prototype, "orthoRight", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], Camera.prototype, "orthoBottom", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], Camera.prototype, "orthoTop", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], Camera.prototype, "fov", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], Camera.prototype, "minZ", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], Camera.prototype, "maxZ", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], Camera.prototype, "inertia", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], Camera.prototype, "mode", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], Camera.prototype, "layerMask", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], Camera.prototype, "fovMode", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], Camera.prototype, "cameraRigMode", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], Camera.prototype, "interaxialDistance", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], Camera.prototype, "isStereoscopicSideBySide", void 0); + return Camera; +}(_node__WEBPACK_IMPORTED_MODULE_6__["Node"])); + + + +/***/ }), + +/***/ "./Cameras/cameraInputsManager.ts": +/*!****************************************!*\ + !*** ./Cameras/cameraInputsManager.ts ***! + \****************************************/ +/*! exports provided: CameraInputTypes, CameraInputsManager */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CameraInputTypes", function() { return CameraInputTypes; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CameraInputsManager", function() { return CameraInputsManager; }); +/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _camera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./camera */ "./Cameras/camera.ts"); + + + +/** + * @ignore + * This is a list of all the different input types that are available in the application. + * Fo instance: ArcRotateCameraGamepadInput... + */ +var CameraInputTypes = {}; +/** + * This represents the input manager used within a camera. + * It helps dealing with all the different kind of input attached to a camera. + * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs + */ +var CameraInputsManager = /** @class */ (function () { + /** + * Instantiate a new Camera Input Manager. + * @param camera Defines the camera the input manager blongs to + */ + function CameraInputsManager(camera) { + this.attached = {}; + this.camera = camera; + this.checkInputs = function () { }; + } + /** + * Add an input method to a camera + * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs + * @param input camera input method + */ + CameraInputsManager.prototype.add = function (input) { + var type = input.getSimpleName(); + if (this.attached[type]) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_0__["Logger"].Warn("camera input of type " + type + " already exists on camera"); + return; + } + this.attached[type] = input; + input.camera = this.camera; + //for checkInputs, we are dynamically creating a function + //the goal is to avoid the performance penalty of looping for inputs in the render loop + if (input.checkInputs) { + this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input)); + } + if (this.attachedElement) { + input.attachControl(this.attachedElement); + } + }; + /** + * Remove a specific input method from a camera + * example: camera.inputs.remove(camera.inputs.attached.mouse); + * @param inputToRemove camera input method + */ + CameraInputsManager.prototype.remove = function (inputToRemove) { + for (var cam in this.attached) { + var input = this.attached[cam]; + if (input === inputToRemove) { + input.detachControl(this.attachedElement); + input.camera = null; + delete this.attached[cam]; + this.rebuildInputCheck(); + } + } + }; + /** + * Remove a specific input type from a camera + * example: camera.inputs.remove("ArcRotateCameraGamepadInput"); + * @param inputType the type of the input to remove + */ + CameraInputsManager.prototype.removeByType = function (inputType) { + for (var cam in this.attached) { + var input = this.attached[cam]; + if (input.getClassName() === inputType) { + input.detachControl(this.attachedElement); + input.camera = null; + delete this.attached[cam]; + this.rebuildInputCheck(); + } + } + }; + CameraInputsManager.prototype._addCheckInputs = function (fn) { + var current = this.checkInputs; + return function () { + current(); + fn(); + }; + }; + /** + * Attach the input controls to the currently attached dom element to listen the events from. + * @param input Defines the input to attach + */ + CameraInputsManager.prototype.attachInput = function (input) { + if (this.attachedElement) { + input.attachControl(this.attachedElement, this.noPreventDefault); + } + }; + /** + * Attach the current manager inputs controls to a specific dom element to listen the events from. + * @param element Defines the dom element to collect the events from + * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) + */ + CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) { + if (noPreventDefault === void 0) { noPreventDefault = false; } + if (this.attachedElement) { + return; + } + noPreventDefault = _camera__WEBPACK_IMPORTED_MODULE_2__["Camera"].ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault; + this.attachedElement = element; + this.noPreventDefault = noPreventDefault; + for (var cam in this.attached) { + this.attached[cam].attachControl(element, noPreventDefault); + } + }; + /** + * Detach the current manager inputs controls from a specific dom element. + * @param element Defines the dom element to collect the events from + * @param disconnect Defines whether the input should be removed from the current list of attached inputs + */ + CameraInputsManager.prototype.detachElement = function (element, disconnect) { + if (disconnect === void 0) { disconnect = false; } + if (this.attachedElement !== element) { + return; + } + for (var cam in this.attached) { + this.attached[cam].detachControl(element); + if (disconnect) { + this.attached[cam].camera = null; + } + } + this.attachedElement = null; + }; + /** + * Rebuild the dynamic inputCheck function from the current list of + * defined inputs in the manager. + */ + CameraInputsManager.prototype.rebuildInputCheck = function () { + this.checkInputs = function () { }; + for (var cam in this.attached) { + var input = this.attached[cam]; + if (input.checkInputs) { + this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input)); + } + } + }; + /** + * Remove all attached input methods from a camera + */ + CameraInputsManager.prototype.clear = function () { + if (this.attachedElement) { + this.detachElement(this.attachedElement, true); + } + this.attached = {}; + this.attachedElement = null; + this.checkInputs = function () { }; + }; + /** + * Serialize the current input manager attached to a camera. + * This ensures than once parsed, + * the input associated to the camera will be identical to the current ones + * @param serializedCamera Defines the camera serialization JSON the input serialization should write to + */ + CameraInputsManager.prototype.serialize = function (serializedCamera) { + var inputs = {}; + for (var cam in this.attached) { + var input = this.attached[cam]; + var res = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(input); + inputs[input.getClassName()] = res; + } + serializedCamera.inputsmgr = inputs; + }; + /** + * Parses an input manager serialized JSON to restore the previous list of inputs + * and states associated to a camera. + * @param parsedCamera Defines the JSON to parse + */ + CameraInputsManager.prototype.parse = function (parsedCamera) { + var parsedInputs = parsedCamera.inputsmgr; + if (parsedInputs) { + this.clear(); + for (var n in parsedInputs) { + var construct = CameraInputTypes[n]; + if (construct) { + var parsedinput = parsedInputs[n]; + var input = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(function () { return new construct(); }, parsedinput, null); + this.add(input); + } + } + } + else { + //2016-03-08 this part is for managing backward compatibility + for (var n in this.attached) { + var construct = CameraInputTypes[this.attached[n].getClassName()]; + if (construct) { + var input = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(function () { return new construct(); }, parsedCamera, null); + this.remove(this.attached[n]); + this.add(input); + } + } + } + }; + return CameraInputsManager; +}()); + + + +/***/ }), + +/***/ "./Cameras/deviceOrientationCamera.ts": +/*!********************************************!*\ + !*** ./Cameras/deviceOrientationCamera.ts ***! + \********************************************/ +/*! exports provided: DeviceOrientationCamera */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DeviceOrientationCamera", function() { return DeviceOrientationCamera; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _freeCamera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./freeCamera */ "./Cameras/freeCamera.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../node */ "./node.ts"); +/* harmony import */ var _Inputs_freeCameraDeviceOrientationInput__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Inputs/freeCameraDeviceOrientationInput */ "./Cameras/Inputs/freeCameraDeviceOrientationInput.ts"); + + + + + +_node__WEBPACK_IMPORTED_MODULE_3__["Node"].AddNodeConstructor("DeviceOrientationCamera", function (name, scene) { + return function () { return new DeviceOrientationCamera(name, _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(), scene); }; +}); +// We're mainly based on the logic defined into the FreeCamera code +/** + * This is a camera specifically designed to react to device orientation events such as a modern mobile device + * being tilted forward or back and left or right. + */ +var DeviceOrientationCamera = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](DeviceOrientationCamera, _super); + /** + * Creates a new device orientation camera + * @param name The name of the camera + * @param position The start position camera + * @param scene The scene the camera belongs to + */ + function DeviceOrientationCamera(name, position, scene) { + var _this = _super.call(this, name, position, scene) || this; + _this._tmpDragQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Quaternion"](); + /** + * @hidden + * Disabled pointer input on first orientation sensor update (Default: true) + */ + _this._disablePointerInputWhenUsingDeviceOrientation = true; + _this._dragFactor = 0; + _this._quaternionCache = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Quaternion"](); + _this.inputs.addDeviceOrientation(); + // When the orientation sensor fires it's first event, disable mouse input + if (_this.inputs._deviceOrientationInput) { + _this.inputs._deviceOrientationInput._onDeviceOrientationChangedObservable.addOnce(function () { + if (_this._disablePointerInputWhenUsingDeviceOrientation) { + if (_this.inputs._mouseInput) { + _this.inputs._mouseInput._allowCameraRotation = false; + _this.inputs._mouseInput.onPointerMovedObservable.add(function (e) { + if (_this._dragFactor != 0) { + if (!_this._initialQuaternion) { + _this._initialQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Quaternion"](); + } + // Rotate the initial space around the y axis to allow users to "turn around" via touch/mouse + _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Quaternion"].FromEulerAnglesToRef(0, e.offsetX * _this._dragFactor, 0, _this._tmpDragQuaternion); + _this._initialQuaternion.multiplyToRef(_this._tmpDragQuaternion, _this._initialQuaternion); + } + }); + } + } + }); + } + return _this; + } + /** + * Enabled turning on the y axis when the orientation sensor is active + * @param dragFactor the factor that controls the turn speed (default: 1/300) + */ + DeviceOrientationCamera.prototype.enableHorizontalDragging = function (dragFactor) { + if (dragFactor === void 0) { dragFactor = 1 / 300; } + this._dragFactor = dragFactor; + }; + /** + * Gets the current instance class name ("DeviceOrientationCamera"). + * This helps avoiding instanceof at run time. + * @returns the class name + */ + DeviceOrientationCamera.prototype.getClassName = function () { + return "DeviceOrientationCamera"; + }; + /** + * @hidden + * Checks and applies the current values of the inputs to the camera. (Internal use only) + */ + DeviceOrientationCamera.prototype._checkInputs = function () { + _super.prototype._checkInputs.call(this); + this._quaternionCache.copyFrom(this.rotationQuaternion); + if (this._initialQuaternion) { + this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion); + } + }; + /** + * Reset the camera to its default orientation on the specified axis only. + * @param axis The axis to reset + */ + DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) { + var _this = this; + if (axis === void 0) { axis = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Axis"].Y; } + //can only work if this camera has a rotation quaternion already. + if (!this.rotationQuaternion) { + return; + } + if (!this._initialQuaternion) { + this._initialQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Quaternion"](); + } + this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion); + ['x', 'y', 'z'].forEach(function (axisName) { + if (!axis[axisName]) { + _this._initialQuaternion[axisName] = 0; + } + else { + _this._initialQuaternion[axisName] *= -1; + } + }); + this._initialQuaternion.normalize(); + //force rotation update + this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion); + }; + return DeviceOrientationCamera; +}(_freeCamera__WEBPACK_IMPORTED_MODULE_1__["FreeCamera"])); + + + +/***/ }), + +/***/ "./Cameras/flyCamera.ts": +/*!******************************!*\ + !*** ./Cameras/flyCamera.ts ***! + \******************************/ +/*! exports provided: FlyCamera */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FlyCamera", function() { return FlyCamera; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Engines/engine */ "./Engines/engine.ts"); +/* harmony import */ var _targetCamera__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./targetCamera */ "./Cameras/targetCamera.ts"); +/* harmony import */ var _flyCameraInputsManager__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./flyCameraInputsManager */ "./Cameras/flyCameraInputsManager.ts"); + + + + + + +/** + * This is a flying camera, designed for 3D movement and rotation in all directions, + * such as in a 3D Space Shooter or a Flight Simulator. + */ +var FlyCamera = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](FlyCamera, _super); + /** + * Instantiates a FlyCamera. + * This is a flying camera, designed for 3D movement and rotation in all directions, + * such as in a 3D Space Shooter or a Flight Simulator. + * @param name Define the name of the camera in the scene. + * @param position Define the starting position of the camera in the scene. + * @param scene Define the scene the camera belongs to. + * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active, if no other camera has been defined as active. + */ + function FlyCamera(name, position, scene, setActiveOnSceneIfNoneActive) { + if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; } + var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this; + /** + * Define the collision ellipsoid of the camera. + * This is helpful for simulating a camera body, like a player's body. + * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera + */ + _this.ellipsoid = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](1, 1, 1); + /** + * Define an offset for the position of the ellipsoid around the camera. + * This can be helpful if the camera is attached away from the player's body center, + * such as at its head. + */ + _this.ellipsoidOffset = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](0, 0, 0); + /** + * Enable or disable collisions of the camera with the rest of the scene objects. + */ + _this.checkCollisions = false; + /** + * Enable or disable gravity on the camera. + */ + _this.applyGravity = false; + /** + * Define the current direction the camera is moving to. + */ + _this.cameraDirection = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); + /** + * Track Roll to maintain the wanted Rolling when looking around. + */ + _this._trackRoll = 0; + /** + * Slowly correct the Roll to its original value after a Pitch+Yaw rotation. + */ + _this.rollCorrect = 100; + /** + * Mimic a banked turn, Rolling the camera when Yawing. + * It's recommended to use rollCorrect = 10 for faster banking correction. + */ + _this.bankedTurn = false; + /** + * Limit in radians for how much Roll banking will add. (Default: 90°) + */ + _this.bankedTurnLimit = Math.PI / 2; + /** + * Value of 0 disables the banked Roll. + * Value of 1 is equal to the Yaw angle in radians. + */ + _this.bankedTurnMultiplier = 1; + _this._needMoveForGravity = false; + _this._oldPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); + _this._diffPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); + _this._newPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); + // Collisions. + _this._collisionMask = -1; + /** @hidden */ + _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) { + if (collidedMesh === void 0) { collidedMesh = null; } + var updatePosition = function (newPos) { + _this._newPosition.copyFrom(newPos); + _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition); + if (_this._diffPosition.length() > _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].CollisionsEpsilon) { + _this.position.addInPlace(_this._diffPosition); + if (_this.onCollide && collidedMesh) { + _this.onCollide(collidedMesh); + } + } + }; + updatePosition(newPosition); + }; + _this.inputs = new _flyCameraInputsManager__WEBPACK_IMPORTED_MODULE_5__["FlyCameraInputsManager"](_this); + _this.inputs.addKeyboard().addMouse(); + return _this; + } + Object.defineProperty(FlyCamera.prototype, "angularSensibility", { + /** + * Gets the input sensibility for mouse input. + * Higher values reduce sensitivity. + */ + get: function () { + var mouse = this.inputs.attached["mouse"]; + if (mouse) { + return mouse.angularSensibility; + } + return 0; + }, + /** + * Sets the input sensibility for a mouse input. + * Higher values reduce sensitivity. + */ + set: function (value) { + var mouse = this.inputs.attached["mouse"]; + if (mouse) { + mouse.angularSensibility = value; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(FlyCamera.prototype, "keysForward", { + /** + * Get the keys for camera movement forward. + */ + get: function () { + var keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + return keyboard.keysForward; + } + return []; + }, + /** + * Set the keys for camera movement forward. + */ + set: function (value) { + var keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + keyboard.keysForward = value; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(FlyCamera.prototype, "keysBackward", { + /** + * Get the keys for camera movement backward. + */ + get: function () { + var keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + return keyboard.keysBackward; + } + return []; + }, + set: function (value) { + var keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + keyboard.keysBackward = value; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(FlyCamera.prototype, "keysUp", { + /** + * Get the keys for camera movement up. + */ + get: function () { + var keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + return keyboard.keysUp; + } + return []; + }, + /** + * Set the keys for camera movement up. + */ + set: function (value) { + var keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + keyboard.keysUp = value; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(FlyCamera.prototype, "keysDown", { + /** + * Get the keys for camera movement down. + */ + get: function () { + var keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + return keyboard.keysDown; + } + return []; + }, + /** + * Set the keys for camera movement down. + */ + set: function (value) { + var keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + keyboard.keysDown = value; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(FlyCamera.prototype, "keysLeft", { + /** + * Get the keys for camera movement left. + */ + get: function () { + var keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + return keyboard.keysLeft; + } + return []; + }, + /** + * Set the keys for camera movement left. + */ + set: function (value) { + var keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + keyboard.keysLeft = value; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(FlyCamera.prototype, "keysRight", { + /** + * Set the keys for camera movement right. + */ + get: function () { + var keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + return keyboard.keysRight; + } + return []; + }, + /** + * Set the keys for camera movement right. + */ + set: function (value) { + var keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + keyboard.keysRight = value; + } + }, + enumerable: true, + configurable: true + }); + /** + * Attach a control to the HTML DOM element. + * @param element Defines the element that listens to the input events. + * @param noPreventDefault Defines whether events caught by the controls should call preventdefault(). https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault + */ + FlyCamera.prototype.attachControl = function (element, noPreventDefault) { + this.inputs.attachElement(element, noPreventDefault); + }; + /** + * Detach a control from the HTML DOM element. + * The camera will stop reacting to that input. + * @param element Defines the element that listens to the input events. + */ + FlyCamera.prototype.detachControl = function (element) { + this.inputs.detachElement(element); + this.cameraDirection = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](0, 0, 0); + }; + Object.defineProperty(FlyCamera.prototype, "collisionMask", { + /** + * Get the mask that the camera ignores in collision events. + */ + get: function () { + return this._collisionMask; + }, + /** + * Set the mask that the camera ignores in collision events. + */ + set: function (mask) { + this._collisionMask = !isNaN(mask) ? mask : -1; + }, + enumerable: true, + configurable: true + }); + /** @hidden */ + FlyCamera.prototype._collideWithWorld = function (displacement) { + var globalPosition; + if (this.parent) { + globalPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].TransformCoordinates(this.position, this.parent.getWorldMatrix()); + } + else { + globalPosition = this.position; + } + globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition); + this._oldPosition.addInPlace(this.ellipsoidOffset); + var coordinator = this.getScene().collisionCoordinator; + if (!this._collider) { + this._collider = coordinator.createCollider(); + } + this._collider._radius = this.ellipsoid; + this._collider.collisionMask = this._collisionMask; + // No need for clone, as long as gravity is not on. + var actualDisplacement = displacement; + // Add gravity to direction to prevent dual-collision checking. + if (this.applyGravity) { + // This prevents mending with cameraDirection, a global variable of the fly camera class. + actualDisplacement = displacement.add(this.getScene().gravity); + } + coordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId); + }; + /** @hidden */ + FlyCamera.prototype._checkInputs = function () { + if (!this._localDirection) { + this._localDirection = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); + this._transformedDirection = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); + } + this.inputs.checkInputs(); + _super.prototype._checkInputs.call(this); + }; + /** @hidden */ + FlyCamera.prototype._decideIfNeedsToMove = function () { + return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0; + }; + /** @hidden */ + FlyCamera.prototype._updatePosition = function () { + if (this.checkCollisions && this.getScene().collisionsEnabled) { + this._collideWithWorld(this.cameraDirection); + } + else { + _super.prototype._updatePosition.call(this); + } + }; + /** + * Restore the Roll to its target value at the rate specified. + * @param rate - Higher means slower restoring. + * @hidden + */ + FlyCamera.prototype.restoreRoll = function (rate) { + var limit = this._trackRoll; // Target Roll. + var z = this.rotation.z; // Current Roll. + var delta = limit - z; // Difference in Roll. + var minRad = 0.001; // Tenth of a radian is a barely noticable difference. + // If the difference is noticable, restore the Roll. + if (Math.abs(delta) >= minRad) { + // Change Z rotation towards the target Roll. + this.rotation.z += delta / rate; + // Match when near enough. + if (Math.abs(limit - this.rotation.z) <= minRad) { + this.rotation.z = limit; + } + } + }; + /** + * Destroy the camera and release the current resources held by it. + */ + FlyCamera.prototype.dispose = function () { + this.inputs.clear(); + _super.prototype.dispose.call(this); + }; + /** + * Get the current object class name. + * @returns the class name. + */ + FlyCamera.prototype.getClassName = function () { + return "FlyCamera"; + }; + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsVector3"])() + ], FlyCamera.prototype, "ellipsoid", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsVector3"])() + ], FlyCamera.prototype, "ellipsoidOffset", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], FlyCamera.prototype, "checkCollisions", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], FlyCamera.prototype, "applyGravity", void 0); + return FlyCamera; +}(_targetCamera__WEBPACK_IMPORTED_MODULE_4__["TargetCamera"])); + + + +/***/ }), + +/***/ "./Cameras/flyCameraInputsManager.ts": +/*!*******************************************!*\ + !*** ./Cameras/flyCameraInputsManager.ts ***! + \*******************************************/ +/*! exports provided: FlyCameraInputsManager */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FlyCameraInputsManager", function() { return FlyCameraInputsManager; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _cameraInputsManager__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); +/* harmony import */ var _Cameras_Inputs_flyCameraMouseInput__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Cameras/Inputs/flyCameraMouseInput */ "./Cameras/Inputs/flyCameraMouseInput.ts"); +/* harmony import */ var _Cameras_Inputs_flyCameraKeyboardInput__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Cameras/Inputs/flyCameraKeyboardInput */ "./Cameras/Inputs/flyCameraKeyboardInput.ts"); + + + + +/** + * Default Inputs manager for the FlyCamera. + * It groups all the default supported inputs for ease of use. + * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs + */ +var FlyCameraInputsManager = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](FlyCameraInputsManager, _super); + /** + * Instantiates a new FlyCameraInputsManager. + * @param camera Defines the camera the inputs belong to. + */ + function FlyCameraInputsManager(camera) { + return _super.call(this, camera) || this; + } + /** + * Add keyboard input support to the input manager. + * @returns the new FlyCameraKeyboardMoveInput(). + */ + FlyCameraInputsManager.prototype.addKeyboard = function () { + this.add(new _Cameras_Inputs_flyCameraKeyboardInput__WEBPACK_IMPORTED_MODULE_3__["FlyCameraKeyboardInput"]()); + return this; + }; + /** + * Add mouse input support to the input manager. + * @param touchEnabled Enable touch screen support. + * @returns the new FlyCameraMouseInput(). + */ + FlyCameraInputsManager.prototype.addMouse = function (touchEnabled) { + if (touchEnabled === void 0) { touchEnabled = true; } + this.add(new _Cameras_Inputs_flyCameraMouseInput__WEBPACK_IMPORTED_MODULE_2__["FlyCameraMouseInput"](touchEnabled)); + return this; + }; + return FlyCameraInputsManager; +}(_cameraInputsManager__WEBPACK_IMPORTED_MODULE_1__["CameraInputsManager"])); + + + +/***/ }), + +/***/ "./Cameras/followCamera.ts": +/*!*********************************!*\ + !*** ./Cameras/followCamera.ts ***! + \*********************************/ +/*! exports provided: FollowCamera, ArcFollowCamera */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FollowCamera", function() { return FollowCamera; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ArcFollowCamera", function() { return ArcFollowCamera; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/tools */ "./Misc/tools.ts"); +/* harmony import */ var _targetCamera__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./targetCamera */ "./Cameras/targetCamera.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../node */ "./node.ts"); +/* harmony import */ var _followCameraInputsManager__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./followCameraInputsManager */ "./Cameras/followCameraInputsManager.ts"); + + + + + + + +_node__WEBPACK_IMPORTED_MODULE_5__["Node"].AddNodeConstructor("FollowCamera", function (name, scene) { + return function () { return new FollowCamera(name, _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"].Zero(), scene); }; +}); +_node__WEBPACK_IMPORTED_MODULE_5__["Node"].AddNodeConstructor("ArcFollowCamera", function (name, scene) { + return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); }; +}); +/** + * A follow camera takes a mesh as a target and follows it as it moves. Both a free camera version followCamera and + * an arc rotate version arcFollowCamera are available. + * @see http://doc.babylonjs.com/features/cameras#follow-camera + */ +var FollowCamera = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](FollowCamera, _super); + /** + * Instantiates the follow camera. + * @see http://doc.babylonjs.com/features/cameras#follow-camera + * @param name Define the name of the camera in the scene + * @param position Define the position of the camera + * @param scene Define the scene the camera belong to + * @param lockedTarget Define the target of the camera + */ + function FollowCamera(name, position, scene, lockedTarget) { + if (lockedTarget === void 0) { lockedTarget = null; } + var _this = _super.call(this, name, position, scene) || this; + /** + * Distance the follow camera should follow an object at + */ + _this.radius = 12; + /** + * Minimum allowed distance of the camera to the axis of rotation + * (The camera can not get closer). + * This can help limiting how the Camera is able to move in the scene. + */ + _this.lowerRadiusLimit = null; + /** + * Maximum allowed distance of the camera to the axis of rotation + * (The camera can not get further). + * This can help limiting how the Camera is able to move in the scene. + */ + _this.upperRadiusLimit = null; + /** + * Define a rotation offset between the camera and the object it follows + */ + _this.rotationOffset = 0; + /** + * Minimum allowed angle to camera position relative to target object. + * This can help limiting how the Camera is able to move in the scene. + */ + _this.lowerRotationOffsetLimit = null; + /** + * Maximum allowed angle to camera position relative to target object. + * This can help limiting how the Camera is able to move in the scene. + */ + _this.upperRotationOffsetLimit = null; + /** + * Define a height offset between the camera and the object it follows. + * It can help following an object from the top (like a car chaing a plane) + */ + _this.heightOffset = 4; + /** + * Minimum allowed height of camera position relative to target object. + * This can help limiting how the Camera is able to move in the scene. + */ + _this.lowerHeightOffsetLimit = null; + /** + * Maximum allowed height of camera position relative to target object. + * This can help limiting how the Camera is able to move in the scene. + */ + _this.upperHeightOffsetLimit = null; + /** + * Define how fast the camera can accelerate to follow it s target. + */ + _this.cameraAcceleration = 0.05; + /** + * Define the speed limit of the camera following an object. + */ + _this.maxCameraSpeed = 20; + _this.lockedTarget = lockedTarget; + _this.inputs = new _followCameraInputsManager__WEBPACK_IMPORTED_MODULE_6__["FollowCameraInputsManager"](_this); + _this.inputs.addKeyboard().addMouseWheel().addPointers(); + return _this; + // Uncomment the following line when the relevant handlers have been implemented. + // this.inputs.addKeyboard().addMouseWheel().addPointers().addVRDeviceOrientation(); + } + FollowCamera.prototype._follow = function (cameraTarget) { + if (!cameraTarget) { + return; + } + var yRotation; + if (cameraTarget.rotationQuaternion) { + var rotMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"](); + cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix); + yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]); + } + else { + yRotation = cameraTarget.rotation.y; + } + var radians = _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].ToRadians(this.rotationOffset) + yRotation; + var targetPosition = cameraTarget.getAbsolutePosition(); + var targetX = targetPosition.x + Math.sin(radians) * this.radius; + var targetZ = targetPosition.z + Math.cos(radians) * this.radius; + var dx = targetX - this.position.x; + var dy = (targetPosition.y + this.heightOffset) - this.position.y; + var dz = (targetZ) - this.position.z; + var vx = dx * this.cameraAcceleration * 2; //this is set to .05 + var vy = dy * this.cameraAcceleration; + var vz = dz * this.cameraAcceleration * 2; + if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) { + vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed; + } + if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) { + vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed; + } + if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) { + vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed; + } + this.position = new _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"](this.position.x + vx, this.position.y + vy, this.position.z + vz); + this.setTarget(targetPosition); + }; + /** + * Attached controls to the current camera. + * @param element Defines the element the controls should be listened from + * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) + */ + FollowCamera.prototype.attachControl = function (element, noPreventDefault) { + this.inputs.attachElement(element, noPreventDefault); + this._reset = function () { + }; + }; + /** + * Detach the current controls from the camera. + * The camera will stop reacting to inputs. + * @param element Defines the element to stop listening the inputs from + */ + FollowCamera.prototype.detachControl = function (element) { + this.inputs.detachElement(element); + if (this._reset) { + this._reset(); + } + }; + /** @hidden */ + FollowCamera.prototype._checkInputs = function () { + this.inputs.checkInputs(); + this._checkLimits(); + _super.prototype._checkInputs.call(this); + if (this.lockedTarget) { + this._follow(this.lockedTarget); + } + }; + FollowCamera.prototype._checkLimits = function () { + if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) { + this.radius = this.lowerRadiusLimit; + } + if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) { + this.radius = this.upperRadiusLimit; + } + if (this.lowerHeightOffsetLimit !== null && + this.heightOffset < this.lowerHeightOffsetLimit) { + this.heightOffset = this.lowerHeightOffsetLimit; + } + if (this.upperHeightOffsetLimit !== null && + this.heightOffset > this.upperHeightOffsetLimit) { + this.heightOffset = this.upperHeightOffsetLimit; + } + if (this.lowerRotationOffsetLimit !== null && + this.rotationOffset < this.lowerRotationOffsetLimit) { + this.rotationOffset = this.lowerRotationOffsetLimit; + } + if (this.upperRotationOffsetLimit !== null && + this.rotationOffset > this.upperRotationOffsetLimit) { + this.rotationOffset = this.upperRotationOffsetLimit; + } + }; + /** + * Gets the camera class name. + * @returns the class name + */ + FollowCamera.prototype.getClassName = function () { + return "FollowCamera"; + }; + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], FollowCamera.prototype, "radius", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], FollowCamera.prototype, "lowerRadiusLimit", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], FollowCamera.prototype, "upperRadiusLimit", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], FollowCamera.prototype, "rotationOffset", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], FollowCamera.prototype, "lowerRotationOffsetLimit", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], FollowCamera.prototype, "upperRotationOffsetLimit", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], FollowCamera.prototype, "heightOffset", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], FollowCamera.prototype, "lowerHeightOffsetLimit", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], FollowCamera.prototype, "upperHeightOffsetLimit", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], FollowCamera.prototype, "cameraAcceleration", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], FollowCamera.prototype, "maxCameraSpeed", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsMeshReference"])("lockedTargetId") + ], FollowCamera.prototype, "lockedTarget", void 0); + return FollowCamera; +}(_targetCamera__WEBPACK_IMPORTED_MODULE_3__["TargetCamera"])); + +/** + * Arc Rotate version of the follow camera. + * It still follows a Defined mesh but in an Arc Rotate Camera fashion. + * @see http://doc.babylonjs.com/features/cameras#follow-camera + */ +var ArcFollowCamera = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ArcFollowCamera, _super); + /** + * Instantiates a new ArcFollowCamera + * @see http://doc.babylonjs.com/features/cameras#follow-camera + * @param name Define the name of the camera + * @param alpha Define the rotation angle of the camera around the logitudinal axis + * @param beta Define the rotation angle of the camera around the elevation axis + * @param radius Define the radius of the camera from its target point + * @param target Define the target of the camera + * @param scene Define the scene the camera belongs to + */ + function ArcFollowCamera(name, + /** The longitudinal angle of the camera */ + alpha, + /** The latitudinal angle of the camera */ + beta, + /** The radius of the camera from its target */ + radius, + /** Define the camera target (the messh it should follow) */ + target, scene) { + var _this = _super.call(this, name, _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"].Zero(), scene) || this; + _this.alpha = alpha; + _this.beta = beta; + _this.radius = radius; + _this.target = target; + _this._cartesianCoordinates = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"].Zero(); + _this._follow(); + return _this; + } + ArcFollowCamera.prototype._follow = function () { + if (!this.target) { + return; + } + this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta); + this._cartesianCoordinates.y = this.radius * Math.sin(this.beta); + this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta); + var targetPosition = this.target.getAbsolutePosition(); + this.position = targetPosition.add(this._cartesianCoordinates); + this.setTarget(targetPosition); + }; + /** @hidden */ + ArcFollowCamera.prototype._checkInputs = function () { + _super.prototype._checkInputs.call(this); + this._follow(); + }; + /** + * Returns the class name of the object. + * It is mostly used internally for serialization purposes. + */ + ArcFollowCamera.prototype.getClassName = function () { + return "ArcFollowCamera"; + }; + return ArcFollowCamera; +}(_targetCamera__WEBPACK_IMPORTED_MODULE_3__["TargetCamera"])); + + + +/***/ }), + +/***/ "./Cameras/followCameraInputsManager.ts": +/*!**********************************************!*\ + !*** ./Cameras/followCameraInputsManager.ts ***! + \**********************************************/ +/*! exports provided: FollowCameraInputsManager */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FollowCameraInputsManager", function() { return FollowCameraInputsManager; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _cameraInputsManager__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); +/* harmony import */ var _Inputs_followCameraKeyboardMoveInput__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Inputs/followCameraKeyboardMoveInput */ "./Cameras/Inputs/followCameraKeyboardMoveInput.ts"); +/* harmony import */ var _Inputs_followCameraMouseWheelInput__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Inputs/followCameraMouseWheelInput */ "./Cameras/Inputs/followCameraMouseWheelInput.ts"); +/* harmony import */ var _Inputs_followCameraPointersInput__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Inputs/followCameraPointersInput */ "./Cameras/Inputs/followCameraPointersInput.ts"); + + + + + +/** + * Default Inputs manager for the FollowCamera. + * It groups all the default supported inputs for ease of use. + * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs + */ +var FollowCameraInputsManager = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](FollowCameraInputsManager, _super); + /** + * Instantiates a new FollowCameraInputsManager. + * @param camera Defines the camera the inputs belong to + */ + function FollowCameraInputsManager(camera) { + return _super.call(this, camera) || this; + } + /** + * Add keyboard input support to the input manager. + * @returns the current input manager + */ + FollowCameraInputsManager.prototype.addKeyboard = function () { + this.add(new _Inputs_followCameraKeyboardMoveInput__WEBPACK_IMPORTED_MODULE_2__["FollowCameraKeyboardMoveInput"]()); + return this; + }; + /** + * Add mouse wheel input support to the input manager. + * @returns the current input manager + */ + FollowCameraInputsManager.prototype.addMouseWheel = function () { + this.add(new _Inputs_followCameraMouseWheelInput__WEBPACK_IMPORTED_MODULE_3__["FollowCameraMouseWheelInput"]()); + return this; + }; + /** + * Add pointers input support to the input manager. + * @returns the current input manager + */ + FollowCameraInputsManager.prototype.addPointers = function () { + this.add(new _Inputs_followCameraPointersInput__WEBPACK_IMPORTED_MODULE_4__["FollowCameraPointersInput"]()); + return this; + }; + /** + * Add orientation input support to the input manager. + * @returns the current input manager + */ + FollowCameraInputsManager.prototype.addVRDeviceOrientation = function () { + console.warn("DeviceOrientation support not yet implemented for FollowCamera."); + return this; + }; + return FollowCameraInputsManager; +}(_cameraInputsManager__WEBPACK_IMPORTED_MODULE_1__["CameraInputsManager"])); + + + +/***/ }), + +/***/ "./Cameras/freeCamera.ts": +/*!*******************************!*\ + !*** ./Cameras/freeCamera.ts ***! + \*******************************/ +/*! exports provided: FreeCamera */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FreeCamera", function() { return FreeCamera; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Engines/engine */ "./Engines/engine.ts"); +/* harmony import */ var _targetCamera__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./targetCamera */ "./Cameras/targetCamera.ts"); +/* harmony import */ var _freeCameraInputsManager__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./freeCameraInputsManager */ "./Cameras/freeCameraInputsManager.ts"); + + + + + + +/** + * This represents a free type of camera. It can be useful in First Person Shooter game for instance. + * Please consider using the new UniversalCamera instead as it adds more functionality like the gamepad. + * @see http://doc.babylonjs.com/features/cameras#universal-camera + */ +var FreeCamera = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](FreeCamera, _super); + /** + * Instantiates a Free Camera. + * This represents a free type of camera. It can be useful in First Person Shooter game for instance. + * Please consider using the new UniversalCamera instead as it adds more functionality like touch to this camera. + * @see http://doc.babylonjs.com/features/cameras#universal-camera + * @param name Define the name of the camera in the scene + * @param position Define the start position of the camera in the scene + * @param scene Define the scene the camera belongs to + * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined + */ + function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) { + if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; } + var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this; + /** + * Define the collision ellipsoid of the camera. + * This is helpful to simulate a camera body like the player body around the camera + * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera + */ + _this.ellipsoid = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](0.5, 1, 0.5); + /** + * Define an offset for the position of the ellipsoid around the camera. + * This can be helpful to determine the center of the body near the gravity center of the body + * instead of its head. + */ + _this.ellipsoidOffset = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](0, 0, 0); + /** + * Enable or disable collisions of the camera with the rest of the scene objects. + */ + _this.checkCollisions = false; + /** + * Enable or disable gravity on the camera. + */ + _this.applyGravity = false; + _this._needMoveForGravity = false; + _this._oldPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); + _this._diffPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); + _this._newPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); + // Collisions + _this._collisionMask = -1; + _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) { + if (collidedMesh === void 0) { collidedMesh = null; } + var updatePosition = function (newPos) { + _this._newPosition.copyFrom(newPos); + _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition); + if (_this._diffPosition.length() > _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].CollisionsEpsilon) { + _this.position.addInPlace(_this._diffPosition); + if (_this.onCollide && collidedMesh) { + _this.onCollide(collidedMesh); + } + } + }; + updatePosition(newPosition); + }; + _this.inputs = new _freeCameraInputsManager__WEBPACK_IMPORTED_MODULE_5__["FreeCameraInputsManager"](_this); + _this.inputs.addKeyboard().addMouse(); + return _this; + } + Object.defineProperty(FreeCamera.prototype, "angularSensibility", { + /** + * Gets the input sensibility for a mouse input. (default is 2000.0) + * Higher values reduce sensitivity. + */ + get: function () { + var mouse = this.inputs.attached["mouse"]; + if (mouse) { + return mouse.angularSensibility; + } + return 0; + }, + /** + * Sets the input sensibility for a mouse input. (default is 2000.0) + * Higher values reduce sensitivity. + */ + set: function (value) { + var mouse = this.inputs.attached["mouse"]; + if (mouse) { + mouse.angularSensibility = value; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(FreeCamera.prototype, "keysUp", { + /** + * Gets or Set the list of keyboard keys used to control the forward move of the camera. + */ + get: function () { + var keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + return keyboard.keysUp; + } + return []; + }, + set: function (value) { + var keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + keyboard.keysUp = value; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(FreeCamera.prototype, "keysDown", { + /** + * Gets or Set the list of keyboard keys used to control the backward move of the camera. + */ + get: function () { + var keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + return keyboard.keysDown; + } + return []; + }, + set: function (value) { + var keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + keyboard.keysDown = value; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(FreeCamera.prototype, "keysLeft", { + /** + * Gets or Set the list of keyboard keys used to control the left strafe move of the camera. + */ + get: function () { + var keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + return keyboard.keysLeft; + } + return []; + }, + set: function (value) { + var keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + keyboard.keysLeft = value; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(FreeCamera.prototype, "keysRight", { + /** + * Gets or Set the list of keyboard keys used to control the right strafe move of the camera. + */ + get: function () { + var keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + return keyboard.keysRight; + } + return []; + }, + set: function (value) { + var keyboard = this.inputs.attached["keyboard"]; + if (keyboard) { + keyboard.keysRight = value; + } + }, + enumerable: true, + configurable: true + }); + /** + * Attached controls to the current camera. + * @param element Defines the element the controls should be listened from + * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) + */ + FreeCamera.prototype.attachControl = function (element, noPreventDefault) { + this.inputs.attachElement(element, noPreventDefault); + }; + /** + * Detach the current controls from the camera. + * The camera will stop reacting to inputs. + * @param element Defines the element to stop listening the inputs from + */ + FreeCamera.prototype.detachControl = function (element) { + this.inputs.detachElement(element); + this.cameraDirection = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](0, 0, 0); + this.cameraRotation = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector2"](0, 0); + }; + Object.defineProperty(FreeCamera.prototype, "collisionMask", { + /** + * Define a collision mask to limit the list of object the camera can collide with + */ + get: function () { + return this._collisionMask; + }, + set: function (mask) { + this._collisionMask = !isNaN(mask) ? mask : -1; + }, + enumerable: true, + configurable: true + }); + /** @hidden */ + FreeCamera.prototype._collideWithWorld = function (displacement) { + var globalPosition; + if (this.parent) { + globalPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].TransformCoordinates(this.position, this.parent.getWorldMatrix()); + } + else { + globalPosition = this.position; + } + globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition); + this._oldPosition.addInPlace(this.ellipsoidOffset); + var coordinator = this.getScene().collisionCoordinator; + if (!this._collider) { + this._collider = coordinator.createCollider(); + } + this._collider._radius = this.ellipsoid; + this._collider.collisionMask = this._collisionMask; + //no need for clone, as long as gravity is not on. + var actualDisplacement = displacement; + //add gravity to the direction to prevent the dual-collision checking + if (this.applyGravity) { + //this prevents mending with cameraDirection, a global variable of the free camera class. + actualDisplacement = displacement.add(this.getScene().gravity); + } + coordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId); + }; + /** @hidden */ + FreeCamera.prototype._checkInputs = function () { + if (!this._localDirection) { + this._localDirection = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); + this._transformedDirection = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); + } + this.inputs.checkInputs(); + _super.prototype._checkInputs.call(this); + }; + /** @hidden */ + FreeCamera.prototype._decideIfNeedsToMove = function () { + return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0; + }; + /** @hidden */ + FreeCamera.prototype._updatePosition = function () { + if (this.checkCollisions && this.getScene().collisionsEnabled) { + this._collideWithWorld(this.cameraDirection); + } + else { + _super.prototype._updatePosition.call(this); + } + }; + /** + * Destroy the camera and release the current resources hold by it. + */ + FreeCamera.prototype.dispose = function () { + this.inputs.clear(); + _super.prototype.dispose.call(this); + }; + /** + * Gets the current object class name. + * @return the class name + */ + FreeCamera.prototype.getClassName = function () { + return "FreeCamera"; + }; + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsVector3"])() + ], FreeCamera.prototype, "ellipsoid", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsVector3"])() + ], FreeCamera.prototype, "ellipsoidOffset", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], FreeCamera.prototype, "checkCollisions", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], FreeCamera.prototype, "applyGravity", void 0); + return FreeCamera; +}(_targetCamera__WEBPACK_IMPORTED_MODULE_4__["TargetCamera"])); + + + +/***/ }), + +/***/ "./Cameras/freeCameraInputsManager.ts": +/*!********************************************!*\ + !*** ./Cameras/freeCameraInputsManager.ts ***! + \********************************************/ +/*! exports provided: FreeCameraInputsManager */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FreeCameraInputsManager", function() { return FreeCameraInputsManager; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _cameraInputsManager__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); +/* harmony import */ var _Cameras_Inputs_freeCameraKeyboardMoveInput__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Cameras/Inputs/freeCameraKeyboardMoveInput */ "./Cameras/Inputs/freeCameraKeyboardMoveInput.ts"); +/* harmony import */ var _Cameras_Inputs_freeCameraMouseInput__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Cameras/Inputs/freeCameraMouseInput */ "./Cameras/Inputs/freeCameraMouseInput.ts"); +/* harmony import */ var _Cameras_Inputs_freeCameraTouchInput__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Cameras/Inputs/freeCameraTouchInput */ "./Cameras/Inputs/freeCameraTouchInput.ts"); + + + + + +/** + * Default Inputs manager for the FreeCamera. + * It groups all the default supported inputs for ease of use. + * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs + */ +var FreeCameraInputsManager = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](FreeCameraInputsManager, _super); + /** + * Instantiates a new FreeCameraInputsManager. + * @param camera Defines the camera the inputs belong to + */ + function FreeCameraInputsManager(camera) { + var _this = _super.call(this, camera) || this; + /** + * @hidden + */ + _this._mouseInput = null; + return _this; + } + /** + * Add keyboard input support to the input manager. + * @returns the current input manager + */ + FreeCameraInputsManager.prototype.addKeyboard = function () { + this.add(new _Cameras_Inputs_freeCameraKeyboardMoveInput__WEBPACK_IMPORTED_MODULE_2__["FreeCameraKeyboardMoveInput"]()); + return this; + }; + /** + * Add mouse input support to the input manager. + * @param touchEnabled if the FreeCameraMouseInput should support touch (default: true) + * @returns the current input manager + */ + FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) { + if (touchEnabled === void 0) { touchEnabled = true; } + if (!this._mouseInput) { + this._mouseInput = new _Cameras_Inputs_freeCameraMouseInput__WEBPACK_IMPORTED_MODULE_3__["FreeCameraMouseInput"](touchEnabled); + this.add(this._mouseInput); + } + return this; + }; + /** + * Removes the mouse input support from the manager + * @returns the current input manager + */ + FreeCameraInputsManager.prototype.removeMouse = function () { + if (this._mouseInput) { + this.remove(this._mouseInput); + } + return this; + }; + /** + * Add touch input support to the input manager. + * @returns the current input manager + */ + FreeCameraInputsManager.prototype.addTouch = function () { + this.add(new _Cameras_Inputs_freeCameraTouchInput__WEBPACK_IMPORTED_MODULE_4__["FreeCameraTouchInput"]()); + return this; + }; + /** + * Remove all attached input methods from a camera + */ + FreeCameraInputsManager.prototype.clear = function () { + _super.prototype.clear.call(this); + this._mouseInput = null; + }; + return FreeCameraInputsManager; +}(_cameraInputsManager__WEBPACK_IMPORTED_MODULE_1__["CameraInputsManager"])); + + + +/***/ }), + +/***/ "./Cameras/gamepadCamera.ts": +/*!**********************************!*\ + !*** ./Cameras/gamepadCamera.ts ***! + \**********************************/ +/*! exports provided: GamepadCamera */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GamepadCamera", function() { return GamepadCamera; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _universalCamera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./universalCamera */ "./Cameras/universalCamera.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../node */ "./node.ts"); + + + + +_node__WEBPACK_IMPORTED_MODULE_3__["Node"].AddNodeConstructor("GamepadCamera", function (name, scene) { + return function () { return new GamepadCamera(name, _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(), scene); }; +}); +/** + * This represents a FPS type of camera. This is only here for back compat purpose. + * Please use the UniversalCamera instead as both are identical. + * @see http://doc.babylonjs.com/features/cameras#universal-camera + */ +var GamepadCamera = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](GamepadCamera, _super); + /** + * Instantiates a new Gamepad Camera + * This represents a FPS type of camera. This is only here for back compat purpose. + * Please use the UniversalCamera instead as both are identical. + * @see http://doc.babylonjs.com/features/cameras#universal-camera + * @param name Define the name of the camera in the scene + * @param position Define the start position of the camera in the scene + * @param scene Define the scene the camera belongs to + */ + function GamepadCamera(name, position, scene) { + return _super.call(this, name, position, scene) || this; + } + /** + * Gets the current object class name. + * @return the class name + */ + GamepadCamera.prototype.getClassName = function () { + return "GamepadCamera"; + }; + return GamepadCamera; +}(_universalCamera__WEBPACK_IMPORTED_MODULE_1__["UniversalCamera"])); + + + +/***/ }), + +/***/ "./Cameras/index.ts": +/*!**************************!*\ + !*** ./Cameras/index.ts ***! + \**************************/ +/*! exports provided: CameraInputTypes, CameraInputsManager, Camera, TargetCamera, FreeCamera, FreeCameraInputsManager, TouchCamera, ArcRotateCamera, ArcRotateCameraInputsManager, DeviceOrientationCamera, FlyCamera, FlyCameraInputsManager, FollowCamera, ArcFollowCamera, GamepadCamera, UniversalCamera, VirtualJoysticksCamera, ArcRotateCameraGamepadInput, ArcRotateCameraKeyboardMoveInput, ArcRotateCameraMouseWheelInput, ArcRotateCameraPointersInput, ArcRotateCameraVRDeviceOrientationInput, FlyCameraKeyboardInput, FlyCameraMouseInput, FollowCameraKeyboardMoveInput, FollowCameraMouseWheelInput, FollowCameraPointersInput, FreeCameraDeviceOrientationInput, FreeCameraGamepadInput, FreeCameraKeyboardMoveInput, FreeCameraMouseInput, FreeCameraTouchInput, FreeCameraVirtualJoystickInput, AnaglyphArcRotateCamera, AnaglyphFreeCamera, AnaglyphGamepadCamera, AnaglyphUniversalCamera, StereoscopicArcRotateCamera, StereoscopicFreeCamera, StereoscopicGamepadCamera, StereoscopicUniversalCamera, VRCameraMetrics, VRDeviceOrientationArcRotateCamera, VRDeviceOrientationFreeCamera, VRDeviceOrientationGamepadCamera, OnAfterEnteringVRObservableEvent, VRExperienceHelper, WebVRFreeCamera, WebXRCamera, WebXREnterExitUIButton, WebXREnterExitUIOptions, WebXREnterExitUI, WebXRState, WebXRExperienceHelper, WebXRController, WebXRInput, WebXRManagedOutputCanvas, WebXRSessionManager */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Inputs_index__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Inputs/index */ "./Cameras/Inputs/index.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraGamepadInput", function() { return _Inputs_index__WEBPACK_IMPORTED_MODULE_0__["ArcRotateCameraGamepadInput"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraKeyboardMoveInput", function() { return _Inputs_index__WEBPACK_IMPORTED_MODULE_0__["ArcRotateCameraKeyboardMoveInput"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraMouseWheelInput", function() { return _Inputs_index__WEBPACK_IMPORTED_MODULE_0__["ArcRotateCameraMouseWheelInput"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraPointersInput", function() { return _Inputs_index__WEBPACK_IMPORTED_MODULE_0__["ArcRotateCameraPointersInput"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraVRDeviceOrientationInput", function() { return _Inputs_index__WEBPACK_IMPORTED_MODULE_0__["ArcRotateCameraVRDeviceOrientationInput"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FlyCameraKeyboardInput", function() { return _Inputs_index__WEBPACK_IMPORTED_MODULE_0__["FlyCameraKeyboardInput"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FlyCameraMouseInput", function() { return _Inputs_index__WEBPACK_IMPORTED_MODULE_0__["FlyCameraMouseInput"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FollowCameraKeyboardMoveInput", function() { return _Inputs_index__WEBPACK_IMPORTED_MODULE_0__["FollowCameraKeyboardMoveInput"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FollowCameraMouseWheelInput", function() { return _Inputs_index__WEBPACK_IMPORTED_MODULE_0__["FollowCameraMouseWheelInput"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FollowCameraPointersInput", function() { return _Inputs_index__WEBPACK_IMPORTED_MODULE_0__["FollowCameraPointersInput"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraDeviceOrientationInput", function() { return _Inputs_index__WEBPACK_IMPORTED_MODULE_0__["FreeCameraDeviceOrientationInput"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraGamepadInput", function() { return _Inputs_index__WEBPACK_IMPORTED_MODULE_0__["FreeCameraGamepadInput"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraKeyboardMoveInput", function() { return _Inputs_index__WEBPACK_IMPORTED_MODULE_0__["FreeCameraKeyboardMoveInput"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraMouseInput", function() { return _Inputs_index__WEBPACK_IMPORTED_MODULE_0__["FreeCameraMouseInput"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraTouchInput", function() { return _Inputs_index__WEBPACK_IMPORTED_MODULE_0__["FreeCameraTouchInput"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraVirtualJoystickInput", function() { return _Inputs_index__WEBPACK_IMPORTED_MODULE_0__["FreeCameraVirtualJoystickInput"]; }); + +/* harmony import */ var _cameraInputsManager__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CameraInputTypes", function() { return _cameraInputsManager__WEBPACK_IMPORTED_MODULE_1__["CameraInputTypes"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CameraInputsManager", function() { return _cameraInputsManager__WEBPACK_IMPORTED_MODULE_1__["CameraInputsManager"]; }); + +/* harmony import */ var _camera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./camera */ "./Cameras/camera.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Camera", function() { return _camera__WEBPACK_IMPORTED_MODULE_2__["Camera"]; }); + +/* harmony import */ var _targetCamera__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./targetCamera */ "./Cameras/targetCamera.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TargetCamera", function() { return _targetCamera__WEBPACK_IMPORTED_MODULE_3__["TargetCamera"]; }); + +/* harmony import */ var _freeCamera__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./freeCamera */ "./Cameras/freeCamera.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCamera", function() { return _freeCamera__WEBPACK_IMPORTED_MODULE_4__["FreeCamera"]; }); + +/* harmony import */ var _freeCameraInputsManager__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./freeCameraInputsManager */ "./Cameras/freeCameraInputsManager.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraInputsManager", function() { return _freeCameraInputsManager__WEBPACK_IMPORTED_MODULE_5__["FreeCameraInputsManager"]; }); + +/* harmony import */ var _touchCamera__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./touchCamera */ "./Cameras/touchCamera.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TouchCamera", function() { return _touchCamera__WEBPACK_IMPORTED_MODULE_6__["TouchCamera"]; }); + +/* harmony import */ var _arcRotateCamera__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./arcRotateCamera */ "./Cameras/arcRotateCamera.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCamera", function() { return _arcRotateCamera__WEBPACK_IMPORTED_MODULE_7__["ArcRotateCamera"]; }); + +/* harmony import */ var _arcRotateCameraInputsManager__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./arcRotateCameraInputsManager */ "./Cameras/arcRotateCameraInputsManager.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraInputsManager", function() { return _arcRotateCameraInputsManager__WEBPACK_IMPORTED_MODULE_8__["ArcRotateCameraInputsManager"]; }); + +/* harmony import */ var _deviceOrientationCamera__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./deviceOrientationCamera */ "./Cameras/deviceOrientationCamera.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DeviceOrientationCamera", function() { return _deviceOrientationCamera__WEBPACK_IMPORTED_MODULE_9__["DeviceOrientationCamera"]; }); + +/* harmony import */ var _flyCamera__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./flyCamera */ "./Cameras/flyCamera.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FlyCamera", function() { return _flyCamera__WEBPACK_IMPORTED_MODULE_10__["FlyCamera"]; }); + +/* harmony import */ var _flyCameraInputsManager__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./flyCameraInputsManager */ "./Cameras/flyCameraInputsManager.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FlyCameraInputsManager", function() { return _flyCameraInputsManager__WEBPACK_IMPORTED_MODULE_11__["FlyCameraInputsManager"]; }); + +/* harmony import */ var _followCamera__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./followCamera */ "./Cameras/followCamera.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FollowCamera", function() { return _followCamera__WEBPACK_IMPORTED_MODULE_12__["FollowCamera"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcFollowCamera", function() { return _followCamera__WEBPACK_IMPORTED_MODULE_12__["ArcFollowCamera"]; }); + +/* harmony import */ var _gamepadCamera__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./gamepadCamera */ "./Cameras/gamepadCamera.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GamepadCamera", function() { return _gamepadCamera__WEBPACK_IMPORTED_MODULE_13__["GamepadCamera"]; }); + +/* harmony import */ var _Stereoscopic_index__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./Stereoscopic/index */ "./Cameras/Stereoscopic/index.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnaglyphArcRotateCamera", function() { return _Stereoscopic_index__WEBPACK_IMPORTED_MODULE_14__["AnaglyphArcRotateCamera"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnaglyphFreeCamera", function() { return _Stereoscopic_index__WEBPACK_IMPORTED_MODULE_14__["AnaglyphFreeCamera"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnaglyphGamepadCamera", function() { return _Stereoscopic_index__WEBPACK_IMPORTED_MODULE_14__["AnaglyphGamepadCamera"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnaglyphUniversalCamera", function() { return _Stereoscopic_index__WEBPACK_IMPORTED_MODULE_14__["AnaglyphUniversalCamera"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StereoscopicArcRotateCamera", function() { return _Stereoscopic_index__WEBPACK_IMPORTED_MODULE_14__["StereoscopicArcRotateCamera"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StereoscopicFreeCamera", function() { return _Stereoscopic_index__WEBPACK_IMPORTED_MODULE_14__["StereoscopicFreeCamera"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StereoscopicGamepadCamera", function() { return _Stereoscopic_index__WEBPACK_IMPORTED_MODULE_14__["StereoscopicGamepadCamera"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StereoscopicUniversalCamera", function() { return _Stereoscopic_index__WEBPACK_IMPORTED_MODULE_14__["StereoscopicUniversalCamera"]; }); + +/* harmony import */ var _universalCamera__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./universalCamera */ "./Cameras/universalCamera.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UniversalCamera", function() { return _universalCamera__WEBPACK_IMPORTED_MODULE_15__["UniversalCamera"]; }); + +/* harmony import */ var _virtualJoysticksCamera__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./virtualJoysticksCamera */ "./Cameras/virtualJoysticksCamera.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VirtualJoysticksCamera", function() { return _virtualJoysticksCamera__WEBPACK_IMPORTED_MODULE_16__["VirtualJoysticksCamera"]; }); + +/* harmony import */ var _VR_index__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./VR/index */ "./Cameras/VR/index.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRCameraMetrics", function() { return _VR_index__WEBPACK_IMPORTED_MODULE_17__["VRCameraMetrics"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRDeviceOrientationArcRotateCamera", function() { return _VR_index__WEBPACK_IMPORTED_MODULE_17__["VRDeviceOrientationArcRotateCamera"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRDeviceOrientationFreeCamera", function() { return _VR_index__WEBPACK_IMPORTED_MODULE_17__["VRDeviceOrientationFreeCamera"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRDeviceOrientationGamepadCamera", function() { return _VR_index__WEBPACK_IMPORTED_MODULE_17__["VRDeviceOrientationGamepadCamera"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OnAfterEnteringVRObservableEvent", function() { return _VR_index__WEBPACK_IMPORTED_MODULE_17__["OnAfterEnteringVRObservableEvent"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRExperienceHelper", function() { return _VR_index__WEBPACK_IMPORTED_MODULE_17__["VRExperienceHelper"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebVRFreeCamera", function() { return _VR_index__WEBPACK_IMPORTED_MODULE_17__["WebVRFreeCamera"]; }); + +/* harmony import */ var _XR_index__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./XR/index */ "./Cameras/XR/index.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRCamera", function() { return _XR_index__WEBPACK_IMPORTED_MODULE_18__["WebXRCamera"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXREnterExitUIButton", function() { return _XR_index__WEBPACK_IMPORTED_MODULE_18__["WebXREnterExitUIButton"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXREnterExitUIOptions", function() { return _XR_index__WEBPACK_IMPORTED_MODULE_18__["WebXREnterExitUIOptions"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXREnterExitUI", function() { return _XR_index__WEBPACK_IMPORTED_MODULE_18__["WebXREnterExitUI"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRState", function() { return _XR_index__WEBPACK_IMPORTED_MODULE_18__["WebXRState"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRExperienceHelper", function() { return _XR_index__WEBPACK_IMPORTED_MODULE_18__["WebXRExperienceHelper"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRController", function() { return _XR_index__WEBPACK_IMPORTED_MODULE_18__["WebXRController"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRInput", function() { return _XR_index__WEBPACK_IMPORTED_MODULE_18__["WebXRInput"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRManagedOutputCanvas", function() { return _XR_index__WEBPACK_IMPORTED_MODULE_18__["WebXRManagedOutputCanvas"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRSessionManager", function() { return _XR_index__WEBPACK_IMPORTED_MODULE_18__["WebXRSessionManager"]; }); + + + + + + + + + + + + + + + + + + + + + + +/***/ }), + +/***/ "./Cameras/targetCamera.ts": +/*!*********************************!*\ + !*** ./Cameras/targetCamera.ts ***! + \*********************************/ +/*! exports provided: TargetCamera */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TargetCamera", function() { return TargetCamera; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _camera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./camera */ "./Cameras/camera.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); + + + + +/** + * A target camera takes a mesh or position as a target and continues to look at it while it moves. + * This is the base of the follow, arc rotate cameras and Free camera + * @see http://doc.babylonjs.com/features/cameras + */ +var TargetCamera = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](TargetCamera, _super); + /** + * Instantiates a target camera that takes a meshor position as a target and continues to look at it while it moves. + * This is the base of the follow, arc rotate cameras and Free camera + * @see http://doc.babylonjs.com/features/cameras + * @param name Defines the name of the camera in the scene + * @param position Defines the start position of the camera in the scene + * @param scene Defines the scene the camera belongs to + * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined + */ + function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) { + if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; } + var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this; + /** + * Define the current direction the camera is moving to + */ + _this.cameraDirection = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0); + /** + * Define the current rotation the camera is rotating to + */ + _this.cameraRotation = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector2"](0, 0); + /** + * When set, the up vector of the camera will be updated by the rotation of the camera + */ + _this.updateUpVectorFromRotation = false; + _this._tmpQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"](); + /** + * Define the current rotation of the camera + */ + _this.rotation = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0); + /** + * Define the current speed of the camera + */ + _this.speed = 2.0; + /** + * Add cconstraint to the camera to prevent it to move freely in all directions and + * around all axis. + */ + _this.noRotationConstraint = false; + /** + * Define the current target of the camera as an object or a position. + */ + _this.lockedTarget = null; + /** @hidden */ + _this._currentTarget = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(); + /** @hidden */ + _this._initialFocalDistance = 1; + /** @hidden */ + _this._viewMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"].Zero(); + /** @hidden */ + _this._camMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"].Zero(); + /** @hidden */ + _this._cameraTransformMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"].Zero(); + /** @hidden */ + _this._cameraRotationMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"].Zero(); + /** @hidden */ + _this._referencePoint = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 1); + /** @hidden */ + _this._transformedReferencePoint = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(); + _this._globalCurrentTarget = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(); + _this._globalCurrentUpVector = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(); + _this._defaultUp = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Up(); + _this._cachedRotationZ = 0; + _this._cachedQuaternionRotationZ = 0; + return _this; + } + /** + * Gets the position in front of the camera at a given distance. + * @param distance The distance from the camera we want the position to be + * @returns the position + */ + TargetCamera.prototype.getFrontPosition = function (distance) { + this.getWorldMatrix(); + var direction = this.getTarget().subtract(this.position); + direction.normalize(); + direction.scaleInPlace(distance); + return this.globalPosition.add(direction); + }; + /** @hidden */ + TargetCamera.prototype._getLockedTargetPosition = function () { + if (!this.lockedTarget) { + return null; + } + if (this.lockedTarget.absolutePosition) { + this.lockedTarget.computeWorldMatrix(); + } + return this.lockedTarget.absolutePosition || this.lockedTarget; + }; + /** + * Store current camera state of the camera (fov, position, rotation, etc..) + * @returns the camera + */ + TargetCamera.prototype.storeState = function () { + this._storedPosition = this.position.clone(); + this._storedRotation = this.rotation.clone(); + if (this.rotationQuaternion) { + this._storedRotationQuaternion = this.rotationQuaternion.clone(); + } + return _super.prototype.storeState.call(this); + }; + /** + * Restored camera state. You must call storeState() first + * @returns whether it was successful or not + * @hidden + */ + TargetCamera.prototype._restoreStateValues = function () { + if (!_super.prototype._restoreStateValues.call(this)) { + return false; + } + this.position = this._storedPosition.clone(); + this.rotation = this._storedRotation.clone(); + if (this.rotationQuaternion) { + this.rotationQuaternion = this._storedRotationQuaternion.clone(); + } + this.cameraDirection.copyFromFloats(0, 0, 0); + this.cameraRotation.copyFromFloats(0, 0); + return true; + }; + /** @hidden */ + TargetCamera.prototype._initCache = function () { + _super.prototype._initCache.call(this); + this._cache.lockedTarget = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); + this._cache.rotation = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); + this._cache.rotationQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"](Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); + }; + /** @hidden */ + TargetCamera.prototype._updateCache = function (ignoreParentClass) { + if (!ignoreParentClass) { + _super.prototype._updateCache.call(this); + } + var lockedTargetPosition = this._getLockedTargetPosition(); + if (!lockedTargetPosition) { + this._cache.lockedTarget = null; + } + else { + if (!this._cache.lockedTarget) { + this._cache.lockedTarget = lockedTargetPosition.clone(); + } + else { + this._cache.lockedTarget.copyFrom(lockedTargetPosition); + } + } + this._cache.rotation.copyFrom(this.rotation); + if (this.rotationQuaternion) { + this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion); + } + }; + // Synchronized + /** @hidden */ + TargetCamera.prototype._isSynchronizedViewMatrix = function () { + if (!_super.prototype._isSynchronizedViewMatrix.call(this)) { + return false; + } + var lockedTargetPosition = this._getLockedTargetPosition(); + return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) + && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation)); + }; + // Methods + /** @hidden */ + TargetCamera.prototype._computeLocalCameraSpeed = function () { + var engine = this.getEngine(); + return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0))); + }; + // Target + /** + * Defines the target the camera should look at. + * This will automatically adapt alpha beta and radius to fit within the new target. + * @param target Defines the new target as a Vector or a mesh + */ + TargetCamera.prototype.setTarget = function (target) { + this.upVector.normalize(); + this._initialFocalDistance = target.subtract(this.position).length(); + if (this.position.z === target.z) { + this.position.z += _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Epsilon"]; + } + _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"].LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix); + this._camMatrix.invert(); + this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]); + var vDir = target.subtract(this.position); + if (vDir.x >= 0.0) { + this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0); + } + else { + this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0); + } + this.rotation.z = 0; + if (isNaN(this.rotation.x)) { + this.rotation.x = 0; + } + if (isNaN(this.rotation.y)) { + this.rotation.y = 0; + } + if (isNaN(this.rotation.z)) { + this.rotation.z = 0; + } + if (this.rotationQuaternion) { + _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion); + } + }; + /** + * Return the current target position of the camera. This value is expressed in local space. + * @returns the target position + */ + TargetCamera.prototype.getTarget = function () { + return this._currentTarget; + }; + /** @hidden */ + TargetCamera.prototype._decideIfNeedsToMove = function () { + return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0; + }; + /** @hidden */ + TargetCamera.prototype._updatePosition = function () { + if (this.parent) { + this.parent.getWorldMatrix().invertToRef(_Maths_math__WEBPACK_IMPORTED_MODULE_3__["Tmp"].Matrix[0]); + _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformNormalToRef(this.cameraDirection, _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Tmp"].Matrix[0], _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Tmp"].Vector3[0]); + this.position.addInPlace(_Maths_math__WEBPACK_IMPORTED_MODULE_3__["Tmp"].Vector3[0]); + return; + } + this.position.addInPlace(this.cameraDirection); + }; + /** @hidden */ + TargetCamera.prototype._checkInputs = function () { + var needToMove = this._decideIfNeedsToMove(); + var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0; + // Move + if (needToMove) { + this._updatePosition(); + } + // Rotate + if (needToRotate) { + this.rotation.x += this.cameraRotation.x; + this.rotation.y += this.cameraRotation.y; + //rotate, if quaternion is set and rotation was used + if (this.rotationQuaternion) { + var len = this.rotation.lengthSquared(); + if (len) { + _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion); + } + } + if (!this.noRotationConstraint) { + var limit = 1.570796; + if (this.rotation.x > limit) { + this.rotation.x = limit; + } + if (this.rotation.x < -limit) { + this.rotation.x = -limit; + } + } + } + // Inertia + if (needToMove) { + if (Math.abs(this.cameraDirection.x) < this.speed * _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Epsilon"]) { + this.cameraDirection.x = 0; + } + if (Math.abs(this.cameraDirection.y) < this.speed * _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Epsilon"]) { + this.cameraDirection.y = 0; + } + if (Math.abs(this.cameraDirection.z) < this.speed * _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Epsilon"]) { + this.cameraDirection.z = 0; + } + this.cameraDirection.scaleInPlace(this.inertia); + } + if (needToRotate) { + if (Math.abs(this.cameraRotation.x) < this.speed * _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Epsilon"]) { + this.cameraRotation.x = 0; + } + if (Math.abs(this.cameraRotation.y) < this.speed * _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Epsilon"]) { + this.cameraRotation.y = 0; + } + this.cameraRotation.scaleInPlace(this.inertia); + } + _super.prototype._checkInputs.call(this); + }; + TargetCamera.prototype._updateCameraRotationMatrix = function () { + if (this.rotationQuaternion) { + this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix); + } + else { + _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"].RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix); + } + }; + /** + * Update the up vector to apply the rotation of the camera (So if you changed the camera rotation.z this will let you update the up vector as well) + * @returns the current camera + */ + TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () { + _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector); + return this; + }; + /** @hidden */ + TargetCamera.prototype._getViewMatrix = function () { + if (this.lockedTarget) { + this.setTarget(this._getLockedTargetPosition()); + } + // Compute + this._updateCameraRotationMatrix(); + // Apply the changed rotation to the upVector + if (this.rotationQuaternion && this._cachedQuaternionRotationZ != this.rotationQuaternion.z) { + this._rotateUpVectorWithCameraRotationMatrix(); + this._cachedQuaternionRotationZ = this.rotationQuaternion.z; + } + else if (this._cachedRotationZ != this.rotation.z) { + this._rotateUpVectorWithCameraRotationMatrix(); + this._cachedRotationZ = this.rotation.z; + } + _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint); + // Computing target and final matrix + this.position.addToRef(this._transformedReferencePoint, this._currentTarget); + if (this.updateUpVectorFromRotation) { + if (this.rotationQuaternion) { + _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Axis"].Y.rotateByQuaternionToRef(this.rotationQuaternion, this.upVector); + } + else { + _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].FromEulerVectorToRef(this.rotation, this._tmpQuaternion); + _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Axis"].Y.rotateByQuaternionToRef(this._tmpQuaternion, this.upVector); + } + } + this._computeViewMatrix(this.position, this._currentTarget, this.upVector); + return this._viewMatrix; + }; + TargetCamera.prototype._computeViewMatrix = function (position, target, up) { + if (this.parent) { + var parentWorldMatrix = this.parent.getWorldMatrix(); + _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition); + _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget); + _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector); + this._markSyncedWithParent(); + } + else { + this._globalPosition.copyFrom(position); + this._globalCurrentTarget.copyFrom(target); + this._globalCurrentUpVector.copyFrom(up); + } + if (this.getScene().useRightHandedSystem) { + _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"].LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix); + } + else { + _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"].LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix); + } + }; + /** + * @hidden + */ + TargetCamera.prototype.createRigCamera = function (name, cameraIndex) { + if (this.cameraRigMode !== _camera__WEBPACK_IMPORTED_MODULE_2__["Camera"].RIG_MODE_NONE) { + var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene()); + if (this.cameraRigMode === _camera__WEBPACK_IMPORTED_MODULE_2__["Camera"].RIG_MODE_VR || this.cameraRigMode === _camera__WEBPACK_IMPORTED_MODULE_2__["Camera"].RIG_MODE_WEBVR) { + if (!this.rotationQuaternion) { + this.rotationQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"](); + } + rigCamera._cameraRigParams = {}; + rigCamera.rotationQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"](); + } + return rigCamera; + } + return null; + }; + /** + * @hidden + */ + TargetCamera.prototype._updateRigCameras = function () { + var camLeft = this._rigCameras[0]; + var camRight = this._rigCameras[1]; + this.computeWorldMatrix(); + switch (this.cameraRigMode) { + case _camera__WEBPACK_IMPORTED_MODULE_2__["Camera"].RIG_MODE_STEREOSCOPIC_ANAGLYPH: + case _camera__WEBPACK_IMPORTED_MODULE_2__["Camera"].RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL: + case _camera__WEBPACK_IMPORTED_MODULE_2__["Camera"].RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED: + case _camera__WEBPACK_IMPORTED_MODULE_2__["Camera"].RIG_MODE_STEREOSCOPIC_OVERUNDER: + //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance: + var leftSign = (this.cameraRigMode === _camera__WEBPACK_IMPORTED_MODULE_2__["Camera"].RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1; + var rightSign = (this.cameraRigMode === _camera__WEBPACK_IMPORTED_MODULE_2__["Camera"].RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1; + this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft); + this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle * rightSign, camRight); + break; + case _camera__WEBPACK_IMPORTED_MODULE_2__["Camera"].RIG_MODE_VR: + if (camLeft.rotationQuaternion) { + camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion); + camRight.rotationQuaternion.copyFrom(this.rotationQuaternion); + } + else { + camLeft.rotation.copyFrom(this.rotation); + camRight.rotation.copyFrom(this.rotation); + } + camLeft.position.copyFrom(this.position); + camRight.position.copyFrom(this.position); + break; + } + _super.prototype._updateRigCameras.call(this); + }; + TargetCamera.prototype._getRigCamPositionAndTarget = function (halfSpace, rigCamera) { + var target = this.getTarget(); + target.subtractToRef(this.position, TargetCamera._TargetFocalPoint); + TargetCamera._TargetFocalPoint.normalize().scaleInPlace(this._initialFocalDistance); + var newFocalTarget = TargetCamera._TargetFocalPoint.addInPlace(this.position); + _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"].TranslationToRef(-newFocalTarget.x, -newFocalTarget.y, -newFocalTarget.z, TargetCamera._TargetTransformMatrix); + TargetCamera._TargetTransformMatrix.multiplyToRef(_Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"].RotationY(halfSpace), TargetCamera._RigCamTransformMatrix); + _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"].TranslationToRef(newFocalTarget.x, newFocalTarget.y, newFocalTarget.z, TargetCamera._TargetTransformMatrix); + TargetCamera._RigCamTransformMatrix.multiplyToRef(TargetCamera._TargetTransformMatrix, TargetCamera._RigCamTransformMatrix); + _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformCoordinatesToRef(this.position, TargetCamera._RigCamTransformMatrix, rigCamera.position); + rigCamera.setTarget(newFocalTarget); + }; + /** + * Gets the current object class name. + * @return the class name + */ + TargetCamera.prototype.getClassName = function () { + return "TargetCamera"; + }; + TargetCamera._RigCamTransformMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"](); + TargetCamera._TargetTransformMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"](); + TargetCamera._TargetFocalPoint = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsVector3"])() + ], TargetCamera.prototype, "rotation", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], TargetCamera.prototype, "speed", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsMeshReference"])("lockedTargetId") + ], TargetCamera.prototype, "lockedTarget", void 0); + return TargetCamera; +}(_camera__WEBPACK_IMPORTED_MODULE_2__["Camera"])); + + + +/***/ }), + +/***/ "./Cameras/touchCamera.ts": +/*!********************************!*\ + !*** ./Cameras/touchCamera.ts ***! + \********************************/ +/*! exports provided: TouchCamera */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TouchCamera", function() { return TouchCamera; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _freeCamera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./freeCamera */ "./Cameras/freeCamera.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../node */ "./node.ts"); + + + + +_node__WEBPACK_IMPORTED_MODULE_3__["Node"].AddNodeConstructor("TouchCamera", function (name, scene) { + return function () { return new TouchCamera(name, _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(), scene); }; +}); +/** + * This represents a FPS type of camera controlled by touch. + * This is like a universal camera minus the Gamepad controls. + * @see http://doc.babylonjs.com/features/cameras#universal-camera + */ +var TouchCamera = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](TouchCamera, _super); + /** + * Instantiates a new touch camera. + * This represents a FPS type of camera controlled by touch. + * This is like a universal camera minus the Gamepad controls. + * @see http://doc.babylonjs.com/features/cameras#universal-camera + * @param name Define the name of the camera in the scene + * @param position Define the start position of the camera in the scene + * @param scene Define the scene the camera belongs to + */ + function TouchCamera(name, position, scene) { + var _this = _super.call(this, name, position, scene) || this; + _this.inputs.addTouch(); + _this._setupInputs(); + return _this; + } + Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", { + /** + * Defines the touch sensibility for rotation. + * The higher the faster. + */ + get: function () { + var touch = this.inputs.attached["touch"]; + if (touch) { + return touch.touchAngularSensibility; + } + return 0; + }, + set: function (value) { + var touch = this.inputs.attached["touch"]; + if (touch) { + touch.touchAngularSensibility = value; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", { + /** + * Defines the touch sensibility for move. + * The higher the faster. + */ + get: function () { + var touch = this.inputs.attached["touch"]; + if (touch) { + return touch.touchMoveSensibility; + } + return 0; + }, + set: function (value) { + var touch = this.inputs.attached["touch"]; + if (touch) { + touch.touchMoveSensibility = value; + } + }, + enumerable: true, + configurable: true + }); + /** + * Gets the current object class name. + * @return the class name + */ + TouchCamera.prototype.getClassName = function () { + return "TouchCamera"; + }; + /** @hidden */ + TouchCamera.prototype._setupInputs = function () { + var mouse = this.inputs.attached["mouse"]; + if (mouse) { + mouse.touchEnabled = false; + } + }; + return TouchCamera; +}(_freeCamera__WEBPACK_IMPORTED_MODULE_1__["FreeCamera"])); + + + +/***/ }), + +/***/ "./Cameras/universalCamera.ts": +/*!************************************!*\ + !*** ./Cameras/universalCamera.ts ***! + \************************************/ +/*! exports provided: UniversalCamera */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UniversalCamera", function() { return UniversalCamera; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _touchCamera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./touchCamera */ "./Cameras/touchCamera.ts"); +/* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../node */ "./node.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _camera__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./camera */ "./Cameras/camera.ts"); +/* harmony import */ var _Gamepads_gamepadSceneComponent__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Gamepads/gamepadSceneComponent */ "./Gamepads/gamepadSceneComponent.ts"); + + + + + + +_node__WEBPACK_IMPORTED_MODULE_2__["Node"].AddNodeConstructor("FreeCamera", function (name, scene) { + // Forcing to use the Universal camera + return function () { return new UniversalCamera(name, _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(), scene); }; +}); +/** + * The Universal Camera is the one to choose for first person shooter type games, and works with all the keyboard, mouse, touch and gamepads. This replaces the earlier Free Camera, + * which still works and will still be found in many Playgrounds. + * @see http://doc.babylonjs.com/features/cameras#universal-camera + */ +var UniversalCamera = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](UniversalCamera, _super); + /** + * The Universal Camera is the one to choose for first person shooter type games, and works with all the keyboard, mouse, touch and gamepads. This replaces the earlier Free Camera, + * which still works and will still be found in many Playgrounds. + * @see http://doc.babylonjs.com/features/cameras#universal-camera + * @param name Define the name of the camera in the scene + * @param position Define the start position of the camera in the scene + * @param scene Define the scene the camera belongs to + */ + function UniversalCamera(name, position, scene) { + var _this = _super.call(this, name, position, scene) || this; + _this.inputs.addGamepad(); + return _this; + } + Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", { + /** + * Defines the gamepad rotation sensiblity. + * This is the threshold from when rotation starts to be accounted for to prevent jittering. + */ + get: function () { + var gamepad = this.inputs.attached["gamepad"]; + if (gamepad) { + return gamepad.gamepadAngularSensibility; + } + return 0; + }, + set: function (value) { + var gamepad = this.inputs.attached["gamepad"]; + if (gamepad) { + gamepad.gamepadAngularSensibility = value; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", { + /** + * Defines the gamepad move sensiblity. + * This is the threshold from when moving starts to be accounted for for to prevent jittering. + */ + get: function () { + var gamepad = this.inputs.attached["gamepad"]; + if (gamepad) { + return gamepad.gamepadMoveSensibility; + } + return 0; + }, + set: function (value) { + var gamepad = this.inputs.attached["gamepad"]; + if (gamepad) { + gamepad.gamepadMoveSensibility = value; + } + }, + enumerable: true, + configurable: true + }); + /** + * Gets the current object class name. + * @return the class name + */ + UniversalCamera.prototype.getClassName = function () { + return "UniversalCamera"; + }; + return UniversalCamera; +}(_touchCamera__WEBPACK_IMPORTED_MODULE_1__["TouchCamera"])); + +_camera__WEBPACK_IMPORTED_MODULE_4__["Camera"]._createDefaultParsedCamera = function (name, scene) { + return new UniversalCamera(name, _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(), scene); +}; + + +/***/ }), + +/***/ "./Cameras/virtualJoysticksCamera.ts": +/*!*******************************************!*\ + !*** ./Cameras/virtualJoysticksCamera.ts ***! + \*******************************************/ +/*! exports provided: VirtualJoysticksCamera */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VirtualJoysticksCamera", function() { return VirtualJoysticksCamera; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _freeCamera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./freeCamera */ "./Cameras/freeCamera.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../node */ "./node.ts"); +/* harmony import */ var _Inputs_freeCameraVirtualJoystickInput__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Inputs/freeCameraVirtualJoystickInput */ "./Cameras/Inputs/freeCameraVirtualJoystickInput.ts"); + + + + + +_node__WEBPACK_IMPORTED_MODULE_3__["Node"].AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) { + return function () { return new VirtualJoysticksCamera(name, _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(), scene); }; +}); +/** + * This represents a free type of camera. It can be useful in First Person Shooter game for instance. + * It is identical to the Free Camera and simply adds by default a virtual joystick. + * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items. + * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera + */ +var VirtualJoysticksCamera = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](VirtualJoysticksCamera, _super); + /** + * Intantiates a VirtualJoysticksCamera. It can be useful in First Person Shooter game for instance. + * It is identical to the Free Camera and simply adds by default a virtual joystick. + * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items. + * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera + * @param name Define the name of the camera in the scene + * @param position Define the start position of the camera in the scene + * @param scene Define the scene the camera belongs to + */ + function VirtualJoysticksCamera(name, position, scene) { + var _this = _super.call(this, name, position, scene) || this; + _this.inputs.addVirtualJoystick(); + return _this; + } + /** + * Gets the current object class name. + * @return the class name + */ + VirtualJoysticksCamera.prototype.getClassName = function () { + return "VirtualJoysticksCamera"; + }; + return VirtualJoysticksCamera; +}(_freeCamera__WEBPACK_IMPORTED_MODULE_1__["FreeCamera"])); + + + +/***/ }), + +/***/ "./Collisions/collider.ts": +/*!********************************!*\ + !*** ./Collisions/collider.ts ***! + \********************************/ +/*! exports provided: Collider */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Collider", function() { return Collider; }); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); + +var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) { + if (boxMin.x > sphereCenter.x + sphereRadius) { + return false; + } + if (sphereCenter.x - sphereRadius > boxMax.x) { + return false; + } + if (boxMin.y > sphereCenter.y + sphereRadius) { + return false; + } + if (sphereCenter.y - sphereRadius > boxMax.y) { + return false; + } + if (boxMin.z > sphereCenter.z + sphereRadius) { + return false; + } + if (sphereCenter.z - sphereRadius > boxMax.z) { + return false; + } + return true; +}; +var getLowestRoot = (function () { + var result = { root: 0, found: false }; + return function (a, b, c, maxR) { + result.root = 0; + result.found = false; + var determinant = b * b - 4.0 * a * c; + if (determinant < 0) { + return result; + } + var sqrtD = Math.sqrt(determinant); + var r1 = (-b - sqrtD) / (2.0 * a); + var r2 = (-b + sqrtD) / (2.0 * a); + if (r1 > r2) { + var temp = r2; + r2 = r1; + r1 = temp; + } + if (r1 > 0 && r1 < maxR) { + result.root = r1; + result.found = true; + return result; + } + if (r2 > 0 && r2 < maxR) { + result.root = r2; + result.found = true; + return result; + } + return result; + }; +})(); +/** @hidden */ +var Collider = /** @class */ (function () { + function Collider() { + this._collisionPoint = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(); + this._planeIntersectionPoint = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(); + this._tempVector = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(); + this._tempVector2 = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(); + this._tempVector3 = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(); + this._tempVector4 = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(); + this._edge = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(); + this._baseToVertex = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(); + this._destinationPoint = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(); + this._slidePlaneNormal = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(); + this._displacementVector = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(); + /** @hidden */ + this._radius = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].One(); + /** @hidden */ + this._retry = 0; + /** @hidden */ + this._basePointWorld = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(); + this._velocityWorld = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(); + this._normalizedVelocity = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(); + this._collisionMask = -1; + } + Object.defineProperty(Collider.prototype, "collisionMask", { + get: function () { + return this._collisionMask; + }, + set: function (mask) { + this._collisionMask = !isNaN(mask) ? mask : -1; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Collider.prototype, "slidePlaneNormal", { + /** + * Gets the plane normal used to compute the sliding response (in local space) + */ + get: function () { + return this._slidePlaneNormal; + }, + enumerable: true, + configurable: true + }); + // Methods + /** @hidden */ + Collider.prototype._initialize = function (source, dir, e) { + this._velocity = dir; + _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].NormalizeToRef(dir, this._normalizedVelocity); + this._basePoint = source; + source.multiplyToRef(this._radius, this._basePointWorld); + dir.multiplyToRef(this._radius, this._velocityWorld); + this._velocityWorldLength = this._velocityWorld.length(); + this._epsilon = e; + this.collisionFound = false; + }; + /** @hidden */ + Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) { + pa.subtractToRef(point, this._tempVector); + pb.subtractToRef(point, this._tempVector2); + _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].CrossToRef(this._tempVector, this._tempVector2, this._tempVector4); + var d = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Dot(this._tempVector4, n); + if (d < 0) { + return false; + } + pc.subtractToRef(point, this._tempVector3); + _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4); + d = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Dot(this._tempVector4, n); + if (d < 0) { + return false; + } + _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].CrossToRef(this._tempVector3, this._tempVector, this._tempVector4); + d = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Dot(this._tempVector4, n); + return d >= 0; + }; + /** @hidden */ + Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) { + var distance = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Distance(this._basePointWorld, sphereCenter); + var max = Math.max(this._radius.x, this._radius.y, this._radius.z); + if (distance > this._velocityWorldLength + max + sphereRadius) { + return false; + } + if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max)) { + return false; + } + return true; + }; + /** @hidden */ + Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) { + var t0; + var embeddedInPlane = false; + //defensive programming, actually not needed. + if (!trianglePlaneArray) { + trianglePlaneArray = []; + } + if (!trianglePlaneArray[faceIndex]) { + trianglePlaneArray[faceIndex] = new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Plane"](0, 0, 0, 0); + trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3); + } + var trianglePlane = trianglePlaneArray[faceIndex]; + if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0)) { + return; + } + var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint); + var normalDotVelocity = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Dot(trianglePlane.normal, this._velocity); + if (normalDotVelocity == 0) { + if (Math.abs(signedDistToTrianglePlane) >= 1.0) { + return; + } + embeddedInPlane = true; + t0 = 0; + } + else { + t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity; + var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity; + if (t0 > t1) { + var temp = t1; + t1 = t0; + t0 = temp; + } + if (t0 > 1.0 || t1 < 0.0) { + return; + } + if (t0 < 0) { + t0 = 0; + } + if (t0 > 1.0) { + t0 = 1.0; + } + } + this._collisionPoint.copyFromFloats(0, 0, 0); + var found = false; + var t = 1.0; + if (!embeddedInPlane) { + this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint); + this._velocity.scaleToRef(t0, this._tempVector); + this._planeIntersectionPoint.addInPlace(this._tempVector); + if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) { + found = true; + t = t0; + this._collisionPoint.copyFrom(this._planeIntersectionPoint); + } + } + if (!found) { + var velocitySquaredLength = this._velocity.lengthSquared(); + var a = velocitySquaredLength; + this._basePoint.subtractToRef(p1, this._tempVector); + var b = 2.0 * (_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Dot(this._velocity, this._tempVector)); + var c = this._tempVector.lengthSquared() - 1.0; + var lowestRoot = getLowestRoot(a, b, c, t); + if (lowestRoot.found) { + t = lowestRoot.root; + found = true; + this._collisionPoint.copyFrom(p1); + } + this._basePoint.subtractToRef(p2, this._tempVector); + b = 2.0 * (_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Dot(this._velocity, this._tempVector)); + c = this._tempVector.lengthSquared() - 1.0; + lowestRoot = getLowestRoot(a, b, c, t); + if (lowestRoot.found) { + t = lowestRoot.root; + found = true; + this._collisionPoint.copyFrom(p2); + } + this._basePoint.subtractToRef(p3, this._tempVector); + b = 2.0 * (_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Dot(this._velocity, this._tempVector)); + c = this._tempVector.lengthSquared() - 1.0; + lowestRoot = getLowestRoot(a, b, c, t); + if (lowestRoot.found) { + t = lowestRoot.root; + found = true; + this._collisionPoint.copyFrom(p3); + } + p2.subtractToRef(p1, this._edge); + p1.subtractToRef(this._basePoint, this._baseToVertex); + var edgeSquaredLength = this._edge.lengthSquared(); + var edgeDotVelocity = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Dot(this._edge, this._velocity); + var edgeDotBaseToVertex = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Dot(this._edge, this._baseToVertex); + a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity; + b = edgeSquaredLength * (2.0 * _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex; + c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex; + lowestRoot = getLowestRoot(a, b, c, t); + if (lowestRoot.found) { + var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength; + if (f >= 0.0 && f <= 1.0) { + t = lowestRoot.root; + found = true; + this._edge.scaleInPlace(f); + p1.addToRef(this._edge, this._collisionPoint); + } + } + p3.subtractToRef(p2, this._edge); + p2.subtractToRef(this._basePoint, this._baseToVertex); + edgeSquaredLength = this._edge.lengthSquared(); + edgeDotVelocity = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Dot(this._edge, this._velocity); + edgeDotBaseToVertex = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Dot(this._edge, this._baseToVertex); + a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity; + b = edgeSquaredLength * (2.0 * _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex; + c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex; + lowestRoot = getLowestRoot(a, b, c, t); + if (lowestRoot.found) { + f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength; + if (f >= 0.0 && f <= 1.0) { + t = lowestRoot.root; + found = true; + this._edge.scaleInPlace(f); + p2.addToRef(this._edge, this._collisionPoint); + } + } + p1.subtractToRef(p3, this._edge); + p3.subtractToRef(this._basePoint, this._baseToVertex); + edgeSquaredLength = this._edge.lengthSquared(); + edgeDotVelocity = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Dot(this._edge, this._velocity); + edgeDotBaseToVertex = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Dot(this._edge, this._baseToVertex); + a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity; + b = edgeSquaredLength * (2.0 * _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex; + c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex; + lowestRoot = getLowestRoot(a, b, c, t); + if (lowestRoot.found) { + f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength; + if (f >= 0.0 && f <= 1.0) { + t = lowestRoot.root; + found = true; + this._edge.scaleInPlace(f); + p3.addToRef(this._edge, this._collisionPoint); + } + } + } + if (found) { + var distToCollision = t * this._velocity.length(); + if (!this.collisionFound || distToCollision < this._nearestDistance) { + if (!this.intersectionPoint) { + this.intersectionPoint = this._collisionPoint.clone(); + } + else { + this.intersectionPoint.copyFrom(this._collisionPoint); + } + this._nearestDistance = distToCollision; + this.collisionFound = true; + } + } + }; + /** @hidden */ + Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) { + for (var i = indexStart; i < indexEnd; i += 3) { + var p1 = pts[indices[i] - decal]; + var p2 = pts[indices[i + 1] - decal]; + var p3 = pts[indices[i + 2] - decal]; + this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial); + } + }; + /** @hidden */ + Collider.prototype._getResponse = function (pos, vel) { + pos.addToRef(vel, this._destinationPoint); + vel.scaleInPlace((this._nearestDistance / vel.length())); + this._basePoint.addToRef(vel, pos); + pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal); + this._slidePlaneNormal.normalize(); + this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector); + pos.addInPlace(this._displacementVector); + this.intersectionPoint.addInPlace(this._displacementVector); + this._slidePlaneNormal.scaleInPlace(_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Plane"].SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint)); + this._destinationPoint.subtractInPlace(this._slidePlaneNormal); + this._destinationPoint.subtractToRef(this.intersectionPoint, vel); + }; + return Collider; +}()); + + + +/***/ }), + +/***/ "./Collisions/collisionCoordinator.ts": +/*!********************************************!*\ + !*** ./Collisions/collisionCoordinator.ts ***! + \********************************************/ +/*! exports provided: DefaultCollisionCoordinator */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DefaultCollisionCoordinator", function() { return DefaultCollisionCoordinator; }); +/* harmony import */ var _scene__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../scene */ "./scene.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Engines/engine */ "./Engines/engine.ts"); +/* harmony import */ var _collider__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./collider */ "./Collisions/collider.ts"); + + + + +/** @hidden */ +var DefaultCollisionCoordinator = /** @class */ (function () { + function DefaultCollisionCoordinator() { + this._scaledPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); + this._scaledVelocity = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); + this._finalPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); + } + DefaultCollisionCoordinator.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) { + position.divideToRef(collider._radius, this._scaledPosition); + displacement.divideToRef(collider._radius, this._scaledVelocity); + collider.collidedMesh = null; + collider._retry = 0; + collider._initialVelocity = this._scaledVelocity; + collider._initialPosition = this._scaledPosition; + this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh); + this._finalPosition.multiplyInPlace(collider._radius); + //run the callback + onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh); + }; + DefaultCollisionCoordinator.prototype.createCollider = function () { + return new _collider__WEBPACK_IMPORTED_MODULE_3__["Collider"](); + }; + DefaultCollisionCoordinator.prototype.init = function (scene) { + this._scene = scene; + }; + DefaultCollisionCoordinator.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) { + if (excludedMesh === void 0) { excludedMesh = null; } + var closeDistance = _Engines_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].CollisionsEpsilon * 10.0; + if (collider._retry >= maximumRetry) { + finalPosition.copyFrom(position); + return; + } + // Check if this is a mesh else camera or -1 + var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask); + collider._initialize(position, velocity, closeDistance); + // Check all meshes + for (var index = 0; index < this._scene.meshes.length; index++) { + var mesh = this._scene.meshes[index]; + if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) { + mesh._checkCollision(collider); + } + } + if (!collider.collisionFound) { + position.addToRef(velocity, finalPosition); + return; + } + if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) { + collider._getResponse(position, velocity); + } + if (velocity.length() <= closeDistance) { + finalPosition.copyFrom(position); + return; + } + collider._retry++; + this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh); + }; + return DefaultCollisionCoordinator; +}()); + +_scene__WEBPACK_IMPORTED_MODULE_0__["Scene"].CollisionCoordinatorFactory = function () { + return new DefaultCollisionCoordinator(); +}; + + +/***/ }), + +/***/ "./Collisions/index.ts": +/*!*****************************!*\ + !*** ./Collisions/index.ts ***! + \*****************************/ +/*! exports provided: Collider, DefaultCollisionCoordinator, PickingInfo, IntersectionInfo, _MeshCollisionData */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _collider__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./collider */ "./Collisions/collider.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Collider", function() { return _collider__WEBPACK_IMPORTED_MODULE_0__["Collider"]; }); + +/* harmony import */ var _collisionCoordinator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./collisionCoordinator */ "./Collisions/collisionCoordinator.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DefaultCollisionCoordinator", function() { return _collisionCoordinator__WEBPACK_IMPORTED_MODULE_1__["DefaultCollisionCoordinator"]; }); + +/* harmony import */ var _pickingInfo__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./pickingInfo */ "./Collisions/pickingInfo.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PickingInfo", function() { return _pickingInfo__WEBPACK_IMPORTED_MODULE_2__["PickingInfo"]; }); + +/* harmony import */ var _intersectionInfo__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./intersectionInfo */ "./Collisions/intersectionInfo.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "IntersectionInfo", function() { return _intersectionInfo__WEBPACK_IMPORTED_MODULE_3__["IntersectionInfo"]; }); + +/* harmony import */ var _meshCollisionData__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./meshCollisionData */ "./Collisions/meshCollisionData.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_MeshCollisionData", function() { return _meshCollisionData__WEBPACK_IMPORTED_MODULE_4__["_MeshCollisionData"]; }); + + + + + + + + +/***/ }), + +/***/ "./Collisions/intersectionInfo.ts": +/*!****************************************!*\ + !*** ./Collisions/intersectionInfo.ts ***! + \****************************************/ +/*! exports provided: IntersectionInfo */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "IntersectionInfo", function() { return IntersectionInfo; }); +/** + * @hidden + */ +var IntersectionInfo = /** @class */ (function () { + function IntersectionInfo(bu, bv, distance) { + this.bu = bu; + this.bv = bv; + this.distance = distance; + this.faceId = 0; + this.subMeshId = 0; + } + return IntersectionInfo; +}()); + + + +/***/ }), + +/***/ "./Collisions/meshCollisionData.ts": +/*!*****************************************!*\ + !*** ./Collisions/meshCollisionData.ts ***! + \*****************************************/ +/*! exports provided: _MeshCollisionData */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_MeshCollisionData", function() { return _MeshCollisionData; }); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); + +/** + * @hidden + */ +var _MeshCollisionData = /** @class */ (function () { + function _MeshCollisionData() { + this._checkCollisions = false; + this._collisionMask = -1; + this._collisionGroup = -1; + this._collider = null; + this._oldPositionForCollisions = new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"](0, 0, 0); + this._diffPositionForCollisions = new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"](0, 0, 0); + } + return _MeshCollisionData; +}()); + + + +/***/ }), + +/***/ "./Collisions/pickingInfo.ts": +/*!***********************************!*\ + !*** ./Collisions/pickingInfo.ts ***! + \***********************************/ +/*! exports provided: PickingInfo */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PickingInfo", function() { return PickingInfo; }); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Meshes_buffer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Meshes/buffer */ "./Meshes/buffer.ts"); + + +/** + * Information about the result of picking within a scene + * @see https://doc.babylonjs.com/babylon101/picking_collisions + */ +var PickingInfo = /** @class */ (function () { + function PickingInfo() { + /** @hidden */ + this._pickingUnavailable = false; + /** + * If the pick collided with an object + */ + this.hit = false; + /** + * Distance away where the pick collided + */ + this.distance = 0; + /** + * The location of pick collision + */ + this.pickedPoint = null; + /** + * The mesh corresponding the the pick collision + */ + this.pickedMesh = null; + /** (See getTextureCoordinates) The barycentric U coordinate that is used when calculating the texture coordinates of the collision.*/ + this.bu = 0; + /** (See getTextureCoordinates) The barycentric V coordinate that is used when calculating the texture coordinates of the collision.*/ + this.bv = 0; + /** The index of the face on the mesh that was picked, or the index of the Line if the picked Mesh is a LinesMesh */ + this.faceId = -1; + /** Id of the the submesh that was picked */ + this.subMeshId = 0; + /** If a sprite was picked, this will be the sprite the pick collided with */ + this.pickedSprite = null; + /** + * If a mesh was used to do the picking (eg. 6dof controller) this will be populated. + */ + this.originMesh = null; + /** + * The ray that was used to perform the picking. + */ + this.ray = null; + } + /** + * Gets the normal correspodning to the face the pick collided with + * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false) + * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map + * @returns The normal correspodning to the face the pick collided with + */ + PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) { + if (useWorldCoordinates === void 0) { useWorldCoordinates = false; } + if (useVerticesNormals === void 0) { useVerticesNormals = true; } + if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_1__["VertexBuffer"].NormalKind)) { + return null; + } + var indices = this.pickedMesh.getIndices(); + if (!indices) { + return null; + } + var result; + if (useVerticesNormals) { + var normals = this.pickedMesh.getVerticesData(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_1__["VertexBuffer"].NormalKind); + var normal0 = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].FromArray(normals, indices[this.faceId * 3] * 3); + var normal1 = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].FromArray(normals, indices[this.faceId * 3 + 1] * 3); + var normal2 = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].FromArray(normals, indices[this.faceId * 3 + 2] * 3); + normal0 = normal0.scale(this.bu); + normal1 = normal1.scale(this.bv); + normal2 = normal2.scale(1.0 - this.bu - this.bv); + result = new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"](normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z); + } + else { + var positions = this.pickedMesh.getVerticesData(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_1__["VertexBuffer"].PositionKind); + var vertex1 = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].FromArray(positions, indices[this.faceId * 3] * 3); + var vertex2 = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].FromArray(positions, indices[this.faceId * 3 + 1] * 3); + var vertex3 = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].FromArray(positions, indices[this.faceId * 3 + 2] * 3); + var p1p2 = vertex1.subtract(vertex2); + var p3p2 = vertex3.subtract(vertex2); + result = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Cross(p1p2, p3p2); + } + if (useWorldCoordinates) { + var wm = this.pickedMesh.getWorldMatrix(); + if (this.pickedMesh.nonUniformScaling) { + _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tmp"].Matrix[0].copyFrom(wm); + wm = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tmp"].Matrix[0]; + wm.setTranslationFromFloats(0, 0, 0); + wm.invert(); + wm.transposeToRef(_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tmp"].Matrix[1]); + wm = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tmp"].Matrix[1]; + } + result = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].TransformNormal(result, wm); + } + result.normalize(); + return result; + }; + /** + * Gets the texture coordinates of where the pick occured + * @returns the vector containing the coordnates of the texture + */ + PickingInfo.prototype.getTextureCoordinates = function () { + if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_1__["VertexBuffer"].UVKind)) { + return null; + } + var indices = this.pickedMesh.getIndices(); + if (!indices) { + return null; + } + var uvs = this.pickedMesh.getVerticesData(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_1__["VertexBuffer"].UVKind); + if (!uvs) { + return null; + } + var uv0 = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector2"].FromArray(uvs, indices[this.faceId * 3] * 2); + var uv1 = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector2"].FromArray(uvs, indices[this.faceId * 3 + 1] * 2); + var uv2 = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector2"].FromArray(uvs, indices[this.faceId * 3 + 2] * 2); + uv0 = uv0.scale(1.0 - this.bu - this.bv); + uv1 = uv1.scale(this.bu); + uv2 = uv2.scale(this.bv); + return new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector2"](uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y); + }; + return PickingInfo; +}()); + + + +/***/ }), + +/***/ "./Culling/Octrees/index.ts": +/*!**********************************!*\ + !*** ./Culling/Octrees/index.ts ***! + \**********************************/ +/*! exports provided: Octree, OctreeBlock, OctreeSceneComponent */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _octree__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./octree */ "./Culling/Octrees/octree.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Octree", function() { return _octree__WEBPACK_IMPORTED_MODULE_0__["Octree"]; }); + +/* harmony import */ var _octreeBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./octreeBlock */ "./Culling/Octrees/octreeBlock.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OctreeBlock", function() { return _octreeBlock__WEBPACK_IMPORTED_MODULE_1__["OctreeBlock"]; }); + +/* harmony import */ var _octreeSceneComponent__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./octreeSceneComponent */ "./Culling/Octrees/octreeSceneComponent.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OctreeSceneComponent", function() { return _octreeSceneComponent__WEBPACK_IMPORTED_MODULE_2__["OctreeSceneComponent"]; }); + + + + + + +/***/ }), + +/***/ "./Culling/Octrees/octree.ts": +/*!***********************************!*\ + !*** ./Culling/Octrees/octree.ts ***! + \***********************************/ +/*! exports provided: Octree */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Octree", function() { return Octree; }); +/* harmony import */ var _Misc_smartArray__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Misc/smartArray */ "./Misc/smartArray.ts"); +/* harmony import */ var _octreeBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./octreeBlock */ "./Culling/Octrees/octreeBlock.ts"); + + +/** + * Octrees are a really powerful data structure that can quickly select entities based on space coordinates. + * @see https://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees + */ +var Octree = /** @class */ (function () { + /** + * Creates a octree + * @see https://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees + * @param creationFunc function to be used to instatiate the octree + * @param maxBlockCapacity defines the maximum number of meshes you want on your octree's leaves (default: 64) + * @param maxDepth defines the maximum depth (sub-levels) for your octree. Default value is 2, which means 8 8 8 = 512 blocks :) (This parameter takes precedence over capacity.) + */ + function Octree(creationFunc, maxBlockCapacity, + /** Defines the maximum depth (sub-levels) for your octree. Default value is 2, which means 8 8 8 = 512 blocks :) (This parameter takes precedence over capacity.) */ + maxDepth) { + if (maxDepth === void 0) { maxDepth = 2; } + this.maxDepth = maxDepth; + /** + * Content stored in the octree + */ + this.dynamicContent = new Array(); + this._maxBlockCapacity = maxBlockCapacity || 64; + this._selectionContent = new _Misc_smartArray__WEBPACK_IMPORTED_MODULE_0__["SmartArrayNoDuplicate"](1024); + this._creationFunc = creationFunc; + } + // Methods + /** + * Updates the octree by adding blocks for the passed in meshes within the min and max world parameters + * @param worldMin worldMin for the octree blocks var blockSize = new Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2); + * @param worldMax worldMax for the octree blocks var blockSize = new Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2); + * @param entries meshes to be added to the octree blocks + */ + Octree.prototype.update = function (worldMin, worldMax, entries) { + _octreeBlock__WEBPACK_IMPORTED_MODULE_1__["OctreeBlock"]._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc); + }; + /** + * Adds a mesh to the octree + * @param entry Mesh to add to the octree + */ + Octree.prototype.addMesh = function (entry) { + for (var index = 0; index < this.blocks.length; index++) { + var block = this.blocks[index]; + block.addEntry(entry); + } + }; + /** + * Remove an element from the octree + * @param entry defines the element to remove + */ + Octree.prototype.removeMesh = function (entry) { + for (var index = 0; index < this.blocks.length; index++) { + var block = this.blocks[index]; + block.removeEntry(entry); + } + }; + /** + * Selects an array of meshes within the frustum + * @param frustumPlanes The frustum planes to use which will select all meshes within it + * @param allowDuplicate If duplicate objects are allowed in the resulting object array + * @returns array of meshes within the frustum + */ + Octree.prototype.select = function (frustumPlanes, allowDuplicate) { + this._selectionContent.reset(); + for (var index = 0; index < this.blocks.length; index++) { + var block = this.blocks[index]; + block.select(frustumPlanes, this._selectionContent, allowDuplicate); + } + if (allowDuplicate) { + this._selectionContent.concat(this.dynamicContent); + } + else { + this._selectionContent.concatWithNoDuplicate(this.dynamicContent); + } + return this._selectionContent; + }; + /** + * Test if the octree intersect with the given bounding sphere and if yes, then add its content to the selection array + * @param sphereCenter defines the bounding sphere center + * @param sphereRadius defines the bounding sphere radius + * @param allowDuplicate defines if the selection array can contains duplicated entries + * @returns an array of objects that intersect the sphere + */ + Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) { + this._selectionContent.reset(); + for (var index = 0; index < this.blocks.length; index++) { + var block = this.blocks[index]; + block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate); + } + if (allowDuplicate) { + this._selectionContent.concat(this.dynamicContent); + } + else { + this._selectionContent.concatWithNoDuplicate(this.dynamicContent); + } + return this._selectionContent; + }; + /** + * Test if the octree intersect with the given ray and if yes, then add its content to resulting array + * @param ray defines the ray to test with + * @returns array of intersected objects + */ + Octree.prototype.intersectsRay = function (ray) { + this._selectionContent.reset(); + for (var index = 0; index < this.blocks.length; index++) { + var block = this.blocks[index]; + block.intersectsRay(ray, this._selectionContent); + } + this._selectionContent.concatWithNoDuplicate(this.dynamicContent); + return this._selectionContent; + }; + /** + * Adds a mesh into the octree block if it intersects the block + */ + Octree.CreationFuncForMeshes = function (entry, block) { + var boundingInfo = entry.getBoundingInfo(); + if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) { + block.entries.push(entry); + } + }; + /** + * Adds a submesh into the octree block if it intersects the block + */ + Octree.CreationFuncForSubMeshes = function (entry, block) { + var boundingInfo = entry.getBoundingInfo(); + if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) { + block.entries.push(entry); + } + }; + return Octree; +}()); + + + +/***/ }), + +/***/ "./Culling/Octrees/octreeBlock.ts": +/*!****************************************!*\ + !*** ./Culling/Octrees/octreeBlock.ts ***! + \****************************************/ +/*! exports provided: OctreeBlock */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OctreeBlock", function() { return OctreeBlock; }); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Culling_boundingBox__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Culling/boundingBox */ "./Culling/boundingBox.ts"); + + +/** + * Class used to store a cell in an octree + * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees + */ +var OctreeBlock = /** @class */ (function () { + /** + * Creates a new block + * @param minPoint defines the minimum vector (in world space) of the block's bounding box + * @param maxPoint defines the maximum vector (in world space) of the block's bounding box + * @param capacity defines the maximum capacity of this block (if capacity is reached the block will be split into sub blocks) + * @param depth defines the current depth of this block in the octree + * @param maxDepth defines the maximal depth allowed (beyond this value, the capacity is ignored) + * @param creationFunc defines a callback to call when an element is added to the block + */ + function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) { + /** + * Gets the content of the current block + */ + this.entries = new Array(); + this._boundingVectors = new Array(); + this._capacity = capacity; + this._depth = depth; + this._maxDepth = maxDepth; + this._creationFunc = creationFunc; + this._minPoint = minPoint; + this._maxPoint = maxPoint; + this._boundingVectors.push(minPoint.clone()); + this._boundingVectors.push(maxPoint.clone()); + this._boundingVectors.push(minPoint.clone()); + this._boundingVectors[2].x = maxPoint.x; + this._boundingVectors.push(minPoint.clone()); + this._boundingVectors[3].y = maxPoint.y; + this._boundingVectors.push(minPoint.clone()); + this._boundingVectors[4].z = maxPoint.z; + this._boundingVectors.push(maxPoint.clone()); + this._boundingVectors[5].z = minPoint.z; + this._boundingVectors.push(maxPoint.clone()); + this._boundingVectors[6].x = minPoint.x; + this._boundingVectors.push(maxPoint.clone()); + this._boundingVectors[7].y = minPoint.y; + } + Object.defineProperty(OctreeBlock.prototype, "capacity", { + // Property + /** + * Gets the maximum capacity of this block (if capacity is reached the block will be split into sub blocks) + */ + get: function () { + return this._capacity; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(OctreeBlock.prototype, "minPoint", { + /** + * Gets the minimum vector (in world space) of the block's bounding box + */ + get: function () { + return this._minPoint; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(OctreeBlock.prototype, "maxPoint", { + /** + * Gets the maximum vector (in world space) of the block's bounding box + */ + get: function () { + return this._maxPoint; + }, + enumerable: true, + configurable: true + }); + // Methods + /** + * Add a new element to this block + * @param entry defines the element to add + */ + OctreeBlock.prototype.addEntry = function (entry) { + if (this.blocks) { + for (var index = 0; index < this.blocks.length; index++) { + var block = this.blocks[index]; + block.addEntry(entry); + } + return; + } + this._creationFunc(entry, this); + if (this.entries.length > this.capacity && this._depth < this._maxDepth) { + this.createInnerBlocks(); + } + }; + /** + * Remove an element from this block + * @param entry defines the element to remove + */ + OctreeBlock.prototype.removeEntry = function (entry) { + if (this.blocks) { + for (var index = 0; index < this.blocks.length; index++) { + var block = this.blocks[index]; + block.removeEntry(entry); + } + return; + } + var entryIndex = this.entries.indexOf(entry); + if (entryIndex > -1) { + this.entries.splice(entryIndex, 1); + } + }; + /** + * Add an array of elements to this block + * @param entries defines the array of elements to add + */ + OctreeBlock.prototype.addEntries = function (entries) { + for (var index = 0; index < entries.length; index++) { + var mesh = entries[index]; + this.addEntry(mesh); + } + }; + /** + * Test if the current block intersects the furstum planes and if yes, then add its content to the selection array + * @param frustumPlanes defines the frustum planes to test + * @param selection defines the array to store current content if selection is positive + * @param allowDuplicate defines if the selection array can contains duplicated entries + */ + OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) { + if (_Culling_boundingBox__WEBPACK_IMPORTED_MODULE_1__["BoundingBox"].IsInFrustum(this._boundingVectors, frustumPlanes)) { + if (this.blocks) { + for (var index = 0; index < this.blocks.length; index++) { + var block = this.blocks[index]; + block.select(frustumPlanes, selection, allowDuplicate); + } + return; + } + if (allowDuplicate) { + selection.concat(this.entries); + } + else { + selection.concatWithNoDuplicate(this.entries); + } + } + }; + /** + * Test if the current block intersect with the given bounding sphere and if yes, then add its content to the selection array + * @param sphereCenter defines the bounding sphere center + * @param sphereRadius defines the bounding sphere radius + * @param selection defines the array to store current content if selection is positive + * @param allowDuplicate defines if the selection array can contains duplicated entries + */ + OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) { + if (_Culling_boundingBox__WEBPACK_IMPORTED_MODULE_1__["BoundingBox"].IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) { + if (this.blocks) { + for (var index = 0; index < this.blocks.length; index++) { + var block = this.blocks[index]; + block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate); + } + return; + } + if (allowDuplicate) { + selection.concat(this.entries); + } + else { + selection.concatWithNoDuplicate(this.entries); + } + } + }; + /** + * Test if the current block intersect with the given ray and if yes, then add its content to the selection array + * @param ray defines the ray to test with + * @param selection defines the array to store current content if selection is positive + */ + OctreeBlock.prototype.intersectsRay = function (ray, selection) { + if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) { + if (this.blocks) { + for (var index = 0; index < this.blocks.length; index++) { + var block = this.blocks[index]; + block.intersectsRay(ray, selection); + } + return; + } + selection.concatWithNoDuplicate(this.entries); + } + }; + /** + * Subdivide the content into child blocks (this block will then be empty) + */ + OctreeBlock.prototype.createInnerBlocks = function () { + OctreeBlock._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc); + }; + /** + * @hidden + */ + OctreeBlock._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) { + target.blocks = new Array(); + var blockSize = new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"]((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2); + // Segmenting space + for (var x = 0; x < 2; x++) { + for (var y = 0; y < 2; y++) { + for (var z = 0; z < 2; z++) { + var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z)); + var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1)); + var block = new OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc); + block.addEntries(entries); + target.blocks.push(block); + } + } + } + }; + return OctreeBlock; +}()); + + + +/***/ }), + +/***/ "./Culling/Octrees/octreeSceneComponent.ts": +/*!*************************************************!*\ + !*** ./Culling/Octrees/octreeSceneComponent.ts ***! + \*************************************************/ +/*! exports provided: OctreeSceneComponent */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OctreeSceneComponent", function() { return OctreeSceneComponent; }); +/* harmony import */ var _scene__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../scene */ "./scene.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Meshes/abstractMesh */ "./Meshes/abstractMesh.ts"); +/* harmony import */ var _Culling_ray__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Culling/ray */ "./Culling/ray.ts"); +/* harmony import */ var _sceneComponent__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../sceneComponent */ "./sceneComponent.ts"); +/* harmony import */ var _octree__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./octree */ "./Culling/Octrees/octree.ts"); + + + + + + +_scene__WEBPACK_IMPORTED_MODULE_0__["Scene"].prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) { + if (maxCapacity === void 0) { maxCapacity = 64; } + if (maxDepth === void 0) { maxDepth = 2; } + var component = this._getComponent(_sceneComponent__WEBPACK_IMPORTED_MODULE_4__["SceneComponentConstants"].NAME_OCTREE); + if (!component) { + component = new OctreeSceneComponent(this); + this._addComponent(component); + } + if (!this._selectionOctree) { + this._selectionOctree = new _octree__WEBPACK_IMPORTED_MODULE_5__["Octree"](_octree__WEBPACK_IMPORTED_MODULE_5__["Octree"].CreationFuncForMeshes, maxCapacity, maxDepth); + } + var worldExtends = this.getWorldExtends(); + // Update octree + this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes); + return this._selectionOctree; +}; +Object.defineProperty(_scene__WEBPACK_IMPORTED_MODULE_0__["Scene"].prototype, "selectionOctree", { + get: function () { + return this._selectionOctree; + }, + enumerable: true, + configurable: true +}); +/** + * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations. + * Please note that you must have a decent number of submeshes to get performance improvements when using an octree + * @param maxCapacity defines the maximum size of each block (64 by default) + * @param maxDepth defines the maximum depth to use (no more than 2 levels by default) + * @returns the new octree + * @see https://www.babylonjs-playground.com/#NA4OQ#12 + * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees + */ +_Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_2__["AbstractMesh"].prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) { + if (maxCapacity === void 0) { maxCapacity = 64; } + if (maxDepth === void 0) { maxDepth = 2; } + var scene = this.getScene(); + var component = scene._getComponent(_sceneComponent__WEBPACK_IMPORTED_MODULE_4__["SceneComponentConstants"].NAME_OCTREE); + if (!component) { + component = new OctreeSceneComponent(scene); + scene._addComponent(component); + } + if (!this._submeshesOctree) { + this._submeshesOctree = new _octree__WEBPACK_IMPORTED_MODULE_5__["Octree"](_octree__WEBPACK_IMPORTED_MODULE_5__["Octree"].CreationFuncForSubMeshes, maxCapacity, maxDepth); + } + this.computeWorldMatrix(true); + var boundingInfo = this.getBoundingInfo(); + // Update octree + var bbox = boundingInfo.boundingBox; + this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes); + return this._submeshesOctree; +}; +/** + * Defines the octree scene component responsible to manage any octrees + * in a given scene. + */ +var OctreeSceneComponent = /** @class */ (function () { + /** + * Creates a new instance of the component for the given scene + * @param scene Defines the scene to register the component in + */ + function OctreeSceneComponent(scene) { + /** + * The component name help to identify the component in the list of scene components. + */ + this.name = _sceneComponent__WEBPACK_IMPORTED_MODULE_4__["SceneComponentConstants"].NAME_OCTREE; + /** + * Indicates if the meshes have been checked to make sure they are isEnabled() + */ + this.checksIsEnabled = true; + this._tempRay = new _Culling_ray__WEBPACK_IMPORTED_MODULE_3__["Ray"](_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(), new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"](1, 1, 1)); + this.scene = scene; + this.scene.getActiveMeshCandidates = this.getActiveMeshCandidates.bind(this); + this.scene.getActiveSubMeshCandidates = this.getActiveSubMeshCandidates.bind(this); + this.scene.getCollidingSubMeshCandidates = this.getCollidingSubMeshCandidates.bind(this); + this.scene.getIntersectingSubMeshCandidates = this.getIntersectingSubMeshCandidates.bind(this); + } + /** + * Registers the component in a given scene + */ + OctreeSceneComponent.prototype.register = function () { + var _this = this; + this.scene.onMeshRemovedObservable.add(function (mesh) { + var sceneOctree = _this.scene.selectionOctree; + if (sceneOctree !== undefined && sceneOctree !== null) { + var index = sceneOctree.dynamicContent.indexOf(mesh); + if (index !== -1) { + sceneOctree.dynamicContent.splice(index, 1); + } + } + }); + this.scene.onMeshImportedObservable.add(function (mesh) { + var sceneOctree = _this.scene.selectionOctree; + if (sceneOctree !== undefined && sceneOctree !== null) { + sceneOctree.addMesh(mesh); + } + }); + }; + /** + * Return the list of active meshes + * @returns the list of active meshes + */ + OctreeSceneComponent.prototype.getActiveMeshCandidates = function () { + if (this.scene._selectionOctree) { + var selection = this.scene._selectionOctree.select(this.scene.frustumPlanes); + return selection; + } + return this.scene._getDefaultMeshCandidates(); + }; + /** + * Return the list of active sub meshes + * @param mesh The mesh to get the candidates sub meshes from + * @returns the list of active sub meshes + */ + OctreeSceneComponent.prototype.getActiveSubMeshCandidates = function (mesh) { + if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) { + var intersections = mesh._submeshesOctree.select(this.scene.frustumPlanes); + return intersections; + } + return this.scene._getDefaultSubMeshCandidates(mesh); + }; + /** + * Return the list of sub meshes intersecting with a given local ray + * @param mesh defines the mesh to find the submesh for + * @param localRay defines the ray in local space + * @returns the list of intersecting sub meshes + */ + OctreeSceneComponent.prototype.getIntersectingSubMeshCandidates = function (mesh, localRay) { + if (mesh._submeshesOctree && mesh.useOctreeForPicking) { + _Culling_ray__WEBPACK_IMPORTED_MODULE_3__["Ray"].TransformToRef(localRay, mesh.getWorldMatrix(), this._tempRay); + var intersections = mesh._submeshesOctree.intersectsRay(this._tempRay); + return intersections; + } + return this.scene._getDefaultSubMeshCandidates(mesh); + }; + /** + * Return the list of sub meshes colliding with a collider + * @param mesh defines the mesh to find the submesh for + * @param collider defines the collider to evaluate the collision against + * @returns the list of colliding sub meshes + */ + OctreeSceneComponent.prototype.getCollidingSubMeshCandidates = function (mesh, collider) { + if (mesh._submeshesOctree && mesh.useOctreeForCollisions) { + var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z); + var intersections = mesh._submeshesOctree.intersects(collider._basePointWorld, radius); + return intersections; + } + return this.scene._getDefaultSubMeshCandidates(mesh); + }; + /** + * Rebuilds the elements related to this component in case of + * context lost for instance. + */ + OctreeSceneComponent.prototype.rebuild = function () { + // Nothing to do here. + }; + /** + * Disposes the component and the associated ressources. + */ + OctreeSceneComponent.prototype.dispose = function () { + // Nothing to do here. + }; + return OctreeSceneComponent; +}()); + + + +/***/ }), + +/***/ "./Culling/boundingBox.ts": +/*!********************************!*\ + !*** ./Culling/boundingBox.ts ***! + \********************************/ +/*! exports provided: BoundingBox */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BoundingBox", function() { return BoundingBox; }); +/* harmony import */ var _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/arrayTools */ "./Misc/arrayTools.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); + + +/** + * Class used to store bounding box information + */ +var BoundingBox = /** @class */ (function () { + /** + * Creates a new bounding box + * @param min defines the minimum vector (in local space) + * @param max defines the maximum vector (in local space) + * @param worldMatrix defines the new world matrix + */ + function BoundingBox(min, max, worldMatrix) { + /** + * Gets the 8 vectors representing the bounding box in local space + */ + this.vectors = _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_0__["ArrayTools"].BuildArray(8, _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero); + /** + * Gets the center of the bounding box in local space + */ + this.center = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); + /** + * Gets the center of the bounding box in world space + */ + this.centerWorld = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); + /** + * Gets the extend size in local space + */ + this.extendSize = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); + /** + * Gets the extend size in world space + */ + this.extendSizeWorld = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); + /** + * Gets the OBB (object bounding box) directions + */ + this.directions = _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_0__["ArrayTools"].BuildArray(3, _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero); + /** + * Gets the 8 vectors representing the bounding box in world space + */ + this.vectorsWorld = _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_0__["ArrayTools"].BuildArray(8, _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero); + /** + * Gets the minimum vector in world space + */ + this.minimumWorld = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); + /** + * Gets the maximum vector in world space + */ + this.maximumWorld = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); + /** + * Gets the minimum vector in local space + */ + this.minimum = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); + /** + * Gets the maximum vector in local space + */ + this.maximum = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); + this.reConstruct(min, max, worldMatrix); + } + // Methods + /** + * Recreates the entire bounding box from scratch as if we call the constructor in place + * @param min defines the new minimum vector (in local space) + * @param max defines the new maximum vector (in local space) + * @param worldMatrix defines the new world matrix + */ + BoundingBox.prototype.reConstruct = function (min, max, worldMatrix) { + var minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z; + var vectors = this.vectors; + this.minimum.copyFromFloats(minX, minY, minZ); + this.maximum.copyFromFloats(maxX, maxY, maxZ); + vectors[0].copyFromFloats(minX, minY, minZ); + vectors[1].copyFromFloats(maxX, maxY, maxZ); + vectors[2].copyFromFloats(maxX, minY, minZ); + vectors[3].copyFromFloats(minX, maxY, minZ); + vectors[4].copyFromFloats(minX, minY, maxZ); + vectors[5].copyFromFloats(maxX, maxY, minZ); + vectors[6].copyFromFloats(minX, maxY, maxZ); + vectors[7].copyFromFloats(maxX, minY, maxZ); + // OBB + max.addToRef(min, this.center).scaleInPlace(0.5); + max.subtractToRef(min, this.extendSize).scaleInPlace(0.5); + this._worldMatrix = worldMatrix || _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].IdentityReadOnly; + this._update(this._worldMatrix); + }; + /** + * Scale the current bounding box by applying a scale factor + * @param factor defines the scale factor to apply + * @returns the current bounding box + */ + BoundingBox.prototype.scale = function (factor) { + var tmpVectors = BoundingBox.TmpVector3; + var diff = this.maximum.subtractToRef(this.minimum, tmpVectors[0]); + var len = diff.length(); + diff.normalizeFromLength(len); + var distance = len * factor; + var newRadius = diff.scaleInPlace(distance * 0.5); + var min = this.center.subtractToRef(newRadius, tmpVectors[1]); + var max = this.center.addToRef(newRadius, tmpVectors[2]); + this.reConstruct(min, max, this._worldMatrix); + return this; + }; + /** + * Gets the world matrix of the bounding box + * @returns a matrix + */ + BoundingBox.prototype.getWorldMatrix = function () { + return this._worldMatrix; + }; + /** @hidden */ + BoundingBox.prototype._update = function (world) { + var minWorld = this.minimumWorld; + var maxWorld = this.maximumWorld; + var directions = this.directions; + var vectorsWorld = this.vectorsWorld; + var vectors = this.vectors; + if (!world.isIdentity()) { + minWorld.setAll(Number.MAX_VALUE); + maxWorld.setAll(-Number.MAX_VALUE); + for (var index = 0; index < 8; ++index) { + var v = vectorsWorld[index]; + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(vectors[index], world, v); + minWorld.minimizeInPlace(v); + maxWorld.maximizeInPlace(v); + } + // Extend + maxWorld.subtractToRef(minWorld, this.extendSizeWorld).scaleInPlace(0.5); + maxWorld.addToRef(minWorld, this.centerWorld).scaleInPlace(0.5); + } + else { + minWorld.copyFrom(this.minimum); + maxWorld.copyFrom(this.maximum); + for (var index = 0; index < 8; ++index) { + vectorsWorld[index].copyFrom(vectors[index]); + } + // Extend + this.extendSizeWorld.copyFrom(this.extendSize); + this.centerWorld.copyFrom(this.center); + } + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].FromArrayToRef(world.m, 0, directions[0]); + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].FromArrayToRef(world.m, 4, directions[1]); + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].FromArrayToRef(world.m, 8, directions[2]); + this._worldMatrix = world; + }; + /** + * Tests if the bounding box is intersecting the frustum planes + * @param frustumPlanes defines the frustum planes to test + * @returns true if there is an intersection + */ + BoundingBox.prototype.isInFrustum = function (frustumPlanes) { + return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes); + }; + /** + * Tests if the bounding box is entirely inside the frustum planes + * @param frustumPlanes defines the frustum planes to test + * @returns true if there is an inclusion + */ + BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) { + return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes); + }; + /** + * Tests if a point is inside the bounding box + * @param point defines the point to test + * @returns true if the point is inside the bounding box + */ + BoundingBox.prototype.intersectsPoint = function (point) { + var min = this.minimumWorld; + var max = this.maximumWorld; + var minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z; + var pointX = point.x, pointY = point.y, pointZ = point.z; + var delta = -_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Epsilon"]; + if (maxX - pointX < delta || delta > pointX - minX) { + return false; + } + if (maxY - pointY < delta || delta > pointY - minY) { + return false; + } + if (maxZ - pointZ < delta || delta > pointZ - minZ) { + return false; + } + return true; + }; + /** + * Tests if the bounding box intersects with a bounding sphere + * @param sphere defines the sphere to test + * @returns true if there is an intersection + */ + BoundingBox.prototype.intersectsSphere = function (sphere) { + return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld); + }; + /** + * Tests if the bounding box intersects with a box defined by a min and max vectors + * @param min defines the min vector to use + * @param max defines the max vector to use + * @returns true if there is an intersection + */ + BoundingBox.prototype.intersectsMinMax = function (min, max) { + var myMin = this.minimumWorld; + var myMax = this.maximumWorld; + var myMinX = myMin.x, myMinY = myMin.y, myMinZ = myMin.z, myMaxX = myMax.x, myMaxY = myMax.y, myMaxZ = myMax.z; + var minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z; + if (myMaxX < minX || myMinX > maxX) { + return false; + } + if (myMaxY < minY || myMinY > maxY) { + return false; + } + if (myMaxZ < minZ || myMinZ > maxZ) { + return false; + } + return true; + }; + // Statics + /** + * Tests if two bounding boxes are intersections + * @param box0 defines the first box to test + * @param box1 defines the second box to test + * @returns true if there is an intersection + */ + BoundingBox.Intersects = function (box0, box1) { + return box0.intersectsMinMax(box1.minimumWorld, box1.maximumWorld); + }; + /** + * Tests if a bounding box defines by a min/max vectors intersects a sphere + * @param minPoint defines the minimum vector of the bounding box + * @param maxPoint defines the maximum vector of the bounding box + * @param sphereCenter defines the sphere center + * @param sphereRadius defines the sphere radius + * @returns true if there is an intersection + */ + BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) { + var vector = BoundingBox.TmpVector3[0]; + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].ClampToRef(sphereCenter, minPoint, maxPoint, vector); + var num = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].DistanceSquared(sphereCenter, vector); + return (num <= (sphereRadius * sphereRadius)); + }; + /** + * Tests if a bounding box defined with 8 vectors is entirely inside frustum planes + * @param boundingVectors defines an array of 8 vectors representing a bounding box + * @param frustumPlanes defines the frustum planes to test + * @return true if there is an inclusion + */ + BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) { + for (var p = 0; p < 6; ++p) { + var frustumPlane = frustumPlanes[p]; + for (var i = 0; i < 8; ++i) { + if (frustumPlane.dotCoordinate(boundingVectors[i]) < 0) { + return false; + } + } + } + return true; + }; + /** + * Tests if a bounding box defined with 8 vectors intersects frustum planes + * @param boundingVectors defines an array of 8 vectors representing a bounding box + * @param frustumPlanes defines the frustum planes to test + * @return true if there is an intersection + */ + BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) { + for (var p = 0; p < 6; ++p) { + var canReturnFalse = true; + var frustumPlane = frustumPlanes[p]; + for (var i = 0; i < 8; ++i) { + if (frustumPlane.dotCoordinate(boundingVectors[i]) >= 0) { + canReturnFalse = false; + break; + } + } + if (canReturnFalse) { + return false; + } + } + return true; + }; + BoundingBox.TmpVector3 = _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_0__["ArrayTools"].BuildArray(3, _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero); + return BoundingBox; +}()); + + + +/***/ }), + +/***/ "./Culling/boundingInfo.ts": +/*!*********************************!*\ + !*** ./Culling/boundingInfo.ts ***! + \*********************************/ +/*! exports provided: BoundingInfo */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BoundingInfo", function() { return BoundingInfo; }); +/* harmony import */ var _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/arrayTools */ "./Misc/arrayTools.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts"); +/* harmony import */ var _boundingBox__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./boundingBox */ "./Culling/boundingBox.ts"); +/* harmony import */ var _boundingSphere__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./boundingSphere */ "./Culling/boundingSphere.ts"); + + + + + +var _result0 = { min: 0, max: 0 }; +var _result1 = { min: 0, max: 0 }; +var computeBoxExtents = function (axis, box, result) { + var p = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Dot(box.centerWorld, axis); + var r0 = Math.abs(_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Dot(box.directions[0], axis)) * box.extendSize.x; + var r1 = Math.abs(_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Dot(box.directions[1], axis)) * box.extendSize.y; + var r2 = Math.abs(_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Dot(box.directions[2], axis)) * box.extendSize.z; + var r = r0 + r1 + r2; + result.min = p - r; + result.max = p + r; +}; +var axisOverlap = function (axis, box0, box1) { + computeBoxExtents(axis, box0, _result0); + computeBoxExtents(axis, box1, _result1); + return !(_result0.min > _result1.max || _result1.min > _result0.max); +}; +/** + * Info for a bounding data of a mesh + */ +var BoundingInfo = /** @class */ (function () { + /** + * Constructs bounding info + * @param minimum min vector of the bounding box/sphere + * @param maximum max vector of the bounding box/sphere + * @param worldMatrix defines the new world matrix + */ + function BoundingInfo(minimum, maximum, worldMatrix) { + this._isLocked = false; + this.boundingBox = new _boundingBox__WEBPACK_IMPORTED_MODULE_3__["BoundingBox"](minimum, maximum, worldMatrix); + this.boundingSphere = new _boundingSphere__WEBPACK_IMPORTED_MODULE_4__["BoundingSphere"](minimum, maximum, worldMatrix); + } + /** + * Recreates the entire bounding info from scratch as if we call the constructor in place + * @param min defines the new minimum vector (in local space) + * @param max defines the new maximum vector (in local space) + * @param worldMatrix defines the new world matrix + */ + BoundingInfo.prototype.reConstruct = function (min, max, worldMatrix) { + this.boundingBox.reConstruct(min, max, worldMatrix); + this.boundingSphere.reConstruct(min, max, worldMatrix); + }; + Object.defineProperty(BoundingInfo.prototype, "minimum", { + /** + * min vector of the bounding box/sphere + */ + get: function () { + return this.boundingBox.minimum; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(BoundingInfo.prototype, "maximum", { + /** + * max vector of the bounding box/sphere + */ + get: function () { + return this.boundingBox.maximum; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(BoundingInfo.prototype, "isLocked", { + /** + * If the info is locked and won't be updated to avoid perf overhead + */ + get: function () { + return this._isLocked; + }, + set: function (value) { + this._isLocked = value; + }, + enumerable: true, + configurable: true + }); + // Methods + /** + * Updates the bounding sphere and box + * @param world world matrix to be used to update + */ + BoundingInfo.prototype.update = function (world) { + if (this._isLocked) { + return; + } + this.boundingBox._update(world); + this.boundingSphere._update(world); + }; + /** + * Recreate the bounding info to be centered around a specific point given a specific extend. + * @param center New center of the bounding info + * @param extend New extend of the bounding info + * @returns the current bounding info + */ + BoundingInfo.prototype.centerOn = function (center, extend) { + var minimum = BoundingInfo.TmpVector3[0].copyFrom(center).subtractInPlace(extend); + var maximum = BoundingInfo.TmpVector3[1].copyFrom(center).addInPlace(extend); + this.boundingBox.reConstruct(minimum, maximum, this.boundingBox.getWorldMatrix()); + this.boundingSphere.reConstruct(minimum, maximum, this.boundingBox.getWorldMatrix()); + return this; + }; + /** + * Scale the current bounding info by applying a scale factor + * @param factor defines the scale factor to apply + * @returns the current bounding info + */ + BoundingInfo.prototype.scale = function (factor) { + this.boundingBox.scale(factor); + this.boundingSphere.scale(factor); + return this; + }; + /** + * Returns `true` if the bounding info is within the frustum defined by the passed array of planes. + * @param frustumPlanes defines the frustum to test + * @param strategy defines the strategy to use for the culling (default is BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD) + * @returns true if the bounding info is in the frustum planes + */ + BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) { + if (strategy === void 0) { strategy = _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].MESHES_CULLINGSTRATEGY_STANDARD; } + var inclusionTest = (strategy === _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION || strategy === _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY); + if (inclusionTest) { + if (this.boundingSphere.isCenterInFrustum(frustumPlanes)) { + return true; + } + } + if (!this.boundingSphere.isInFrustum(frustumPlanes)) { + return false; + } + var bSphereOnlyTest = (strategy === _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY || strategy === _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY); + if (bSphereOnlyTest) { + return true; + } + return this.boundingBox.isInFrustum(frustumPlanes); + }; + Object.defineProperty(BoundingInfo.prototype, "diagonalLength", { + /** + * Gets the world distance between the min and max points of the bounding box + */ + get: function () { + var boundingBox = this.boundingBox; + var diag = boundingBox.maximumWorld.subtractToRef(boundingBox.minimumWorld, BoundingInfo.TmpVector3[0]); + return diag.length(); + }, + enumerable: true, + configurable: true + }); + /** + * Checks if a cullable object (mesh...) is in the camera frustum + * Unlike isInFrustum this cheks the full bounding box + * @param frustumPlanes Camera near/planes + * @returns true if the object is in frustum otherwise false + */ + BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) { + return this.boundingBox.isCompletelyInFrustum(frustumPlanes); + }; + /** @hidden */ + BoundingInfo.prototype._checkCollision = function (collider) { + return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld); + }; + /** + * Checks if a point is inside the bounding box and bounding sphere or the mesh + * @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh + * @param point the point to check intersection with + * @returns if the point intersects + */ + BoundingInfo.prototype.intersectsPoint = function (point) { + if (!this.boundingSphere.centerWorld) { + return false; + } + if (!this.boundingSphere.intersectsPoint(point)) { + return false; + } + if (!this.boundingBox.intersectsPoint(point)) { + return false; + } + return true; + }; + /** + * Checks if another bounding info intersects the bounding box and bounding sphere or the mesh + * @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh + * @param boundingInfo the bounding info to check intersection with + * @param precise if the intersection should be done using OBB + * @returns if the bounding info intersects + */ + BoundingInfo.prototype.intersects = function (boundingInfo, precise) { + if (!_boundingSphere__WEBPACK_IMPORTED_MODULE_4__["BoundingSphere"].Intersects(this.boundingSphere, boundingInfo.boundingSphere)) { + return false; + } + if (!_boundingBox__WEBPACK_IMPORTED_MODULE_3__["BoundingBox"].Intersects(this.boundingBox, boundingInfo.boundingBox)) { + return false; + } + if (!precise) { + return true; + } + var box0 = this.boundingBox; + var box1 = boundingInfo.boundingBox; + if (!axisOverlap(box0.directions[0], box0, box1)) { + return false; + } + if (!axisOverlap(box0.directions[1], box0, box1)) { + return false; + } + if (!axisOverlap(box0.directions[2], box0, box1)) { + return false; + } + if (!axisOverlap(box1.directions[0], box0, box1)) { + return false; + } + if (!axisOverlap(box1.directions[1], box0, box1)) { + return false; + } + if (!axisOverlap(box1.directions[2], box0, box1)) { + return false; + } + if (!axisOverlap(_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Cross(box0.directions[0], box1.directions[0]), box0, box1)) { + return false; + } + if (!axisOverlap(_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Cross(box0.directions[0], box1.directions[1]), box0, box1)) { + return false; + } + if (!axisOverlap(_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Cross(box0.directions[0], box1.directions[2]), box0, box1)) { + return false; + } + if (!axisOverlap(_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Cross(box0.directions[1], box1.directions[0]), box0, box1)) { + return false; + } + if (!axisOverlap(_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Cross(box0.directions[1], box1.directions[1]), box0, box1)) { + return false; + } + if (!axisOverlap(_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Cross(box0.directions[1], box1.directions[2]), box0, box1)) { + return false; + } + if (!axisOverlap(_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Cross(box0.directions[2], box1.directions[0]), box0, box1)) { + return false; + } + if (!axisOverlap(_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Cross(box0.directions[2], box1.directions[1]), box0, box1)) { + return false; + } + if (!axisOverlap(_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Cross(box0.directions[2], box1.directions[2]), box0, box1)) { + return false; + } + return true; + }; + BoundingInfo.TmpVector3 = _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_0__["ArrayTools"].BuildArray(2, _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero); + return BoundingInfo; +}()); + + + +/***/ }), + +/***/ "./Culling/boundingSphere.ts": +/*!***********************************!*\ + !*** ./Culling/boundingSphere.ts ***! + \***********************************/ +/*! exports provided: BoundingSphere */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BoundingSphere", function() { return BoundingSphere; }); +/* harmony import */ var _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/arrayTools */ "./Misc/arrayTools.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); + + +/** + * Class used to store bounding sphere information + */ +var BoundingSphere = /** @class */ (function () { + /** + * Creates a new bounding sphere + * @param min defines the minimum vector (in local space) + * @param max defines the maximum vector (in local space) + * @param worldMatrix defines the new world matrix + */ + function BoundingSphere(min, max, worldMatrix) { + /** + * Gets the center of the bounding sphere in local space + */ + this.center = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); + /** + * Gets the center of the bounding sphere in world space + */ + this.centerWorld = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); + /** + * Gets the minimum vector in local space + */ + this.minimum = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); + /** + * Gets the maximum vector in local space + */ + this.maximum = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); + this.reConstruct(min, max, worldMatrix); + } + /** + * Recreates the entire bounding sphere from scratch as if we call the constructor in place + * @param min defines the new minimum vector (in local space) + * @param max defines the new maximum vector (in local space) + * @param worldMatrix defines the new world matrix + */ + BoundingSphere.prototype.reConstruct = function (min, max, worldMatrix) { + this.minimum.copyFrom(min); + this.maximum.copyFrom(max); + var distance = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Distance(min, max); + max.addToRef(min, this.center).scaleInPlace(0.5); + this.radius = distance * 0.5; + this._update(worldMatrix || _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].IdentityReadOnly); + }; + /** + * Scale the current bounding sphere by applying a scale factor + * @param factor defines the scale factor to apply + * @returns the current bounding box + */ + BoundingSphere.prototype.scale = function (factor) { + var newRadius = this.radius * factor; + var tmpVectors = BoundingSphere.TmpVector3; + var tempRadiusVector = tmpVectors[0].setAll(newRadius); + var min = this.center.subtractToRef(tempRadiusVector, tmpVectors[1]); + var max = this.center.addToRef(tempRadiusVector, tmpVectors[2]); + this.reConstruct(min, max, this._worldMatrix); + return this; + }; + /** + * Gets the world matrix of the bounding box + * @returns a matrix + */ + BoundingSphere.prototype.getWorldMatrix = function () { + return this._worldMatrix; + }; + // Methods + /** @hidden */ + BoundingSphere.prototype._update = function (worldMatrix) { + if (!worldMatrix.isIdentity()) { + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(this.center, worldMatrix, this.centerWorld); + var tempVector = BoundingSphere.TmpVector3[0]; + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, worldMatrix, tempVector); + this.radiusWorld = Math.max(Math.abs(tempVector.x), Math.abs(tempVector.y), Math.abs(tempVector.z)) * this.radius; + } + else { + this.centerWorld.copyFrom(this.center); + this.radiusWorld = this.radius; + } + }; + /** + * Tests if the bounding sphere is intersecting the frustum planes + * @param frustumPlanes defines the frustum planes to test + * @returns true if there is an intersection + */ + BoundingSphere.prototype.isInFrustum = function (frustumPlanes) { + var center = this.centerWorld; + var radius = this.radiusWorld; + for (var i = 0; i < 6; i++) { + if (frustumPlanes[i].dotCoordinate(center) <= -radius) { + return false; + } + } + return true; + }; + /** + * Tests if the bounding sphere center is in between the frustum planes. + * Used for optimistic fast inclusion. + * @param frustumPlanes defines the frustum planes to test + * @returns true if the sphere center is in between the frustum planes + */ + BoundingSphere.prototype.isCenterInFrustum = function (frustumPlanes) { + var center = this.centerWorld; + for (var i = 0; i < 6; i++) { + if (frustumPlanes[i].dotCoordinate(center) < 0) { + return false; + } + } + return true; + }; + /** + * Tests if a point is inside the bounding sphere + * @param point defines the point to test + * @returns true if the point is inside the bounding sphere + */ + BoundingSphere.prototype.intersectsPoint = function (point) { + var squareDistance = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].DistanceSquared(this.centerWorld, point); + if (this.radiusWorld * this.radiusWorld < squareDistance) { + return false; + } + return true; + }; + // Statics + /** + * Checks if two sphere intersct + * @param sphere0 sphere 0 + * @param sphere1 sphere 1 + * @returns true if the speres intersect + */ + BoundingSphere.Intersects = function (sphere0, sphere1) { + var squareDistance = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].DistanceSquared(sphere0.centerWorld, sphere1.centerWorld); + var radiusSum = sphere0.radiusWorld + sphere1.radiusWorld; + if (radiusSum * radiusSum < squareDistance) { + return false; + } + return true; + }; + BoundingSphere.TmpVector3 = _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_0__["ArrayTools"].BuildArray(3, _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero); + return BoundingSphere; +}()); + + + +/***/ }), + +/***/ "./Culling/index.ts": +/*!**************************!*\ + !*** ./Culling/index.ts ***! + \**************************/ +/*! exports provided: BoundingBox, BoundingInfo, BoundingSphere, Ray, Octree, OctreeBlock, OctreeSceneComponent */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _boundingBox__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./boundingBox */ "./Culling/boundingBox.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoundingBox", function() { return _boundingBox__WEBPACK_IMPORTED_MODULE_0__["BoundingBox"]; }); + +/* harmony import */ var _boundingInfo__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./boundingInfo */ "./Culling/boundingInfo.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoundingInfo", function() { return _boundingInfo__WEBPACK_IMPORTED_MODULE_1__["BoundingInfo"]; }); + +/* harmony import */ var _boundingSphere__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./boundingSphere */ "./Culling/boundingSphere.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoundingSphere", function() { return _boundingSphere__WEBPACK_IMPORTED_MODULE_2__["BoundingSphere"]; }); + +/* harmony import */ var _Octrees_index__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Octrees/index */ "./Culling/Octrees/index.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Octree", function() { return _Octrees_index__WEBPACK_IMPORTED_MODULE_3__["Octree"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OctreeBlock", function() { return _Octrees_index__WEBPACK_IMPORTED_MODULE_3__["OctreeBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OctreeSceneComponent", function() { return _Octrees_index__WEBPACK_IMPORTED_MODULE_3__["OctreeSceneComponent"]; }); + +/* harmony import */ var _ray__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./ray */ "./Culling/ray.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Ray", function() { return _ray__WEBPACK_IMPORTED_MODULE_4__["Ray"]; }); + + + + + + + + +/***/ }), + +/***/ "./Culling/ray.ts": +/*!************************!*\ + !*** ./Culling/ray.ts ***! + \************************/ +/*! exports provided: Ray */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Ray", function() { return Ray; }); +/* harmony import */ var _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/arrayTools */ "./Misc/arrayTools.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Collisions_pickingInfo__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Collisions/pickingInfo */ "./Collisions/pickingInfo.ts"); +/* harmony import */ var _Collisions_intersectionInfo__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Collisions/intersectionInfo */ "./Collisions/intersectionInfo.ts"); +/* harmony import */ var _scene__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../scene */ "./scene.ts"); +/* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Cameras/camera */ "./Cameras/camera.ts"); + + + + + + +/** + * Class representing a ray with position and direction + */ +var Ray = /** @class */ (function () { + /** + * Creates a new ray + * @param origin origin point + * @param direction direction + * @param length length of the ray + */ + function Ray( + /** origin point */ + origin, + /** direction */ + direction, + /** length of the ray */ + length) { + if (length === void 0) { length = Number.MAX_VALUE; } + this.origin = origin; + this.direction = direction; + this.length = length; + } + // Methods + /** + * Checks if the ray intersects a box + * @param minimum bound of the box + * @param maximum bound of the box + * @param intersectionTreshold extra extend to be added to the box in all direction + * @returns if the box was hit + */ + Ray.prototype.intersectsBoxMinMax = function (minimum, maximum, intersectionTreshold) { + if (intersectionTreshold === void 0) { intersectionTreshold = 0; } + var newMinimum = Ray.TmpVector3[0].copyFromFloats(minimum.x - intersectionTreshold, minimum.y - intersectionTreshold, minimum.z - intersectionTreshold); + var newMaximum = Ray.TmpVector3[1].copyFromFloats(maximum.x + intersectionTreshold, maximum.y + intersectionTreshold, maximum.z + intersectionTreshold); + var d = 0.0; + var maxValue = Number.MAX_VALUE; + var inv; + var min; + var max; + var temp; + if (Math.abs(this.direction.x) < 0.0000001) { + if (this.origin.x < newMinimum.x || this.origin.x > newMaximum.x) { + return false; + } + } + else { + inv = 1.0 / this.direction.x; + min = (newMinimum.x - this.origin.x) * inv; + max = (newMaximum.x - this.origin.x) * inv; + if (max === -Infinity) { + max = Infinity; + } + if (min > max) { + temp = min; + min = max; + max = temp; + } + d = Math.max(min, d); + maxValue = Math.min(max, maxValue); + if (d > maxValue) { + return false; + } + } + if (Math.abs(this.direction.y) < 0.0000001) { + if (this.origin.y < newMinimum.y || this.origin.y > newMaximum.y) { + return false; + } + } + else { + inv = 1.0 / this.direction.y; + min = (newMinimum.y - this.origin.y) * inv; + max = (newMaximum.y - this.origin.y) * inv; + if (max === -Infinity) { + max = Infinity; + } + if (min > max) { + temp = min; + min = max; + max = temp; + } + d = Math.max(min, d); + maxValue = Math.min(max, maxValue); + if (d > maxValue) { + return false; + } + } + if (Math.abs(this.direction.z) < 0.0000001) { + if (this.origin.z < newMinimum.z || this.origin.z > newMaximum.z) { + return false; + } + } + else { + inv = 1.0 / this.direction.z; + min = (newMinimum.z - this.origin.z) * inv; + max = (newMaximum.z - this.origin.z) * inv; + if (max === -Infinity) { + max = Infinity; + } + if (min > max) { + temp = min; + min = max; + max = temp; + } + d = Math.max(min, d); + maxValue = Math.min(max, maxValue); + if (d > maxValue) { + return false; + } + } + return true; + }; + /** + * Checks if the ray intersects a box + * @param box the bounding box to check + * @param intersectionTreshold extra extend to be added to the BoundingBox in all direction + * @returns if the box was hit + */ + Ray.prototype.intersectsBox = function (box, intersectionTreshold) { + if (intersectionTreshold === void 0) { intersectionTreshold = 0; } + return this.intersectsBoxMinMax(box.minimum, box.maximum, intersectionTreshold); + }; + /** + * If the ray hits a sphere + * @param sphere the bounding sphere to check + * @param intersectionTreshold extra extend to be added to the BoundingSphere in all direction + * @returns true if it hits the sphere + */ + Ray.prototype.intersectsSphere = function (sphere, intersectionTreshold) { + if (intersectionTreshold === void 0) { intersectionTreshold = 0; } + var x = sphere.center.x - this.origin.x; + var y = sphere.center.y - this.origin.y; + var z = sphere.center.z - this.origin.z; + var pyth = (x * x) + (y * y) + (z * z); + var radius = sphere.radius + intersectionTreshold; + var rr = radius * radius; + if (pyth <= rr) { + return true; + } + var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z); + if (dot < 0.0) { + return false; + } + var temp = pyth - (dot * dot); + return temp <= rr; + }; + /** + * If the ray hits a triange + * @param vertex0 triangle vertex + * @param vertex1 triangle vertex + * @param vertex2 triangle vertex + * @returns intersection information if hit + */ + Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) { + var edge1 = Ray.TmpVector3[0]; + var edge2 = Ray.TmpVector3[1]; + var pvec = Ray.TmpVector3[2]; + var tvec = Ray.TmpVector3[3]; + var qvec = Ray.TmpVector3[4]; + vertex1.subtractToRef(vertex0, edge1); + vertex2.subtractToRef(vertex0, edge2); + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].CrossToRef(this.direction, edge2, pvec); + var det = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Dot(edge1, pvec); + if (det === 0) { + return null; + } + var invdet = 1 / det; + this.origin.subtractToRef(vertex0, tvec); + var bv = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Dot(tvec, pvec) * invdet; + if (bv < 0 || bv > 1.0) { + return null; + } + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].CrossToRef(tvec, edge1, qvec); + var bw = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Dot(this.direction, qvec) * invdet; + if (bw < 0 || bv + bw > 1.0) { + return null; + } + //check if the distance is longer than the predefined length. + var distance = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Dot(edge2, qvec) * invdet; + if (distance > this.length) { + return null; + } + return new _Collisions_intersectionInfo__WEBPACK_IMPORTED_MODULE_3__["IntersectionInfo"](1 - bv - bw, bv, distance); + }; + /** + * Checks if ray intersects a plane + * @param plane the plane to check + * @returns the distance away it was hit + */ + Ray.prototype.intersectsPlane = function (plane) { + var distance; + var result1 = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Dot(plane.normal, this.direction); + if (Math.abs(result1) < 9.99999997475243E-07) { + return null; + } + else { + var result2 = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Dot(plane.normal, this.origin); + distance = (-plane.d - result2) / result1; + if (distance < 0.0) { + if (distance < -9.99999997475243E-07) { + return null; + } + else { + return 0; + } + } + return distance; + } + }; + /** + * Checks if ray intersects a mesh + * @param mesh the mesh to check + * @param fastCheck if only the bounding box should checked + * @returns picking info of the intersecton + */ + Ray.prototype.intersectsMesh = function (mesh, fastCheck) { + var tm = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Tmp"].Matrix[0]; + mesh.getWorldMatrix().invertToRef(tm); + if (this._tmpRay) { + Ray.TransformToRef(this, tm, this._tmpRay); + } + else { + this._tmpRay = Ray.Transform(this, tm); + } + return mesh.intersects(this._tmpRay, fastCheck); + }; + /** + * Checks if ray intersects a mesh + * @param meshes the meshes to check + * @param fastCheck if only the bounding box should checked + * @param results array to store result in + * @returns Array of picking infos + */ + Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) { + if (results) { + results.length = 0; + } + else { + results = []; + } + for (var i = 0; i < meshes.length; i++) { + var pickInfo = this.intersectsMesh(meshes[i], fastCheck); + if (pickInfo.hit) { + results.push(pickInfo); + } + } + results.sort(this._comparePickingInfo); + return results; + }; + Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) { + if (pickingInfoA.distance < pickingInfoB.distance) { + return -1; + } + else if (pickingInfoA.distance > pickingInfoB.distance) { + return 1; + } + else { + return 0; + } + }; + /** + * Intersection test between the ray and a given segment whithin a given tolerance (threshold) + * @param sega the first point of the segment to test the intersection against + * @param segb the second point of the segment to test the intersection against + * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful + * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection + */ + Ray.prototype.intersectionSegment = function (sega, segb, threshold) { + var o = this.origin; + var u = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Tmp"].Vector3[0]; + var rsegb = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Tmp"].Vector3[1]; + var v = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Tmp"].Vector3[2]; + var w = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Tmp"].Vector3[3]; + segb.subtractToRef(sega, u); + this.direction.scaleToRef(Ray.rayl, v); + o.addToRef(v, rsegb); + sega.subtractToRef(o, w); + var a = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Dot(u, u); // always >= 0 + var b = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Dot(u, v); + var c = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Dot(v, v); // always >= 0 + var d = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Dot(u, w); + var e = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Dot(v, w); + var D = a * c - b * b; // always >= 0 + var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0 + var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0 + // compute the line parameters of the two closest points + if (D < Ray.smallnum) { // the lines are almost parallel + sN = 0.0; // force using point P0 on segment S1 + sD = 1.0; // to prevent possible division by 0.0 later + tN = e; + tD = c; + } + else { // get the closest points on the infinite lines + sN = (b * e - c * d); + tN = (a * e - b * d); + if (sN < 0.0) { // sc < 0 => the s=0 edge is visible + sN = 0.0; + tN = e; + tD = c; + } + else if (sN > sD) { // sc > 1 => the s=1 edge is visible + sN = sD; + tN = e + b; + tD = c; + } + } + if (tN < 0.0) { // tc < 0 => the t=0 edge is visible + tN = 0.0; + // recompute sc for this edge + if (-d < 0.0) { + sN = 0.0; + } + else if (-d > a) { + sN = sD; + } + else { + sN = -d; + sD = a; + } + } + else if (tN > tD) { // tc > 1 => the t=1 edge is visible + tN = tD; + // recompute sc for this edge + if ((-d + b) < 0.0) { + sN = 0; + } + else if ((-d + b) > a) { + sN = sD; + } + else { + sN = (-d + b); + sD = a; + } + } + // finally do the division to get sc and tc + sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD); + tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD); + // get the difference of the two closest points + var qtc = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Tmp"].Vector3[4]; + v.scaleToRef(tc, qtc); + var qsc = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Tmp"].Vector3[5]; + u.scaleToRef(sc, qsc); + qsc.addInPlace(w); + var dP = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Tmp"].Vector3[6]; + qsc.subtractToRef(qtc, dP); // = S1(sc) - S2(tc) + var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result + if (isIntersected) { + return qsc.length(); + } + return -1; + }; + /** + * Update the ray from viewport position + * @param x position + * @param y y position + * @param viewportWidth viewport width + * @param viewportHeight viewport height + * @param world world matrix + * @param view view matrix + * @param projection projection matrix + * @returns this ray updated + */ + Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) { + this.unprojectRayToRef(x, y, viewportWidth, viewportHeight, world, view, projection); + return this; + }; + // Statics + /** + * Creates a ray with origin and direction of 0,0,0 + * @returns the new ray + */ + Ray.Zero = function () { + return new Ray(_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(), _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero()); + }; + /** + * Creates a new ray from screen space and viewport + * @param x position + * @param y y position + * @param viewportWidth viewport width + * @param viewportHeight viewport height + * @param world world matrix + * @param view view matrix + * @param projection projection matrix + * @returns new ray + */ + Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) { + var result = Ray.Zero(); + return result.update(x, y, viewportWidth, viewportHeight, world, view, projection); + }; + /** + * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be + * transformed to the given world matrix. + * @param origin The origin point + * @param end The end point + * @param world a matrix to transform the ray to. Default is the identity matrix. + * @returns the new ray + */ + Ray.CreateNewFromTo = function (origin, end, world) { + if (world === void 0) { world = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].IdentityReadOnly; } + var direction = end.subtract(origin); + var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z)); + direction.normalize(); + return Ray.Transform(new Ray(origin, direction, length), world); + }; + /** + * Transforms a ray by a matrix + * @param ray ray to transform + * @param matrix matrix to apply + * @returns the resulting new ray + */ + Ray.Transform = function (ray, matrix) { + var result = new Ray(new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"](0, 0, 0), new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"](0, 0, 0)); + Ray.TransformToRef(ray, matrix, result); + return result; + }; + /** + * Transforms a ray by a matrix + * @param ray ray to transform + * @param matrix matrix to apply + * @param result ray to store result in + */ + Ray.TransformToRef = function (ray, matrix, result) { + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(ray.origin, matrix, result.origin); + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformNormalToRef(ray.direction, matrix, result.direction); + result.length = ray.length; + var dir = result.direction; + var len = dir.length(); + if (!(len === 0 || len === 1)) { + var num = 1.0 / len; + dir.x *= num; + dir.y *= num; + dir.z *= num; + result.length *= len; + } + }; + /** + * Unproject a ray from screen space to object space + * @param sourceX defines the screen space x coordinate to use + * @param sourceY defines the screen space y coordinate to use + * @param viewportWidth defines the current width of the viewport + * @param viewportHeight defines the current height of the viewport + * @param world defines the world matrix to use (can be set to Identity to go to world space) + * @param view defines the view matrix to use + * @param projection defines the projection matrix to use + */ + Ray.prototype.unprojectRayToRef = function (sourceX, sourceY, viewportWidth, viewportHeight, world, view, projection) { + var matrix = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Tmp"].Matrix[0]; + world.multiplyToRef(view, matrix); + matrix.multiplyToRef(projection, matrix); + matrix.invert(); + var nearScreenSource = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Tmp"].Vector3[0]; + nearScreenSource.x = sourceX / viewportWidth * 2 - 1; + nearScreenSource.y = -(sourceY / viewportHeight * 2 - 1); + nearScreenSource.z = -1.0; + var farScreenSource = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Tmp"].Vector3[1].copyFromFloats(nearScreenSource.x, nearScreenSource.y, 1.0); + var nearVec3 = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Tmp"].Vector3[2]; + var farVec3 = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Tmp"].Vector3[3]; + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"]._UnprojectFromInvertedMatrixToRef(nearScreenSource, matrix, nearVec3); + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"]._UnprojectFromInvertedMatrixToRef(farScreenSource, matrix, farVec3); + this.origin.copyFrom(nearVec3); + farVec3.subtractToRef(nearVec3, this.direction); + this.direction.normalize(); + }; + Ray.TmpVector3 = _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_0__["ArrayTools"].BuildArray(6, _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero); + Ray.smallnum = 0.00000001; + Ray.rayl = 10e8; + return Ray; +}()); + +_scene__WEBPACK_IMPORTED_MODULE_4__["Scene"].prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) { + if (cameraViewSpace === void 0) { cameraViewSpace = false; } + var result = Ray.Zero(); + this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace); + return result; +}; +_scene__WEBPACK_IMPORTED_MODULE_4__["Scene"].prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) { + if (cameraViewSpace === void 0) { cameraViewSpace = false; } + var engine = this.getEngine(); + if (!camera) { + if (!this.activeCamera) { + throw new Error("Active camera not set"); + } + camera = this.activeCamera; + } + var cameraViewport = camera.viewport; + var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight()); + // Moving coordinates to local viewport world + x = x / engine.getHardwareScalingLevel() - viewport.x; + y = y / engine.getHardwareScalingLevel() - (engine.getRenderHeight() - viewport.y - viewport.height); + result.update(x, y, viewport.width, viewport.height, world ? world : _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].IdentityReadOnly, cameraViewSpace ? _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].IdentityReadOnly : camera.getViewMatrix(), camera.getProjectionMatrix()); + return this; +}; +_scene__WEBPACK_IMPORTED_MODULE_4__["Scene"].prototype.createPickingRayInCameraSpace = function (x, y, camera) { + var result = Ray.Zero(); + this.createPickingRayInCameraSpaceToRef(x, y, result, camera); + return result; +}; +_scene__WEBPACK_IMPORTED_MODULE_4__["Scene"].prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) { + if (!_Collisions_pickingInfo__WEBPACK_IMPORTED_MODULE_2__["PickingInfo"]) { + return this; + } + var engine = this.getEngine(); + if (!camera) { + if (!this.activeCamera) { + throw new Error("Active camera not set"); + } + camera = this.activeCamera; + } + var cameraViewport = camera.viewport; + var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight()); + var identity = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Identity(); + // Moving coordinates to local viewport world + x = x / engine.getHardwareScalingLevel() - viewport.x; + y = y / engine.getHardwareScalingLevel() - (engine.getRenderHeight() - viewport.y - viewport.height); + result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix()); + return this; +}; +_scene__WEBPACK_IMPORTED_MODULE_4__["Scene"].prototype._internalPick = function (rayFunction, predicate, fastCheck, trianglePredicate) { + if (!_Collisions_pickingInfo__WEBPACK_IMPORTED_MODULE_2__["PickingInfo"]) { + return null; + } + var pickingInfo = null; + for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) { + var mesh = this.meshes[meshIndex]; + if (predicate) { + if (!predicate(mesh)) { + continue; + } + } + else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) { + continue; + } + var world = mesh.getWorldMatrix(); + var ray = rayFunction(world); + var result = mesh.intersects(ray, fastCheck, trianglePredicate); + if (!result || !result.hit) { + continue; + } + if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance) { + continue; + } + pickingInfo = result; + if (fastCheck) { + break; + } + } + return pickingInfo || new _Collisions_pickingInfo__WEBPACK_IMPORTED_MODULE_2__["PickingInfo"](); +}; +_scene__WEBPACK_IMPORTED_MODULE_4__["Scene"].prototype._internalMultiPick = function (rayFunction, predicate, trianglePredicate) { + if (!_Collisions_pickingInfo__WEBPACK_IMPORTED_MODULE_2__["PickingInfo"]) { + return null; + } + var pickingInfos = new Array(); + for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) { + var mesh = this.meshes[meshIndex]; + if (predicate) { + if (!predicate(mesh)) { + continue; + } + } + else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) { + continue; + } + var world = mesh.getWorldMatrix(); + var ray = rayFunction(world); + var result = mesh.intersects(ray, false, trianglePredicate); + if (!result || !result.hit) { + continue; + } + pickingInfos.push(result); + } + return pickingInfos; +}; +_scene__WEBPACK_IMPORTED_MODULE_4__["Scene"].prototype.pick = function (x, y, predicate, fastCheck, camera, trianglePredicate) { + var _this = this; + if (!_Collisions_pickingInfo__WEBPACK_IMPORTED_MODULE_2__["PickingInfo"]) { + return null; + } + var result = this._internalPick(function (world) { + if (!_this._tempPickingRay) { + _this._tempPickingRay = Ray.Zero(); + } + _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null); + return _this._tempPickingRay; + }, predicate, fastCheck, trianglePredicate); + if (result) { + result.ray = this.createPickingRay(x, y, _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Identity(), camera || null); + } + return result; +}; +_scene__WEBPACK_IMPORTED_MODULE_4__["Scene"].prototype.pickWithRay = function (ray, predicate, fastCheck, trianglePredicate) { + var _this = this; + var result = this._internalPick(function (world) { + if (!_this._pickWithRayInverseMatrix) { + _this._pickWithRayInverseMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Identity(); + } + world.invertToRef(_this._pickWithRayInverseMatrix); + if (!_this._cachedRayForTransform) { + _this._cachedRayForTransform = Ray.Zero(); + } + Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform); + return _this._cachedRayForTransform; + }, predicate, fastCheck, trianglePredicate); + if (result) { + result.ray = ray; + } + return result; +}; +_scene__WEBPACK_IMPORTED_MODULE_4__["Scene"].prototype.multiPick = function (x, y, predicate, camera, trianglePredicate) { + var _this = this; + return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate, trianglePredicate); +}; +_scene__WEBPACK_IMPORTED_MODULE_4__["Scene"].prototype.multiPickWithRay = function (ray, predicate, trianglePredicate) { + var _this = this; + return this._internalMultiPick(function (world) { + if (!_this._pickWithRayInverseMatrix) { + _this._pickWithRayInverseMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Identity(); + } + world.invertToRef(_this._pickWithRayInverseMatrix); + if (!_this._cachedRayForTransform) { + _this._cachedRayForTransform = Ray.Zero(); + } + Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform); + return _this._cachedRayForTransform; + }, predicate, trianglePredicate); +}; +_Cameras_camera__WEBPACK_IMPORTED_MODULE_5__["Camera"].prototype.getForwardRay = function (length, transform, origin) { + if (length === void 0) { length = 100; } + if (!transform) { + transform = this.getWorldMatrix(); + } + if (!origin) { + origin = this.position; + } + var forward = this._scene.useRightHandedSystem ? new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"](0, 0, -1) : new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"](0, 0, 1); + var forwardWorld = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformNormal(forward, transform); + var direction = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Normalize(forwardWorld); + return new Ray(origin, direction, length); +}; + + +/***/ }), + +/***/ "./Debug/axesViewer.ts": +/*!*****************************!*\ + !*** ./Debug/axesViewer.ts ***! + \*****************************/ +/*! exports provided: AxesViewer */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AxesViewer", function() { return AxesViewer; }); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Materials/standardMaterial */ "./Materials/standardMaterial.ts"); +/* harmony import */ var _Gizmos_axisDragGizmo__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Gizmos/axisDragGizmo */ "./Gizmos/axisDragGizmo.ts"); + + + +/** + * The Axes viewer will show 3 axes in a specific point in space + */ +var AxesViewer = /** @class */ (function () { + /** + * Creates a new AxesViewer + * @param scene defines the hosting scene + * @param scaleLines defines a number used to scale line length (1 by default) + * @param renderingGroupId defines a number used to set the renderingGroupId of the meshes (2 by default) + * @param xAxis defines the node hierarchy used to render the x-axis + * @param yAxis defines the node hierarchy used to render the y-axis + * @param zAxis defines the node hierarchy used to render the z-axis + */ + function AxesViewer(scene, scaleLines, renderingGroupId, xAxis, yAxis, zAxis) { + if (scaleLines === void 0) { scaleLines = 1; } + if (renderingGroupId === void 0) { renderingGroupId = 2; } + this._scaleLinesFactor = 4; + this._instanced = false; + /** + * Gets or sets a number used to scale line length + */ + this.scaleLines = 1; + this.scaleLines = scaleLines; + if (!xAxis) { + var redColoredMaterial = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_1__["StandardMaterial"]("", scene); + redColoredMaterial.disableLighting = true; + redColoredMaterial.emissiveColor = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Color3"].Red().scale(0.5); + xAxis = _Gizmos_axisDragGizmo__WEBPACK_IMPORTED_MODULE_2__["AxisDragGizmo"]._CreateArrow(scene, redColoredMaterial); + } + if (!yAxis) { + var greenColoredMaterial = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_1__["StandardMaterial"]("", scene); + greenColoredMaterial.disableLighting = true; + greenColoredMaterial.emissiveColor = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Color3"].Green().scale(0.5); + yAxis = _Gizmos_axisDragGizmo__WEBPACK_IMPORTED_MODULE_2__["AxisDragGizmo"]._CreateArrow(scene, greenColoredMaterial); + } + if (!zAxis) { + var blueColoredMaterial = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_1__["StandardMaterial"]("", scene); + blueColoredMaterial.disableLighting = true; + blueColoredMaterial.emissiveColor = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Color3"].Blue().scale(0.5); + zAxis = _Gizmos_axisDragGizmo__WEBPACK_IMPORTED_MODULE_2__["AxisDragGizmo"]._CreateArrow(scene, blueColoredMaterial); + } + this._xAxis = xAxis; + this._xAxis.scaling.setAll(this.scaleLines * this._scaleLinesFactor); + this._yAxis = yAxis; + this._yAxis.scaling.setAll(this.scaleLines * this._scaleLinesFactor); + this._zAxis = zAxis; + this._zAxis.scaling.setAll(this.scaleLines * this._scaleLinesFactor); + if (renderingGroupId != null) { + AxesViewer._SetRenderingGroupId(this._xAxis, renderingGroupId); + AxesViewer._SetRenderingGroupId(this._yAxis, renderingGroupId); + AxesViewer._SetRenderingGroupId(this._zAxis, renderingGroupId); + } + this.scene = scene; + this.update(new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"](), _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Right(), _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Up(), _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Forward()); + } + Object.defineProperty(AxesViewer.prototype, "xAxis", { + /** Gets the node hierarchy used to render x-axis */ + get: function () { + return this._xAxis; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(AxesViewer.prototype, "yAxis", { + /** Gets the node hierarchy used to render y-axis */ + get: function () { + return this._yAxis; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(AxesViewer.prototype, "zAxis", { + /** Gets the node hierarchy used to render z-axis */ + get: function () { + return this._zAxis; + }, + enumerable: true, + configurable: true + }); + /** + * Force the viewer to update + * @param position defines the position of the viewer + * @param xaxis defines the x axis of the viewer + * @param yaxis defines the y axis of the viewer + * @param zaxis defines the z axis of the viewer + */ + AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) { + this._xAxis.position.copyFrom(position); + this._xAxis.setDirection(xaxis); + this._xAxis.scaling.setAll(this.scaleLines * this._scaleLinesFactor); + this._yAxis.position.copyFrom(position); + this._yAxis.setDirection(yaxis); + this._yAxis.scaling.setAll(this.scaleLines * this._scaleLinesFactor); + this._zAxis.position.copyFrom(position); + this._zAxis.setDirection(zaxis); + this._zAxis.scaling.setAll(this.scaleLines * this._scaleLinesFactor); + }; + /** + * Creates an instance of this axes viewer. + * @returns a new axes viewer with instanced meshes + */ + AxesViewer.prototype.createInstance = function () { + var xAxis = _Gizmos_axisDragGizmo__WEBPACK_IMPORTED_MODULE_2__["AxisDragGizmo"]._CreateArrowInstance(this.scene, this._xAxis); + var yAxis = _Gizmos_axisDragGizmo__WEBPACK_IMPORTED_MODULE_2__["AxisDragGizmo"]._CreateArrowInstance(this.scene, this._yAxis); + var zAxis = _Gizmos_axisDragGizmo__WEBPACK_IMPORTED_MODULE_2__["AxisDragGizmo"]._CreateArrowInstance(this.scene, this._zAxis); + var axesViewer = new AxesViewer(this.scene, this.scaleLines, null, xAxis, yAxis, zAxis); + axesViewer._instanced = true; + return axesViewer; + }; + /** Releases resources */ + AxesViewer.prototype.dispose = function () { + if (this._xAxis) { + this._xAxis.dispose(false, !this._instanced); + delete this._xAxis; + } + if (this._yAxis) { + this._yAxis.dispose(false, !this._instanced); + delete this._yAxis; + } + if (this._zAxis) { + this._zAxis.dispose(false, !this._instanced); + delete this._zAxis; + } + delete this.scene; + }; + AxesViewer._SetRenderingGroupId = function (node, id) { + node.getChildMeshes().forEach(function (mesh) { + mesh.renderingGroupId = id; + }); + }; + return AxesViewer; +}()); + + + +/***/ }), + +/***/ "./Debug/boneAxesViewer.ts": +/*!*********************************!*\ + !*** ./Debug/boneAxesViewer.ts ***! + \*********************************/ +/*! exports provided: BoneAxesViewer */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BoneAxesViewer", function() { return BoneAxesViewer; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Debug_axesViewer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Debug/axesViewer */ "./Debug/axesViewer.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); + + + +/** + * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh + * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8 + */ +var BoneAxesViewer = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](BoneAxesViewer, _super); + /** + * Creates a new BoneAxesViewer + * @param scene defines the hosting scene + * @param bone defines the target bone + * @param mesh defines the target mesh + * @param scaleLines defines a scaling factor for line length (1 by default) + */ + function BoneAxesViewer(scene, bone, mesh, scaleLines) { + if (scaleLines === void 0) { scaleLines = 1; } + var _this = _super.call(this, scene, scaleLines) || this; + /** Gets current position */ + _this.pos = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); + /** Gets direction of X axis */ + _this.xaxis = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); + /** Gets direction of Y axis */ + _this.yaxis = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); + /** Gets direction of Z axis */ + _this.zaxis = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); + _this.mesh = mesh; + _this.bone = bone; + return _this; + } + /** + * Force the viewer to update + */ + BoneAxesViewer.prototype.update = function () { + if (!this.mesh || !this.bone) { + return; + } + var bone = this.bone; + bone._markAsDirtyAndCompose(); + bone.getAbsolutePositionToRef(this.mesh, this.pos); + bone.getDirectionToRef(_Maths_math__WEBPACK_IMPORTED_MODULE_2__["Axis"].X, this.mesh, this.xaxis); + bone.getDirectionToRef(_Maths_math__WEBPACK_IMPORTED_MODULE_2__["Axis"].Y, this.mesh, this.yaxis); + bone.getDirectionToRef(_Maths_math__WEBPACK_IMPORTED_MODULE_2__["Axis"].Z, this.mesh, this.zaxis); + _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis); + }; + /** Releases resources */ + BoneAxesViewer.prototype.dispose = function () { + if (this.mesh) { + this.mesh = null; + this.bone = null; + _super.prototype.dispose.call(this); + } + }; + return BoneAxesViewer; +}(_Debug_axesViewer__WEBPACK_IMPORTED_MODULE_1__["AxesViewer"])); + + + +/***/ }), + +/***/ "./Debug/debugLayer.ts": +/*!*****************************!*\ + !*** ./Debug/debugLayer.ts ***! + \*****************************/ +/*! exports provided: DebugLayer */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DebugLayer", function() { return DebugLayer; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/tools */ "./Misc/tools.ts"); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _scene__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../scene */ "./scene.ts"); +/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Engines/engine */ "./Engines/engine.ts"); + + + + + +Object.defineProperty(_scene__WEBPACK_IMPORTED_MODULE_3__["Scene"].prototype, "debugLayer", { + get: function () { + if (!this._debugLayer) { + this._debugLayer = new DebugLayer(this); + } + return this._debugLayer; + }, + enumerable: true, + configurable: true +}); +/** + * The debug layer (aka Inspector) is the go to tool in order to better understand + * what is happening in your scene + * @see http://doc.babylonjs.com/features/playground_debuglayer + */ +var DebugLayer = /** @class */ (function () { + /** + * Instantiates a new debug layer. + * The debug layer (aka Inspector) is the go to tool in order to better understand + * what is happening in your scene + * @see http://doc.babylonjs.com/features/playground_debuglayer + * @param scene Defines the scene to inspect + */ + function DebugLayer(scene) { + var _this = this; + this.BJSINSPECTOR = this._getGlobalInspector(); + /** + * Observable triggered when a property is changed through the inspector. + */ + this.onPropertyChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); + this._scene = scene; + this._scene.onDisposeObservable.add(function () { + // Debug layer + if (_this._scene._debugLayer) { + _this._scene._debugLayer.hide(); + } + }); + } + /** Creates the inspector window. */ + DebugLayer.prototype._createInspector = function (config) { + if (this.isVisible()) { + return; + } + var userOptions = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({ overlay: false, showExplorer: true, showInspector: true, embedMode: false, handleResize: true, enablePopup: true }, config); + this.BJSINSPECTOR = this.BJSINSPECTOR || this._getGlobalInspector(); + this.BJSINSPECTOR.Inspector.Show(this._scene, userOptions); + }; + /** + * Select a specific entity in the scene explorer and highlight a specific block in that entity property grid + * @param entity defines the entity to select + * @param lineContainerTitle defines the specific block to highlight + */ + DebugLayer.prototype.select = function (entity, lineContainerTitle) { + if (this.BJSINSPECTOR) { + this.BJSINSPECTOR.Inspector.MarkLineContainerTitleForHighlighting(lineContainerTitle); + this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable.notifyObservers(entity); + } + }; + /** Get the inspector from bundle or global */ + DebugLayer.prototype._getGlobalInspector = function () { + // UMD Global name detection from Webpack Bundle UMD Name. + if (typeof INSPECTOR !== 'undefined') { + return INSPECTOR; + } + // In case of module let s check the global emitted from the Inspector entry point. + if (typeof BABYLON !== 'undefined' && typeof BABYLON.Inspector !== 'undefined') { + return BABYLON; + } + return undefined; + }; + /** + * Get if the inspector is visible or not. + * @returns true if visible otherwise, false + */ + DebugLayer.prototype.isVisible = function () { + return this.BJSINSPECTOR && this.BJSINSPECTOR.Inspector.IsVisible; + }; + /** + * Hide the inspector and close its window. + */ + DebugLayer.prototype.hide = function () { + if (this.BJSINSPECTOR) { + this.BJSINSPECTOR.Inspector.Hide(); + } + }; + /** + * Launch the debugLayer. + * @param config Define the configuration of the inspector + * @return a promise fulfilled when the debug layer is visible + */ + DebugLayer.prototype.show = function (config) { + var _this = this; + return new Promise(function (resolve, reject) { + if (typeof _this.BJSINSPECTOR == 'undefined') { + var inspectorUrl = config && config.inspectorURL ? config.inspectorURL : DebugLayer.InspectorURL; + // Load inspector and add it to the DOM + _Misc_tools__WEBPACK_IMPORTED_MODULE_1__["Tools"].LoadScript(inspectorUrl, function () { + _this._createInspector(config); + resolve(_this); + }); + } + else { + // Otherwise creates the inspector + _this._createInspector(config); + resolve(_this); + } + }); + }; + /** + * Define the url to get the inspector script from. + * By default it uses the babylonjs CDN. + * @ignoreNaming + */ + DebugLayer.InspectorURL = "https://unpkg.com/babylonjs-inspector@" + _Engines_engine__WEBPACK_IMPORTED_MODULE_4__["Engine"].Version + "/babylon.inspector.bundle.js"; + return DebugLayer; +}()); + + + +/***/ }), + +/***/ "./Debug/index.ts": +/*!************************!*\ + !*** ./Debug/index.ts ***! + \************************/ +/*! exports provided: AxesViewer, BoneAxesViewer, DebugLayer, PhysicsViewer, RayHelper, SkeletonViewer */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _axesViewer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./axesViewer */ "./Debug/axesViewer.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AxesViewer", function() { return _axesViewer__WEBPACK_IMPORTED_MODULE_0__["AxesViewer"]; }); + +/* harmony import */ var _boneAxesViewer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./boneAxesViewer */ "./Debug/boneAxesViewer.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoneAxesViewer", function() { return _boneAxesViewer__WEBPACK_IMPORTED_MODULE_1__["BoneAxesViewer"]; }); + +/* harmony import */ var _debugLayer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./debugLayer */ "./Debug/debugLayer.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DebugLayer", function() { return _debugLayer__WEBPACK_IMPORTED_MODULE_2__["DebugLayer"]; }); + +/* harmony import */ var _physicsViewer__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./physicsViewer */ "./Debug/physicsViewer.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PhysicsViewer", function() { return _physicsViewer__WEBPACK_IMPORTED_MODULE_3__["PhysicsViewer"]; }); + +/* harmony import */ var _rayHelper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./rayHelper */ "./Debug/rayHelper.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RayHelper", function() { return _rayHelper__WEBPACK_IMPORTED_MODULE_4__["RayHelper"]; }); + +/* harmony import */ var _skeletonViewer__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./skeletonViewer */ "./Debug/skeletonViewer.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SkeletonViewer", function() { return _skeletonViewer__WEBPACK_IMPORTED_MODULE_5__["SkeletonViewer"]; }); + + + + + + + + + +/***/ }), + +/***/ "./Debug/physicsViewer.ts": +/*!********************************!*\ + !*** ./Debug/physicsViewer.ts ***! + \********************************/ +/*! exports provided: PhysicsViewer */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PhysicsViewer", function() { return PhysicsViewer; }); +/* harmony import */ var _Meshes_mesh__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Meshes/mesh */ "./Meshes/mesh.ts"); +/* harmony import */ var _Meshes_Builders_boxBuilder__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Meshes/Builders/boxBuilder */ "./Meshes/Builders/boxBuilder.ts"); +/* harmony import */ var _Meshes_Builders_sphereBuilder__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Meshes/Builders/sphereBuilder */ "./Meshes/Builders/sphereBuilder.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Engines_engineStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Engines/engineStore */ "./Engines/engineStore.ts"); +/* harmony import */ var _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Materials/standardMaterial */ "./Materials/standardMaterial.ts"); +/* harmony import */ var _Physics_physicsImpostor__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Physics/physicsImpostor */ "./Physics/physicsImpostor.ts"); +/* harmony import */ var _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Rendering/utilityLayerRenderer */ "./Rendering/utilityLayerRenderer.ts"); +/* harmony import */ var _Meshes_Builders_cylinderBuilder__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Meshes/Builders/cylinderBuilder */ "./Meshes/Builders/cylinderBuilder.ts"); + + + + + + + + + +/** + * Used to show the physics impostor around the specific mesh + */ +var PhysicsViewer = /** @class */ (function () { + /** + * Creates a new PhysicsViewer + * @param scene defines the hosting scene + */ + function PhysicsViewer(scene) { + /** @hidden */ + this._impostors = []; + /** @hidden */ + this._meshes = []; + /** @hidden */ + this._numMeshes = 0; + this._debugMeshMeshes = new Array(); + this._scene = scene || _Engines_engineStore__WEBPACK_IMPORTED_MODULE_4__["EngineStore"].LastCreatedScene; + var physicEngine = this._scene.getPhysicsEngine(); + if (physicEngine) { + this._physicsEnginePlugin = physicEngine.getPhysicsPlugin(); + } + this._utilityLayer = new _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_7__["UtilityLayerRenderer"](this._scene, false); + this._utilityLayer.pickUtilitySceneFirst = false; + this._utilityLayer.utilityLayerScene.autoClearDepthAndStencil = true; + } + /** @hidden */ + PhysicsViewer.prototype._updateDebugMeshes = function () { + var plugin = this._physicsEnginePlugin; + for (var i = 0; i < this._numMeshes; i++) { + var impostor = this._impostors[i]; + if (!impostor) { + continue; + } + if (impostor.isDisposed) { + this.hideImpostor(this._impostors[i--]); + } + else { + if (impostor.type === _Physics_physicsImpostor__WEBPACK_IMPORTED_MODULE_6__["PhysicsImpostor"].MeshImpostor) { + continue; + } + var mesh = this._meshes[i]; + if (mesh && plugin) { + plugin.syncMeshWithImpostor(mesh, impostor); + } + } + } + }; + /** + * Renders a specified physic impostor + * @param impostor defines the impostor to render + * @param targetMesh defines the mesh represented by the impostor + * @returns the new debug mesh used to render the impostor + */ + PhysicsViewer.prototype.showImpostor = function (impostor, targetMesh) { + if (!this._scene) { + return null; + } + for (var i = 0; i < this._numMeshes; i++) { + if (this._impostors[i] == impostor) { + return null; + } + } + var debugMesh = this._getDebugMesh(impostor, targetMesh); + if (debugMesh) { + this._impostors[this._numMeshes] = impostor; + this._meshes[this._numMeshes] = debugMesh; + if (this._numMeshes === 0) { + this._renderFunction = this._updateDebugMeshes.bind(this); + this._scene.registerBeforeRender(this._renderFunction); + } + this._numMeshes++; + } + return debugMesh; + }; + /** + * Hides a specified physic impostor + * @param impostor defines the impostor to hide + */ + PhysicsViewer.prototype.hideImpostor = function (impostor) { + if (!impostor || !this._scene || !this._utilityLayer) { + return; + } + var removed = false; + var utilityLayerScene = this._utilityLayer.utilityLayerScene; + for (var i = 0; i < this._numMeshes; i++) { + if (this._impostors[i] == impostor) { + var mesh = this._meshes[i]; + if (!mesh) { + continue; + } + utilityLayerScene.removeMesh(mesh); + mesh.dispose(); + var index = this._debugMeshMeshes.indexOf(mesh); + if (index > -1) { + this._debugMeshMeshes.splice(index, 1); + } + this._numMeshes--; + if (this._numMeshes > 0) { + this._meshes[i] = this._meshes[this._numMeshes]; + this._impostors[i] = this._impostors[this._numMeshes]; + this._meshes[this._numMeshes] = null; + this._impostors[this._numMeshes] = null; + } + else { + this._meshes[0] = null; + this._impostors[0] = null; + } + removed = true; + break; + } + } + if (removed && this._numMeshes === 0) { + this._scene.unregisterBeforeRender(this._renderFunction); + } + }; + PhysicsViewer.prototype._getDebugMaterial = function (scene) { + if (!this._debugMaterial) { + this._debugMaterial = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_5__["StandardMaterial"]('', scene); + this._debugMaterial.wireframe = true; + this._debugMaterial.emissiveColor = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Color3"].White(); + this._debugMaterial.disableLighting = true; + } + return this._debugMaterial; + }; + PhysicsViewer.prototype._getDebugBoxMesh = function (scene) { + if (!this._debugBoxMesh) { + this._debugBoxMesh = _Meshes_Builders_boxBuilder__WEBPACK_IMPORTED_MODULE_1__["BoxBuilder"].CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene); + this._debugBoxMesh.rotationQuaternion = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].Identity(); + this._debugBoxMesh.material = this._getDebugMaterial(scene); + this._debugBoxMesh.setEnabled(false); + } + return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance'); + }; + PhysicsViewer.prototype._getDebugSphereMesh = function (scene) { + if (!this._debugSphereMesh) { + this._debugSphereMesh = _Meshes_Builders_sphereBuilder__WEBPACK_IMPORTED_MODULE_2__["SphereBuilder"].CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene); + this._debugSphereMesh.rotationQuaternion = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].Identity(); + this._debugSphereMesh.material = this._getDebugMaterial(scene); + this._debugSphereMesh.setEnabled(false); + } + return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance'); + }; + PhysicsViewer.prototype._getDebugCylinderMesh = function (scene) { + if (!this._debugCylinderMesh) { + this._debugCylinderMesh = _Meshes_Builders_cylinderBuilder__WEBPACK_IMPORTED_MODULE_8__["CylinderBuilder"].CreateCylinder('physicsBodyCylinderViewMesh', { diameterTop: 1, diameterBottom: 1, height: 1 }, scene); + this._debugCylinderMesh.rotationQuaternion = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].Identity(); + this._debugCylinderMesh.material = this._getDebugMaterial(scene); + this._debugCylinderMesh.setEnabled(false); + } + return this._debugCylinderMesh.createInstance('physicsBodyBoxViewInstance'); + }; + PhysicsViewer.prototype._getDebugMeshMesh = function (mesh, scene) { + var wireframeOver = new _Meshes_mesh__WEBPACK_IMPORTED_MODULE_0__["Mesh"](mesh.name, scene, null, mesh); + wireframeOver.position = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(); + wireframeOver.setParent(mesh); + wireframeOver.material = this._getDebugMaterial(scene); + this._debugMeshMeshes.push(wireframeOver); + return wireframeOver; + }; + PhysicsViewer.prototype._getDebugMesh = function (impostor, targetMesh) { + var _this = this; + if (!this._utilityLayer) { + return null; + } + // Only create child impostor debug meshes when evaluating the parent + if (targetMesh && targetMesh.parent && targetMesh.parent.physicsImpostor) { + return null; + } + var mesh = null; + var utilityLayerScene = this._utilityLayer.utilityLayerScene; + switch (impostor.type) { + case _Physics_physicsImpostor__WEBPACK_IMPORTED_MODULE_6__["PhysicsImpostor"].BoxImpostor: + mesh = this._getDebugBoxMesh(utilityLayerScene); + impostor.getBoxSizeToRef(mesh.scaling); + break; + case _Physics_physicsImpostor__WEBPACK_IMPORTED_MODULE_6__["PhysicsImpostor"].SphereImpostor: + mesh = this._getDebugSphereMesh(utilityLayerScene); + var radius = impostor.getRadius(); + mesh.scaling.x = radius * 2; + mesh.scaling.y = radius * 2; + mesh.scaling.z = radius * 2; + break; + case _Physics_physicsImpostor__WEBPACK_IMPORTED_MODULE_6__["PhysicsImpostor"].MeshImpostor: + if (targetMesh) { + mesh = this._getDebugMeshMesh(targetMesh, utilityLayerScene); + } + break; + case _Physics_physicsImpostor__WEBPACK_IMPORTED_MODULE_6__["PhysicsImpostor"].NoImpostor: + if (targetMesh) { + // Handle compound impostors + var childMeshes = targetMesh.getChildMeshes().filter(function (c) { return c.physicsImpostor ? 1 : 0; }); + childMeshes.forEach(function (m) { + var a = _this._getDebugBoxMesh(utilityLayerScene); + a.parent = m; + }); + } + break; + case _Physics_physicsImpostor__WEBPACK_IMPORTED_MODULE_6__["PhysicsImpostor"].CylinderImpostor: + mesh = this._getDebugCylinderMesh(utilityLayerScene); + var bi = impostor.object.getBoundingInfo(); + mesh.scaling.x = bi.boundingBox.maximum.x - bi.boundingBox.minimum.x; + mesh.scaling.y = bi.boundingBox.maximum.y - bi.boundingBox.minimum.y; + mesh.scaling.z = bi.boundingBox.maximum.z - bi.boundingBox.minimum.z; + break; + } + return mesh; + }; + /** Releases all resources */ + PhysicsViewer.prototype.dispose = function () { + var count = this._numMeshes; + for (var index = 0; index < count; index++) { + this.hideImpostor(this._impostors[0]); + } + if (this._debugBoxMesh) { + this._debugBoxMesh.dispose(); + } + if (this._debugSphereMesh) { + this._debugSphereMesh.dispose(); + } + if (this._debugCylinderMesh) { + this._debugCylinderMesh.dispose(); + } + if (this._debugMaterial) { + this._debugMaterial.dispose(); + } + this._impostors.length = 0; + this._scene = null; + this._physicsEnginePlugin = null; + if (this._utilityLayer) { + this._utilityLayer.dispose(); + this._utilityLayer = null; + } + }; + return PhysicsViewer; +}()); + + + +/***/ }), + +/***/ "./Debug/rayHelper.ts": +/*!****************************!*\ + !*** ./Debug/rayHelper.ts ***! + \****************************/ +/*! exports provided: RayHelper */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RayHelper", function() { return RayHelper; }); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Meshes_mesh__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Meshes/mesh */ "./Meshes/mesh.ts"); +/* harmony import */ var _Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Meshes/Builders/linesBuilder */ "./Meshes/Builders/linesBuilder.ts"); + + + +/** + * As raycast might be hard to debug, the RayHelper can help rendering the different rays + * in order to better appreciate the issue one might have. + * @see http://doc.babylonjs.com/babylon101/raycasts#debugging + */ +var RayHelper = /** @class */ (function () { + /** + * Instantiate a new ray helper. + * As raycast might be hard to debug, the RayHelper can help rendering the different rays + * in order to better appreciate the issue one might have. + * @see http://doc.babylonjs.com/babylon101/raycasts#debugging + * @param ray Defines the ray we are currently tryin to visualize + */ + function RayHelper(ray) { + this.ray = ray; + } + /** + * Helper function to create a colored helper in a scene in one line. + * @param ray Defines the ray we are currently tryin to visualize + * @param scene Defines the scene the ray is used in + * @param color Defines the color we want to see the ray in + * @returns The newly created ray helper. + */ + RayHelper.CreateAndShow = function (ray, scene, color) { + var helper = new RayHelper(ray); + helper.show(scene, color); + return helper; + }; + /** + * Shows the ray we are willing to debug. + * @param scene Defines the scene the ray needs to be rendered in + * @param color Defines the color the ray needs to be rendered in + */ + RayHelper.prototype.show = function (scene, color) { + if (!this._renderFunction && this.ray) { + var ray = this.ray; + this._renderFunction = this._render.bind(this); + this._scene = scene; + this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))]; + this._renderLine = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_1__["Mesh"].CreateLines("ray", this._renderPoints, scene, true); + if (this._renderFunction) { + this._scene.registerBeforeRender(this._renderFunction); + } + } + if (color && this._renderLine) { + this._renderLine.color.copyFrom(color); + } + }; + /** + * Hides the ray we are debugging. + */ + RayHelper.prototype.hide = function () { + if (this._renderFunction && this._scene) { + this._scene.unregisterBeforeRender(this._renderFunction); + this._scene = null; + this._renderFunction = null; + if (this._renderLine) { + this._renderLine.dispose(); + this._renderLine = null; + } + this._renderPoints = []; + } + }; + RayHelper.prototype._render = function () { + var ray = this.ray; + if (!ray) { + return; + } + var point = this._renderPoints[1]; + var len = Math.min(ray.length, 1000000); + point.copyFrom(ray.direction); + point.scaleInPlace(len); + point.addInPlace(ray.origin); + _Meshes_mesh__WEBPACK_IMPORTED_MODULE_1__["Mesh"].CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine); + }; + /** + * Attach a ray helper to a mesh so that we can easily see its orientation for instance or information like its normals. + * @param mesh Defines the mesh we want the helper attached to + * @param meshSpaceDirection Defines the direction of the Ray in mesh space (local space of the mesh node) + * @param meshSpaceOrigin Defines the origin of the Ray in mesh space (local space of the mesh node) + * @param length Defines the length of the ray + */ + RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) { + this._attachedToMesh = mesh; + var ray = this.ray; + if (!ray) { + return; + } + if (!ray.direction) { + ray.direction = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(); + } + if (!ray.origin) { + ray.origin = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(); + } + if (length) { + ray.length = length; + } + if (!meshSpaceOrigin) { + meshSpaceOrigin = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(); + } + if (!meshSpaceDirection) { + // -1 so that this will work with Mesh.lookAt + meshSpaceDirection = new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"](0, 0, -1); + } + if (!this._meshSpaceDirection) { + this._meshSpaceDirection = meshSpaceDirection.clone(); + this._meshSpaceOrigin = meshSpaceOrigin.clone(); + } + else { + this._meshSpaceDirection.copyFrom(meshSpaceDirection); + this._meshSpaceOrigin.copyFrom(meshSpaceOrigin); + } + if (!this._updateToMeshFunction) { + this._updateToMeshFunction = this._updateToMesh.bind(this); + this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction); + } + this._updateToMesh(); + }; + /** + * Detach the ray helper from the mesh it has previously been attached to. + */ + RayHelper.prototype.detachFromMesh = function () { + if (this._attachedToMesh) { + if (this._updateToMeshFunction) { + this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction); + } + this._attachedToMesh = null; + this._updateToMeshFunction = null; + } + }; + RayHelper.prototype._updateToMesh = function () { + var ray = this.ray; + if (!this._attachedToMesh || !ray) { + return; + } + if (this._attachedToMesh._isDisposed) { + this.detachFromMesh(); + return; + } + this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction); + _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin); + }; + /** + * Dispose the helper and release its associated resources. + */ + RayHelper.prototype.dispose = function () { + this.hide(); + this.detachFromMesh(); + this.ray = null; + }; + return RayHelper; +}()); + + + +/***/ }), + +/***/ "./Debug/skeletonViewer.ts": +/*!*********************************!*\ + !*** ./Debug/skeletonViewer.ts ***! + \*********************************/ +/*! exports provided: SkeletonViewer */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SkeletonViewer", function() { return SkeletonViewer; }); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Meshes/Builders/linesBuilder */ "./Meshes/Builders/linesBuilder.ts"); +/* harmony import */ var _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Rendering/utilityLayerRenderer */ "./Rendering/utilityLayerRenderer.ts"); + + + +/** + * Class used to render a debug view of a given skeleton + * @see http://www.babylonjs-playground.com/#1BZJVJ#8 + */ +var SkeletonViewer = /** @class */ (function () { + /** + * Creates a new SkeletonViewer + * @param skeleton defines the skeleton to render + * @param mesh defines the mesh attached to the skeleton + * @param scene defines the hosting scene + * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) + * @param renderingGroupId defines the rendering group id to use with the viewer + */ + function SkeletonViewer( + /** defines the skeleton to render */ + skeleton, + /** defines the mesh attached to the skeleton */ + mesh, scene, + /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */ + autoUpdateBonesMatrices, + /** defines the rendering group id to use with the viewer */ + renderingGroupId) { + if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; } + if (renderingGroupId === void 0) { renderingGroupId = 1; } + this.skeleton = skeleton; + this.mesh = mesh; + this.autoUpdateBonesMatrices = autoUpdateBonesMatrices; + this.renderingGroupId = renderingGroupId; + /** Gets or sets the color used to render the skeleton */ + this.color = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Color3"].White(); + this._debugLines = new Array(); + this._isEnabled = false; + this._scene = scene; + this._utilityLayer = new _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_2__["UtilityLayerRenderer"](this._scene, false); + this._utilityLayer.pickUtilitySceneFirst = false; + this._utilityLayer.utilityLayerScene.autoClearDepthAndStencil = true; + this.update(); + this._renderFunction = this.update.bind(this); + } + Object.defineProperty(SkeletonViewer.prototype, "debugMesh", { + /** + * Returns the mesh used to render the bones + */ + get: function () { + return this._debugMesh; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SkeletonViewer.prototype, "isEnabled", { + get: function () { + return this._isEnabled; + }, + /** Gets or sets a boolean indicating if the viewer is enabled */ + set: function (value) { + if (this._isEnabled === value) { + return; + } + this._isEnabled = value; + if (value) { + this._scene.registerBeforeRender(this._renderFunction); + } + else { + this._scene.unregisterBeforeRender(this._renderFunction); + } + }, + enumerable: true, + configurable: true + }); + SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) { + if (x === void 0) { x = 0; } + if (y === void 0) { y = 0; } + if (z === void 0) { z = 0; } + var tmat = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tmp"].Matrix[0]; + var parentBone = bone.getParent(); + tmat.copyFrom(bone.getLocalMatrix()); + if (x !== 0 || y !== 0 || z !== 0) { + var tmat2 = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tmp"].Matrix[1]; + _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].IdentityToRef(tmat2); + tmat2.setTranslationFromFloats(x, y, z); + tmat2.multiplyToRef(tmat, tmat); + } + if (parentBone) { + tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat); + } + tmat.multiplyToRef(meshMat, tmat); + position.x = tmat.m[12]; + position.y = tmat.m[13]; + position.z = tmat.m[14]; + }; + SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) { + var len = bones.length; + var mesh = this.mesh._effectiveMesh; + var meshPos = mesh.position; + for (var i = 0; i < len; i++) { + var bone = bones[i]; + var points = this._debugLines[i]; + if (!points) { + points = [_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(), _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero()]; + this._debugLines[i] = points; + } + this._getBonePosition(points[0], bone, meshMat); + this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0); + points[0].subtractInPlace(meshPos); + points[1].subtractInPlace(meshPos); + } + }; + SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) { + var len = bones.length; + var boneNum = 0; + var mesh = this.mesh._effectiveMesh; + var meshPos = mesh.position; + for (var i = len - 1; i >= 0; i--) { + var childBone = bones[i]; + var parentBone = childBone.getParent(); + if (!parentBone) { + continue; + } + var points = this._debugLines[boneNum]; + if (!points) { + points = [_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(), _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero()]; + this._debugLines[boneNum] = points; + } + childBone.getAbsolutePositionToRef(mesh, points[0]); + parentBone.getAbsolutePositionToRef(mesh, points[1]); + points[0].subtractInPlace(meshPos); + points[1].subtractInPlace(meshPos); + boneNum++; + } + }; + /** Update the viewer to sync with current skeleton state */ + SkeletonViewer.prototype.update = function () { + if (!this._utilityLayer) { + return; + } + if (this.autoUpdateBonesMatrices) { + this.skeleton.computeAbsoluteTransforms(); + } + var mesh = this.mesh._effectiveMesh; + if (this.skeleton.bones[0].length === undefined) { + this._getLinesForBonesNoLength(this.skeleton.bones, mesh.getWorldMatrix()); + } + else { + this._getLinesForBonesWithLength(this.skeleton.bones, mesh.getWorldMatrix()); + } + var targetScene = this._utilityLayer.utilityLayerScene; + if (!this._debugMesh) { + this._debugMesh = _Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_1__["LinesBuilder"].CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, targetScene); + this._debugMesh.renderingGroupId = this.renderingGroupId; + } + else { + _Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_1__["LinesBuilder"].CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, targetScene); + } + this._debugMesh.position.copyFrom(this.mesh.position); + this._debugMesh.color = this.color; + }; + /** Release associated resources */ + SkeletonViewer.prototype.dispose = function () { + this.isEnabled = false; + if (this._debugMesh) { + this.isEnabled = false; + this._debugMesh.dispose(); + this._debugMesh = null; + } + if (this._utilityLayer) { + this._utilityLayer.dispose(); + this._utilityLayer = null; + } + }; + return SkeletonViewer; +}()); + + + +/***/ }), + +/***/ "./Engines/Extensions/engine.cubeTexture.ts": +/*!**************************************************!*\ + !*** ./Engines/Extensions/engine.cubeTexture.ts ***! + \**************************************************/ +/*! no exports provided */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Engines/engine */ "./Engines/engine.ts"); +/* harmony import */ var _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Materials/Textures/internalTexture */ "./Materials/Textures/internalTexture.ts"); +/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Misc/logger */ "./Misc/logger.ts"); +/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Misc/tools */ "./Misc/tools.ts"); + + + + + +_Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].prototype._createDepthStencilCubeTexture = function (size, options) { + var internalTexture = new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_2__["InternalTexture"](this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_2__["InternalTexture"].DATASOURCE_UNKNOWN); + internalTexture.isCube = true; + if (this.webGLVersion === 1) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_3__["Logger"].Error("Depth cube texture is not supported by WebGL 1."); + return internalTexture; + } + var internalOptions = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options); + var gl = this._gl; + this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true); + this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction); + // Create the depth/stencil buffer + for (var face = 0; face < 6; face++) { + if (internalOptions.generateStencil) { + gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH24_STENCIL8, size, size, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null); + } + else { + gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null); + } + } + this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null); + return internalTexture; +}; +_Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].prototype._partialLoadFile = function (url, index, loadedFiles, onfinish, onErrorCallBack) { + if (onErrorCallBack === void 0) { onErrorCallBack = null; } + var onload = function (data) { + loadedFiles[index] = data; + loadedFiles._internalCount++; + if (loadedFiles._internalCount === 6) { + onfinish(loadedFiles); + } + }; + var onerror = function (request, exception) { + if (onErrorCallBack && request) { + onErrorCallBack(request.status + " " + request.statusText, exception); + } + }; + this._loadFile(url, onload, undefined, undefined, true, onerror); +}; +_Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) { + if (onError === void 0) { onError = null; } + var loadedFiles = []; + loadedFiles._internalCount = 0; + for (var index = 0; index < 6; index++) { + this._partialLoadFile(files[index], index, loadedFiles, onfinish, onError); + } +}; +_Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].prototype._cascadeLoadImgs = function (scene, onfinish, files, onError) { + if (onError === void 0) { onError = null; } + var loadedImages = []; + loadedImages._internalCount = 0; + for (var index = 0; index < 6; index++) { + this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError); + } +}; +_Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) { + if (onErrorCallBack === void 0) { onErrorCallBack = null; } + var img; + var onload = function () { + loadedImages[index] = img; + loadedImages._internalCount++; + if (scene) { + scene._removePendingData(img); + } + if (loadedImages._internalCount === 6) { + onfinish(loadedImages); + } + }; + var onerror = function (message, exception) { + if (scene) { + scene._removePendingData(img); + } + if (onErrorCallBack) { + onErrorCallBack(message, exception); + } + }; + img = _Misc_tools__WEBPACK_IMPORTED_MODULE_4__["Tools"].LoadImage(url, onload, onerror, scene ? scene.offlineProvider : null); + if (scene) { + scene._addPendingData(img); + } +}; +_Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback, excludeLoaders) { + var _this = this; + if (onLoad === void 0) { onLoad = null; } + if (onError === void 0) { onError = null; } + if (forcedExtension === void 0) { forcedExtension = null; } + if (createPolynomials === void 0) { createPolynomials = false; } + if (lodScale === void 0) { lodScale = 0; } + if (lodOffset === void 0) { lodOffset = 0; } + if (fallback === void 0) { fallback = null; } + if (excludeLoaders === void 0) { excludeLoaders = []; } + var gl = this._gl; + var texture = fallback ? fallback : new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_2__["InternalTexture"](this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_2__["InternalTexture"].DATASOURCE_CUBE); + texture.isCube = true; + texture.url = rootUrl; + texture.generateMipMaps = !noMipmap; + texture._lodGenerationScale = lodScale; + texture._lodGenerationOffset = lodOffset; + if (!this._doNotHandleContextLost) { + texture._extension = forcedExtension; + texture._files = files; + } + var lastDot = rootUrl.lastIndexOf('.'); + var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : ""); + var loader = null; + for (var _i = 0, _a = _Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"]._TextureLoaders; _i < _a.length; _i++) { + var availableLoader = _a[_i]; + if (excludeLoaders.indexOf(availableLoader) === -1 && availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) { + loader = availableLoader; + break; + } + } + var onInternalError = function (request, exception) { + if (loader) { + var fallbackUrl = loader.getFallbackTextureUrl(texture.url, _this._textureFormatInUse); + _Misc_logger__WEBPACK_IMPORTED_MODULE_3__["Logger"].Warn(loader.constructor.name + " failed when trying to load " + texture.url + ", falling back to the next supported loader"); + if (fallbackUrl) { + excludeLoaders.push(loader); + _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture, excludeLoaders); + return; + } + } + if (onError && request) { + onError(request.status + " " + request.statusText, exception); + } + }; + if (loader) { + rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse); + var onloaddata = function (data) { + _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true); + loader.loadCubeData(data, texture, createPolynomials, onLoad, onError); + }; + if (files && files.length === 6) { + if (loader.supportCascades) { + this._cascadeLoadFiles(scene, onloaddata, files, onError); + } + else { + if (onError) { + onError("Textures type does not support cascades."); + } + else { + _Misc_logger__WEBPACK_IMPORTED_MODULE_3__["Logger"].Warn("Texture loader does not support cascades."); + } + } + } + else { + this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError); + } + } + else { + if (!files) { + throw new Error("Cannot load cubemap because files were not defined"); + } + this._cascadeLoadImgs(scene, function (imgs) { + var width = _this.needPOTTextures ? _Misc_tools__WEBPACK_IMPORTED_MODULE_4__["Tools"].GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width; + var height = width; + _this._prepareWorkingCanvas(); + if (!_this._workingCanvas || !_this._workingContext) { + return; + } + _this._workingCanvas.width = width; + _this._workingCanvas.height = height; + var faces = [ + gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z, + gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z + ]; + _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true); + _this._unpackFlipY(false); + var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA; + for (var index = 0; index < faces.length; index++) { + if (imgs[index].width !== width || imgs[index].height !== height) { + _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height); + gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas); + } + else { + gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, imgs[index]); + } + } + if (!noMipmap) { + gl.generateMipmap(gl.TEXTURE_CUBE_MAP); + } + _this._setCubeMapTextureParams(!noMipmap); + texture.width = width; + texture.height = height; + texture.isReady = true; + if (format) { + texture.format = format; + } + texture.onLoadedObservable.notifyObservers(texture); + texture.onLoadedObservable.clear(); + if (onLoad) { + onLoad(); + } + }, files, onError); + } + this._internalTexturesCache.push(texture); + return texture; +}; + + +/***/ }), + +/***/ "./Engines/Extensions/engine.multiRender.ts": +/*!**************************************************!*\ + !*** ./Engines/Extensions/engine.multiRender.ts ***! + \**************************************************/ +/*! no exports provided */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Engines/engine */ "./Engines/engine.ts"); +/* harmony import */ var _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Materials/Textures/internalTexture */ "./Materials/Textures/internalTexture.ts"); +/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/logger */ "./Misc/logger.ts"); + + + +_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) { + if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; } + this._currentRenderTarget = null; + // If MSAA, we need to bitblt back to main texture + var gl = this._gl; + if (textures[0]._MSAAFramebuffer) { + gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer); + gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer); + var attachments = textures[0]._attachments; + if (!attachments) { + attachments = new Array(textures.length); + textures[0]._attachments = attachments; + } + for (var i = 0; i < textures.length; i++) { + var texture = textures[i]; + for (var j = 0; j < attachments.length; j++) { + attachments[j] = gl.NONE; + } + attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"]; + gl.readBuffer(attachments[i]); + gl.drawBuffers(attachments); + gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST); + } + for (var i = 0; i < attachments.length; i++) { + attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"]; + } + gl.drawBuffers(attachments); + } + for (var i = 0; i < textures.length; i++) { + var texture = textures[i]; + if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) { + this._bindTextureDirectly(gl.TEXTURE_2D, texture); + gl.generateMipmap(gl.TEXTURE_2D); + this._bindTextureDirectly(gl.TEXTURE_2D, null); + } + } + if (onBeforeUnbind) { + if (textures[0]._MSAAFramebuffer) { + // Bind the correct framebuffer + this._bindUnboundFramebuffer(textures[0]._framebuffer); + } + onBeforeUnbind(); + } + this._bindUnboundFramebuffer(null); +}; +_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.createMultipleRenderTarget = function (size, options) { + var generateMipMaps = false; + var generateDepthBuffer = true; + var generateStencilBuffer = false; + var generateDepthTexture = false; + var textureCount = 1; + var defaultType = _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].TEXTURETYPE_UNSIGNED_INT; + var defaultSamplingMode = _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].TEXTURE_TRILINEAR_SAMPLINGMODE; + var types = new Array(); + var samplingModes = new Array(); + if (options !== undefined) { + generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps; + generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer; + generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer; + generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture; + textureCount = options.textureCount || 1; + if (options.types) { + types = options.types; + } + if (options.samplingModes) { + samplingModes = options.samplingModes; + } + } + var gl = this._gl; + // Create the framebuffer + var framebuffer = gl.createFramebuffer(); + this._bindUnboundFramebuffer(framebuffer); + var width = size.width || size; + var height = size.height || size; + var textures = []; + var attachments = []; + var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height); + for (var i = 0; i < textureCount; i++) { + var samplingMode = samplingModes[i] || defaultSamplingMode; + var type = types[i] || defaultType; + if (type === _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) { + // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE + samplingMode = _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].TEXTURE_NEAREST_SAMPLINGMODE; + } + else if (type === _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) { + // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE + samplingMode = _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].TEXTURE_NEAREST_SAMPLINGMODE; + } + var filters = this._getSamplingParameters(samplingMode, generateMipMaps); + if (type === _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].TEXTURETYPE_FLOAT && !this._caps.textureFloat) { + type = _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].TEXTURETYPE_UNSIGNED_INT; + _Misc_logger__WEBPACK_IMPORTED_MODULE_2__["Logger"].Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type"); + } + var texture = new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_1__["InternalTexture"](this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_1__["InternalTexture"].DATASOURCE_MULTIRENDERTARGET); + var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"]; + textures.push(texture); + attachments.push(attachment); + gl.activeTexture(gl["TEXTURE" + i]); + gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null); + gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0); + if (generateMipMaps) { + this._gl.generateMipmap(this._gl.TEXTURE_2D); + } + // Unbind + this._bindTextureDirectly(gl.TEXTURE_2D, null); + texture._framebuffer = framebuffer; + texture._depthStencilBuffer = depthStencilBuffer; + texture.baseWidth = width; + texture.baseHeight = height; + texture.width = width; + texture.height = height; + texture.isReady = true; + texture.samples = 1; + texture.generateMipMaps = generateMipMaps; + texture.samplingMode = samplingMode; + texture.type = type; + texture._generateDepthBuffer = generateDepthBuffer; + texture._generateStencilBuffer = generateStencilBuffer; + texture._attachments = attachments; + this._internalTexturesCache.push(texture); + } + if (generateDepthTexture && this._caps.depthTextureExtension) { + // Depth texture + var depthTexture = new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_1__["InternalTexture"](this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_1__["InternalTexture"].DATASOURCE_MULTIRENDERTARGET); + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + gl.texImage2D(gl.TEXTURE_2D, 0, this.webGLVersion < 2 ? gl.DEPTH_COMPONENT : gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null); + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0); + depthTexture._framebuffer = framebuffer; + depthTexture.baseWidth = width; + depthTexture.baseHeight = height; + depthTexture.width = width; + depthTexture.height = height; + depthTexture.isReady = true; + depthTexture.samples = 1; + depthTexture.generateMipMaps = generateMipMaps; + depthTexture.samplingMode = gl.NEAREST; + depthTexture._generateDepthBuffer = generateDepthBuffer; + depthTexture._generateStencilBuffer = generateStencilBuffer; + textures.push(depthTexture); + this._internalTexturesCache.push(depthTexture); + } + gl.drawBuffers(attachments); + gl.bindRenderbuffer(gl.RENDERBUFFER, null); + this._bindUnboundFramebuffer(null); + this.resetTextureCache(); + return textures; +}; +_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) { + if (this.webGLVersion < 2 || !textures || textures.length == 0) { + return 1; + } + if (textures[0].samples === samples) { + return samples; + } + var gl = this._gl; + samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES)); + // Dispose previous render buffers + if (textures[0]._depthStencilBuffer) { + gl.deleteRenderbuffer(textures[0]._depthStencilBuffer); + textures[0]._depthStencilBuffer = null; + } + if (textures[0]._MSAAFramebuffer) { + gl.deleteFramebuffer(textures[0]._MSAAFramebuffer); + textures[0]._MSAAFramebuffer = null; + } + for (var i = 0; i < textures.length; i++) { + if (textures[i]._MSAARenderBuffer) { + gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer); + textures[i]._MSAARenderBuffer = null; + } + } + if (samples > 1) { + var framebuffer = gl.createFramebuffer(); + if (!framebuffer) { + throw new Error("Unable to create multi sampled framebuffer"); + } + this._bindUnboundFramebuffer(framebuffer); + var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples); + var attachments = []; + for (var i = 0; i < textures.length; i++) { + var texture = textures[i]; + var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"]; + var colorRenderbuffer = gl.createRenderbuffer(); + if (!colorRenderbuffer) { + throw new Error("Unable to create multi sampled framebuffer"); + } + gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer); + gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height); + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer); + texture._MSAAFramebuffer = framebuffer; + texture._MSAARenderBuffer = colorRenderbuffer; + texture.samples = samples; + texture._depthStencilBuffer = depthStencilBuffer; + gl.bindRenderbuffer(gl.RENDERBUFFER, null); + attachments.push(attachment); + } + gl.drawBuffers(attachments); + } + else { + this._bindUnboundFramebuffer(textures[0]._framebuffer); + } + this._bindUnboundFramebuffer(null); + return samples; +}; + + +/***/ }), + +/***/ "./Engines/Extensions/engine.multiview.ts": +/*!************************************************!*\ + !*** ./Engines/Extensions/engine.multiview.ts ***! + \************************************************/ +/*! no exports provided */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Cameras/camera */ "./Cameras/camera.ts"); +/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Engines/engine */ "./Engines/engine.ts"); +/* harmony import */ var _scene__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../scene */ "./scene.ts"); +/* harmony import */ var _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Materials/Textures/internalTexture */ "./Materials/Textures/internalTexture.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Materials_uniformBuffer__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Materials/uniformBuffer */ "./Materials/uniformBuffer.ts"); +/* harmony import */ var _Materials_Textures_MultiviewRenderTarget__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../Materials/Textures/MultiviewRenderTarget */ "./Materials/Textures/MultiviewRenderTarget.ts"); + + + + + + + +_Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].prototype.createMultiviewRenderTargetTexture = function (width, height) { + var gl = this._gl; + if (!this.getCaps().multiview) { + throw "Multiview is not supported"; + } + var internalTexture = new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_3__["InternalTexture"](this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_3__["InternalTexture"].DATASOURCE_UNKNOWN, true); + internalTexture.width = width; + internalTexture.height = height; + internalTexture._framebuffer = gl.createFramebuffer(); + internalTexture._colorTextureArray = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D_ARRAY, internalTexture._colorTextureArray); + gl.texStorage3D(gl.TEXTURE_2D_ARRAY, 1, gl.RGBA8, width, height, 2); + internalTexture._depthStencilTextureArray = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D_ARRAY, internalTexture._depthStencilTextureArray); + gl.texStorage3D(gl.TEXTURE_2D_ARRAY, 1, gl.DEPTH32F_STENCIL8, width, height, 2); + internalTexture.isReady = true; + return internalTexture; +}; +_Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].prototype.bindMultiviewFramebuffer = function (multiviewTexture) { + var gl = this._gl; + var ext = this.getCaps().multiview; + this.bindFramebuffer(multiviewTexture, undefined, undefined, undefined, true); + gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, multiviewTexture._framebuffer); + if (multiviewTexture._colorTextureArray && multiviewTexture._depthStencilTextureArray) { + ext.framebufferTextureMultiviewOVR(gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, multiviewTexture._colorTextureArray, 0, 0, 2); + ext.framebufferTextureMultiviewOVR(gl.DRAW_FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, multiviewTexture._depthStencilTextureArray, 0, 0, 2); + } + else { + throw "Invalid multiview frame buffer"; + } +}; +_Cameras_camera__WEBPACK_IMPORTED_MODULE_0__["Camera"].prototype._useMultiviewToSingleView = false; +_Cameras_camera__WEBPACK_IMPORTED_MODULE_0__["Camera"].prototype._multiviewTexture = null; +_Cameras_camera__WEBPACK_IMPORTED_MODULE_0__["Camera"].prototype._resizeOrCreateMultiviewTexture = function (width, height) { + if (!this._multiviewTexture) { + this._multiviewTexture = new _Materials_Textures_MultiviewRenderTarget__WEBPACK_IMPORTED_MODULE_6__["MultiviewRenderTarget"](this.getScene(), { width: width, height: height }); + } + else if (this._multiviewTexture.getRenderWidth() != width || this._multiviewTexture.getRenderHeight() != height) { + this._multiviewTexture.dispose(); + this._multiviewTexture = new _Materials_Textures_MultiviewRenderTarget__WEBPACK_IMPORTED_MODULE_6__["MultiviewRenderTarget"](this.getScene(), { width: width, height: height }); + } +}; +_scene__WEBPACK_IMPORTED_MODULE_2__["Scene"].prototype._transformMatrixR = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"].Zero(); +_scene__WEBPACK_IMPORTED_MODULE_2__["Scene"].prototype._multiviewSceneUbo = null; +_scene__WEBPACK_IMPORTED_MODULE_2__["Scene"].prototype._createMultiviewUbo = function () { + this._multiviewSceneUbo = new _Materials_uniformBuffer__WEBPACK_IMPORTED_MODULE_5__["UniformBuffer"](this.getEngine(), undefined, true); + this._multiviewSceneUbo.addUniform("viewProjection", 16); + this._multiviewSceneUbo.addUniform("viewProjectionR", 16); + this._multiviewSceneUbo.addUniform("view", 16); +}; +_scene__WEBPACK_IMPORTED_MODULE_2__["Scene"].prototype._updateMultiviewUbo = function (viewR, projectionR) { + if (viewR && projectionR) { + viewR.multiplyToRef(projectionR, this._transformMatrixR); + } + if (viewR && projectionR) { + viewR.multiplyToRef(projectionR, _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Tmp"].Matrix[0]); + _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Frustum"].GetRightPlaneToRef(_Maths_math__WEBPACK_IMPORTED_MODULE_4__["Tmp"].Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane + } + if (this._multiviewSceneUbo) { + this._multiviewSceneUbo.updateMatrix("viewProjection", this.getTransformMatrix()); + this._multiviewSceneUbo.updateMatrix("viewProjectionR", this._transformMatrixR); + this._multiviewSceneUbo.updateMatrix("view", this._viewMatrix); + this._multiviewSceneUbo.update(); + } +}; +_scene__WEBPACK_IMPORTED_MODULE_2__["Scene"].prototype._renderMultiviewToSingleView = function (camera) { + // Multiview is only able to be displayed directly for API's such as webXR + // This displays a multiview image by rendering to the multiview image and then + // copying the result into the sub cameras instead of rendering them and proceeding as normal from there + // Render to a multiview texture + camera._resizeOrCreateMultiviewTexture((camera._rigPostProcess && camera._rigPostProcess && camera._rigPostProcess.width > 0) ? camera._rigPostProcess.width / 2 : this.getEngine().getRenderWidth(true) / 2, (camera._rigPostProcess && camera._rigPostProcess && camera._rigPostProcess.height > 0) ? camera._rigPostProcess.height : this.getEngine().getRenderHeight(true)); + if (!this._multiviewSceneUbo) { + this._createMultiviewUbo(); + } + camera.outputRenderTarget = camera._multiviewTexture; + this._renderForCamera(camera); + camera.outputRenderTarget = null; + // Consume the multiview texture through a shader for each eye + for (var index = 0; index < camera._rigCameras.length; index++) { + var engine = this.getEngine(); + this._activeCamera = camera._rigCameras[index]; + engine.setViewport(this._activeCamera.viewport); + if (this.postProcessManager) { + this.postProcessManager._prepareFrame(); + this.postProcessManager._finalizeFrame(this._activeCamera.isIntermediate); + } + } +}; + + +/***/ }), + +/***/ "./Engines/Extensions/engine.occlusionQuery.ts": +/*!*****************************************************!*\ + !*** ./Engines/Extensions/engine.occlusionQuery.ts ***! + \*****************************************************/ +/*! exports provided: _OcclusionDataStorage */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_OcclusionDataStorage", function() { return _OcclusionDataStorage; }); +/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Engines/engine */ "./Engines/engine.ts"); +/* harmony import */ var _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Meshes/abstractMesh */ "./Meshes/abstractMesh.ts"); +/* harmony import */ var _Instrumentation_timeToken__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Instrumentation/timeToken */ "./Instrumentation/timeToken.ts"); + + + +/** @hidden */ +var _OcclusionDataStorage = /** @class */ (function () { + function _OcclusionDataStorage() { + /** @hidden */ + this.occlusionInternalRetryCounter = 0; + /** @hidden */ + this.isOcclusionQueryInProgress = false; + /** @hidden */ + this.isOccluded = false; + /** @hidden */ + this.occlusionRetryCount = -1; + /** @hidden */ + this.occlusionType = _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_1__["AbstractMesh"].OCCLUSION_TYPE_NONE; + /** @hidden */ + this.occlusionQueryAlgorithmType = _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_1__["AbstractMesh"].OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE; + } + return _OcclusionDataStorage; +}()); + +_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.createQuery = function () { + return this._gl.createQuery(); +}; +_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.deleteQuery = function (query) { + this._gl.deleteQuery(query); + return this; +}; +_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.isQueryResultAvailable = function (query) { + return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE); +}; +_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.getQueryResult = function (query) { + return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT); +}; +_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.beginOcclusionQuery = function (algorithmType, query) { + var glAlgorithm = this._getGlAlgorithmType(algorithmType); + this._gl.beginQuery(glAlgorithm, query); + return this; +}; +_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.endOcclusionQuery = function (algorithmType) { + var glAlgorithm = this._getGlAlgorithmType(algorithmType); + this._gl.endQuery(glAlgorithm); + return this; +}; +_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype._createTimeQuery = function () { + var timerQuery = this.getCaps().timerQuery; + if (timerQuery.createQueryEXT) { + return timerQuery.createQueryEXT(); + } + return this.createQuery(); +}; +_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype._deleteTimeQuery = function (query) { + var timerQuery = this.getCaps().timerQuery; + if (timerQuery.deleteQueryEXT) { + timerQuery.deleteQueryEXT(query); + return; + } + this.deleteQuery(query); +}; +_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype._getTimeQueryResult = function (query) { + var timerQuery = this.getCaps().timerQuery; + if (timerQuery.getQueryObjectEXT) { + return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT); + } + return this.getQueryResult(query); +}; +_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype._getTimeQueryAvailability = function (query) { + var timerQuery = this.getCaps().timerQuery; + if (timerQuery.getQueryObjectEXT) { + return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT); + } + return this.isQueryResultAvailable(query); +}; +_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.startTimeQuery = function () { + var caps = this.getCaps(); + var timerQuery = caps.timerQuery; + if (!timerQuery) { + return null; + } + var token = new _Instrumentation_timeToken__WEBPACK_IMPORTED_MODULE_2__["_TimeToken"](); + this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT); + if (caps.canUseTimestampForTimerQuery) { + token._startTimeQuery = this._createTimeQuery(); + timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT); + } + else { + if (this._currentNonTimestampToken) { + return this._currentNonTimestampToken; + } + token._timeElapsedQuery = this._createTimeQuery(); + if (timerQuery.beginQueryEXT) { + timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery); + } + else { + this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery); + } + this._currentNonTimestampToken = token; + } + return token; +}; +_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.endTimeQuery = function (token) { + var caps = this.getCaps(); + var timerQuery = caps.timerQuery; + if (!timerQuery || !token) { + return -1; + } + if (caps.canUseTimestampForTimerQuery) { + if (!token._startTimeQuery) { + return -1; + } + if (!token._endTimeQuery) { + token._endTimeQuery = this._createTimeQuery(); + timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT); + } + } + else if (!token._timeElapsedQueryEnded) { + if (!token._timeElapsedQuery) { + return -1; + } + if (timerQuery.endQueryEXT) { + timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT); + } + else { + this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT); + } + token._timeElapsedQueryEnded = true; + } + var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT); + var available = false; + if (token._endTimeQuery) { + available = this._getTimeQueryAvailability(token._endTimeQuery); + } + else if (token._timeElapsedQuery) { + available = this._getTimeQueryAvailability(token._timeElapsedQuery); + } + if (available && !disjoint) { + var result = 0; + if (caps.canUseTimestampForTimerQuery) { + if (!token._startTimeQuery || !token._endTimeQuery) { + return -1; + } + var timeStart = this._getTimeQueryResult(token._startTimeQuery); + var timeEnd = this._getTimeQueryResult(token._endTimeQuery); + result = timeEnd - timeStart; + this._deleteTimeQuery(token._startTimeQuery); + this._deleteTimeQuery(token._endTimeQuery); + token._startTimeQuery = null; + token._endTimeQuery = null; + } + else { + if (!token._timeElapsedQuery) { + return -1; + } + result = this._getTimeQueryResult(token._timeElapsedQuery); + this._deleteTimeQuery(token._timeElapsedQuery); + token._timeElapsedQuery = null; + token._timeElapsedQueryEnded = false; + this._currentNonTimestampToken = null; + } + return result; + } + return -1; +}; +_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype._getGlAlgorithmType = function (algorithmType) { + return algorithmType === _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_1__["AbstractMesh"].OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED; +}; +Object.defineProperty(_Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_1__["AbstractMesh"].prototype, "isOcclusionQueryInProgress", { + get: function () { + return this._occlusionDataStorage.isOcclusionQueryInProgress; + }, + enumerable: false, + configurable: true +}); +Object.defineProperty(_Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_1__["AbstractMesh"].prototype, "_occlusionDataStorage", { + get: function () { + if (!this.__occlusionDataStorage) { + this.__occlusionDataStorage = new _OcclusionDataStorage(); + } + return this.__occlusionDataStorage; + }, + enumerable: false, + configurable: true +}); +Object.defineProperty(_Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_1__["AbstractMesh"].prototype, "isOccluded", { + get: function () { + return this._occlusionDataStorage.isOccluded; + }, + set: function (value) { + this._occlusionDataStorage.isOccluded = value; + }, + enumerable: true, + configurable: true +}); +Object.defineProperty(_Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_1__["AbstractMesh"].prototype, "occlusionQueryAlgorithmType", { + get: function () { + return this._occlusionDataStorage.occlusionQueryAlgorithmType; + }, + set: function (value) { + this._occlusionDataStorage.occlusionQueryAlgorithmType = value; + }, + enumerable: true, + configurable: true +}); +Object.defineProperty(_Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_1__["AbstractMesh"].prototype, "occlusionType", { + get: function () { + return this._occlusionDataStorage.occlusionType; + }, + set: function (value) { + this._occlusionDataStorage.occlusionType = value; + }, + enumerable: true, + configurable: true +}); +Object.defineProperty(_Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_1__["AbstractMesh"].prototype, "occlusionRetryCount", { + get: function () { + return this._occlusionDataStorage.occlusionRetryCount; + }, + set: function (value) { + this._occlusionDataStorage.occlusionRetryCount = value; + }, + enumerable: true, + configurable: true +}); +// We also need to update AbstractMesh as there is a portion of the code there +_Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_1__["AbstractMesh"].prototype._checkOcclusionQuery = function () { + var dataStorage = this._occlusionDataStorage; + if (dataStorage.occlusionType === _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_1__["AbstractMesh"].OCCLUSION_TYPE_NONE) { + dataStorage.isOccluded = false; + return false; + } + var engine = this.getEngine(); + if (engine.webGLVersion < 2) { + dataStorage.isOccluded = false; + return false; + } + if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced + dataStorage.isOccluded = false; + return false; + } + if (this.isOcclusionQueryInProgress && this._occlusionQuery) { + var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery); + if (isOcclusionQueryAvailable) { + var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery); + dataStorage.isOcclusionQueryInProgress = false; + dataStorage.occlusionInternalRetryCounter = 0; + dataStorage.isOccluded = occlusionQueryResult === 1 ? false : true; + } + else { + dataStorage.occlusionInternalRetryCounter++; + if (dataStorage.occlusionRetryCount !== -1 && dataStorage.occlusionInternalRetryCounter > dataStorage.occlusionRetryCount) { + dataStorage.isOcclusionQueryInProgress = false; + dataStorage.occlusionInternalRetryCounter = 0; + // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop) + // if strict continue the last state of the object. + dataStorage.isOccluded = dataStorage.occlusionType === _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_1__["AbstractMesh"].OCCLUSION_TYPE_OPTIMISTIC ? false : dataStorage.isOccluded; + } + else { + return false; + } + } + } + var scene = this.getScene(); + if (scene.getBoundingBoxRenderer) { + var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer(); + if (!this._occlusionQuery) { + this._occlusionQuery = engine.createQuery(); + } + engine.beginOcclusionQuery(dataStorage.occlusionQueryAlgorithmType, this._occlusionQuery); + occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this); + engine.endOcclusionQuery(dataStorage.occlusionQueryAlgorithmType); + this._occlusionDataStorage.isOcclusionQueryInProgress = true; + } + return dataStorage.isOccluded; +}; + + +/***/ }), + +/***/ "./Engines/Extensions/engine.rawTexture.ts": +/*!*************************************************!*\ + !*** ./Engines/Extensions/engine.rawTexture.ts ***! + \*************************************************/ +/*! no exports provided */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Engines/engine */ "./Engines/engine.ts"); +/* harmony import */ var _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Materials/Textures/internalTexture */ "./Materials/Textures/internalTexture.ts"); +/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/logger */ "./Misc/logger.ts"); +/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Misc/tools */ "./Misc/tools.ts"); + + + + +_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) { + if (compression === void 0) { compression = null; } + if (type === void 0) { type = _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].TEXTURETYPE_UNSIGNED_INT; } + if (!texture) { + return; + } + // Babylon's internalSizedFomat but gl's texImage2D internalFormat + var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format); + // Babylon's internalFormat but gl's texImage2D format + var internalFormat = this._getInternalFormat(format); + var textureType = this._getWebGLTextureType(type); + this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true); + this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false)); + if (!this._doNotHandleContextLost) { + texture._bufferView = data; + texture.format = format; + texture.type = type; + texture.invertY = invertY; + texture._compression = compression; + } + if (texture.width % 4 !== 0) { + this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1); + } + if (compression && data) { + this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data); + } + else { + this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data); + } + if (texture.generateMipMaps) { + this._gl.generateMipmap(this._gl.TEXTURE_2D); + } + this._bindTextureDirectly(this._gl.TEXTURE_2D, null); + // this.resetTextureCache(); + texture.isReady = true; +}; +_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) { + if (compression === void 0) { compression = null; } + if (type === void 0) { type = _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].TEXTURETYPE_UNSIGNED_INT; } + var texture = new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_1__["InternalTexture"](this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_1__["InternalTexture"].DATASOURCE_RAW); + texture.baseWidth = width; + texture.baseHeight = height; + texture.width = width; + texture.height = height; + texture.format = format; + texture.generateMipMaps = generateMipMaps; + texture.samplingMode = samplingMode; + texture.invertY = invertY; + texture._compression = compression; + texture.type = type; + if (!this._doNotHandleContextLost) { + texture._bufferView = data; + } + this.updateRawTexture(texture, data, format, invertY, compression, type); + this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true); + // Filters + var filters = this._getSamplingParameters(samplingMode, generateMipMaps); + this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag); + this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min); + if (generateMipMaps) { + this._gl.generateMipmap(this._gl.TEXTURE_2D); + } + this._bindTextureDirectly(this._gl.TEXTURE_2D, null); + this._internalTexturesCache.push(texture); + return texture; +}; +_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) { + if (compression === void 0) { compression = null; } + var gl = this._gl; + var texture = new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_1__["InternalTexture"](this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_1__["InternalTexture"].DATASOURCE_CUBERAW); + texture.isCube = true; + texture.format = format; + texture.type = type; + if (!this._doNotHandleContextLost) { + texture._bufferViewArray = data; + } + var textureType = this._getWebGLTextureType(type); + var internalFormat = this._getInternalFormat(format); + if (internalFormat === gl.RGB) { + internalFormat = gl.RGBA; + } + // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable + if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) { + generateMipMaps = false; + samplingMode = _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].TEXTURE_NEAREST_SAMPLINGMODE; + _Misc_logger__WEBPACK_IMPORTED_MODULE_2__["Logger"].Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively."); + } + else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) { + generateMipMaps = false; + samplingMode = _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].TEXTURE_NEAREST_SAMPLINGMODE; + _Misc_logger__WEBPACK_IMPORTED_MODULE_2__["Logger"].Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively."); + } + else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) { + generateMipMaps = false; + _Misc_logger__WEBPACK_IMPORTED_MODULE_2__["Logger"].Warn("Render to float textures is not supported. Mipmap generation forced to false."); + } + else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) { + generateMipMaps = false; + _Misc_logger__WEBPACK_IMPORTED_MODULE_2__["Logger"].Warn("Render to half float textures is not supported. Mipmap generation forced to false."); + } + var width = size; + var height = width; + texture.width = width; + texture.height = height; + // Double check on POT to generate Mips. + var isPot = !this.needPOTTextures || (_Misc_tools__WEBPACK_IMPORTED_MODULE_3__["Tools"].IsExponentOfTwo(texture.width) && _Misc_tools__WEBPACK_IMPORTED_MODULE_3__["Tools"].IsExponentOfTwo(texture.height)); + if (!isPot) { + generateMipMaps = false; + } + // Upload data if needed. The texture won't be ready until then. + if (data) { + this.updateRawCubeTexture(texture, data, format, type, invertY, compression); + } + this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true); + // Filters + if (data && generateMipMaps) { + this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP); + } + var filters = this._getSamplingParameters(samplingMode, generateMipMaps); + gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag); + gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min); + gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null); + texture.generateMipMaps = generateMipMaps; + return texture; +}; +_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) { + if (compression === void 0) { compression = null; } + if (level === void 0) { level = 0; } + texture._bufferViewArray = data; + texture.format = format; + texture.type = type; + texture.invertY = invertY; + texture._compression = compression; + var gl = this._gl; + var textureType = this._getWebGLTextureType(type); + var internalFormat = this._getInternalFormat(format); + var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type); + var needConversion = false; + if (internalFormat === gl.RGB) { + internalFormat = gl.RGBA; + needConversion = true; + } + this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true); + this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false)); + if (texture.width % 4 !== 0) { + gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1); + } + // Data are known to be in +X +Y +Z -X -Y -Z + for (var faceIndex = 0; faceIndex < 6; faceIndex++) { + var faceData = data[faceIndex]; + if (compression) { + gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData); + } + else { + if (needConversion) { + faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type); + } + gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData); + } + } + var isPot = !this.needPOTTextures || (_Misc_tools__WEBPACK_IMPORTED_MODULE_3__["Tools"].IsExponentOfTwo(texture.width) && _Misc_tools__WEBPACK_IMPORTED_MODULE_3__["Tools"].IsExponentOfTwo(texture.height)); + if (isPot && texture.generateMipMaps && level === 0) { + this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP); + } + this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null); + // this.resetTextureCache(); + texture.isReady = true; +}; +_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) { + var _this = this; + if (onLoad === void 0) { onLoad = null; } + if (onError === void 0) { onError = null; } + if (samplingMode === void 0) { samplingMode = _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].TEXTURE_TRILINEAR_SAMPLINGMODE; } + if (invertY === void 0) { invertY = false; } + var gl = this._gl; + var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode); + scene._addPendingData(texture); + texture.url = url; + this._internalTexturesCache.push(texture); + var onerror = function (request, exception) { + scene._removePendingData(texture); + if (onError && request) { + onError(request.status + " " + request.statusText, exception); + } + }; + var internalCallback = function (data) { + var width = texture.width; + var faceDataArrays = callback(data); + if (!faceDataArrays) { + return; + } + if (mipmapGenerator) { + var textureType = _this._getWebGLTextureType(type); + var internalFormat = _this._getInternalFormat(format); + var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type); + var needConversion = false; + if (internalFormat === gl.RGB) { + internalFormat = gl.RGBA; + needConversion = true; + } + _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true); + _this._unpackFlipY(false); + var mipData = mipmapGenerator(faceDataArrays); + for (var level = 0; level < mipData.length; level++) { + var mipSize = width >> level; + for (var faceIndex = 0; faceIndex < 6; faceIndex++) { + var mipFaceData = mipData[level][faceIndex]; + if (needConversion) { + mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type); + } + gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData); + } + } + _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null); + } + else { + _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY); + } + texture.isReady = true; + // this.resetTextureCache(); + scene._removePendingData(texture); + if (onLoad) { + onLoad(); + } + }; + this._loadFile(url, function (data) { + internalCallback(data); + }, undefined, scene.offlineProvider, true, onerror); + return texture; +}; +_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) { + if (compression === void 0) { compression = null; } + if (textureType === void 0) { textureType = _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].TEXTURETYPE_UNSIGNED_INT; } + var texture = new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_1__["InternalTexture"](this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_1__["InternalTexture"].DATASOURCE_RAW3D); + texture.baseWidth = width; + texture.baseHeight = height; + texture.baseDepth = depth; + texture.width = width; + texture.height = height; + texture.depth = depth; + texture.format = format; + texture.type = textureType; + texture.generateMipMaps = generateMipMaps; + texture.samplingMode = samplingMode; + texture.is3D = true; + if (!this._doNotHandleContextLost) { + texture._bufferView = data; + } + this.updateRawTexture3D(texture, data, format, invertY, compression, textureType); + this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true); + // Filters + var filters = this._getSamplingParameters(samplingMode, generateMipMaps); + this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag); + this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min); + if (generateMipMaps) { + this._gl.generateMipmap(this._gl.TEXTURE_3D); + } + this._bindTextureDirectly(this._gl.TEXTURE_3D, null); + this._internalTexturesCache.push(texture); + return texture; +}; +_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) { + if (compression === void 0) { compression = null; } + if (textureType === void 0) { textureType = _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].TEXTURETYPE_UNSIGNED_INT; } + var internalType = this._getWebGLTextureType(textureType); + var internalFormat = this._getInternalFormat(format); + var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format); + this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true); + this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false)); + if (!this._doNotHandleContextLost) { + texture._bufferView = data; + texture.format = format; + texture.invertY = invertY; + texture._compression = compression; + } + if (texture.width % 4 !== 0) { + this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1); + } + if (compression && data) { + this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data); + } + else { + this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data); + } + if (texture.generateMipMaps) { + this._gl.generateMipmap(this._gl.TEXTURE_3D); + } + this._bindTextureDirectly(this._gl.TEXTURE_3D, null); + // this.resetTextureCache(); + texture.isReady = true; +}; + + +/***/ }), + +/***/ "./Engines/Extensions/engine.renderTarget.ts": +/*!***************************************************!*\ + !*** ./Engines/Extensions/engine.renderTarget.ts ***! + \***************************************************/ +/*! no exports provided */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Engines/engine */ "./Engines/engine.ts"); +/* harmony import */ var _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Materials/Textures/internalTexture */ "./Materials/Textures/internalTexture.ts"); +/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Misc/logger */ "./Misc/logger.ts"); + + + + +_Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].prototype.createRenderTargetCubeTexture = function (size, options) { + var fullOptions = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: _Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].TEXTURETYPE_UNSIGNED_INT, samplingMode: _Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].TEXTURE_TRILINEAR_SAMPLINGMODE, format: _Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].TEXTUREFORMAT_RGBA }, options); + fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer; + if (fullOptions.type === _Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) { + // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE + fullOptions.samplingMode = _Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].TEXTURE_NEAREST_SAMPLINGMODE; + } + else if (fullOptions.type === _Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) { + // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE + fullOptions.samplingMode = _Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].TEXTURE_NEAREST_SAMPLINGMODE; + } + var gl = this._gl; + var texture = new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_2__["InternalTexture"](this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_2__["InternalTexture"].DATASOURCE_RENDERTARGET); + this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true); + var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps); + if (fullOptions.type === _Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].TEXTURETYPE_FLOAT && !this._caps.textureFloat) { + fullOptions.type = _Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].TEXTURETYPE_UNSIGNED_INT; + _Misc_logger__WEBPACK_IMPORTED_MODULE_3__["Logger"].Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type"); + } + gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag); + gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min); + gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + for (var face = 0; face < 6; face++) { + gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), size, size, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null); + } + // Create the framebuffer + var framebuffer = gl.createFramebuffer(); + this._bindUnboundFramebuffer(framebuffer); + texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size); + // MipMaps + if (fullOptions.generateMipMaps) { + gl.generateMipmap(gl.TEXTURE_CUBE_MAP); + } + // Unbind + this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null); + gl.bindRenderbuffer(gl.RENDERBUFFER, null); + this._bindUnboundFramebuffer(null); + texture._framebuffer = framebuffer; + texture.width = size; + texture.height = size; + texture.isReady = true; + texture.isCube = true; + texture.samples = 1; + texture.generateMipMaps = fullOptions.generateMipMaps; + texture.samplingMode = fullOptions.samplingMode; + texture.type = fullOptions.type; + texture.format = fullOptions.format; + texture._generateDepthBuffer = fullOptions.generateDepthBuffer; + texture._generateStencilBuffer = fullOptions.generateStencilBuffer; + this._internalTexturesCache.push(texture); + return texture; +}; + + +/***/ }), + +/***/ "./Engines/Extensions/engine.transformFeedback.ts": +/*!********************************************************!*\ + !*** ./Engines/Extensions/engine.transformFeedback.ts ***! + \********************************************************/ +/*! exports provided: _forceTransformFeedbackToBundle */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_forceTransformFeedbackToBundle", function() { return _forceTransformFeedbackToBundle; }); +/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Engines/engine */ "./Engines/engine.ts"); + +/** @hidden */ +var _forceTransformFeedbackToBundle = true; +_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.createTransformFeedback = function () { + return this._gl.createTransformFeedback(); +}; +_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.deleteTransformFeedback = function (value) { + this._gl.deleteTransformFeedback(value); +}; +_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.bindTransformFeedback = function (value) { + this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value); +}; +_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.beginTransformFeedback = function (usePoints) { + if (usePoints === void 0) { usePoints = true; } + this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES); +}; +_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.endTransformFeedback = function () { + this._gl.endTransformFeedback(); +}; +_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.setTranformFeedbackVaryings = function (program, value) { + this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS); +}; +_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.bindTransformFeedbackBuffer = function (value) { + this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value ? value.underlyingResource : null); +}; + + +/***/ }), + +/***/ "./Engines/Extensions/engine.webVR.ts": +/*!********************************************!*\ + !*** ./Engines/Extensions/engine.webVR.ts ***! + \********************************************/ +/*! no exports provided */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Engines/engine */ "./Engines/engine.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Misc/tools */ "./Misc/tools.ts"); +/* harmony import */ var _Misc_domManagement__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Misc/domManagement */ "./Misc/domManagement.ts"); + + + + + +Object.defineProperty(_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype, "isInVRExclusivePointerMode", { + get: function () { + return this._vrExclusivePointerMode; + }, + enumerable: true, + configurable: true +}); +_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype._prepareVRComponent = function () { + this._vrSupported = false; + this._vrExclusivePointerMode = false; + this.onVRDisplayChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); + this.onVRRequestPresentComplete = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); + this.onVRRequestPresentStart = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); +}; +_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.isVRDevicePresent = function () { + return !!this._vrDisplay; +}; +_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.getVRDevice = function () { + return this._vrDisplay; +}; +_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.initWebVR = function () { + this.initWebVRAsync(); + return this.onVRDisplayChangedObservable; +}; +_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.initWebVRAsync = function () { + var _this = this; + var notifyObservers = function () { + var eventArgs = { + vrDisplay: _this._vrDisplay, + vrSupported: _this._vrSupported + }; + _this.onVRDisplayChangedObservable.notifyObservers(eventArgs); + _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); }); + }; + if (!this._onVrDisplayConnect) { + this._onVrDisplayConnect = function (event) { + _this._vrDisplay = event.display; + notifyObservers(); + }; + this._onVrDisplayDisconnect = function () { + _this._vrDisplay.cancelAnimationFrame(_this._frameHandler); + _this._vrDisplay = undefined; + _this._frameHandler = _Misc_tools__WEBPACK_IMPORTED_MODULE_3__["Tools"].QueueNewFrame(_this._bindedRenderFunction); + notifyObservers(); + }; + this._onVrDisplayPresentChange = function () { + _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting; + }; + window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect); + window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect); + window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange); + } + this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync(); + this._webVRInitPromise.then(notifyObservers); + return this._webVRInitPromise; +}; +_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype._getVRDisplaysAsync = function () { + var _this = this; + return new Promise(function (res) { + if (navigator.getVRDisplays) { + navigator.getVRDisplays().then(function (devices) { + _this._vrSupported = true; + // note that devices may actually be an empty array. This is fine; + // we expect this._vrDisplay to be undefined in this case. + _this._vrDisplay = devices[0]; + res({ + vrDisplay: _this._vrDisplay, + vrSupported: _this._vrSupported + }); + }); + } + else { + _this._vrDisplay = undefined; + _this._vrSupported = false; + res({ + vrDisplay: _this._vrDisplay, + vrSupported: _this._vrSupported + }); + } + }); +}; +_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.enableVR = function () { + var _this = this; + if (this._vrDisplay && !this._vrDisplay.isPresenting) { + var onResolved = function () { + _this.onVRRequestPresentComplete.notifyObservers(true); + _this._onVRFullScreenTriggered(); + }; + var onRejected = function () { + _this.onVRRequestPresentComplete.notifyObservers(false); + }; + this.onVRRequestPresentStart.notifyObservers(this); + this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected); + } +}; +_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype._onVRFullScreenTriggered = function () { + if (this._vrDisplay && this._vrDisplay.isPresenting) { + //get the old size before we change + this._oldSize = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Size"](this.getRenderWidth(), this.getRenderHeight()); + this._oldHardwareScaleFactor = this.getHardwareScalingLevel(); + //get the width and height, change the render size + var leftEye = this._vrDisplay.getEyeParameters('left'); + this.setHardwareScalingLevel(1); + this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight); + } + else { + this.setHardwareScalingLevel(this._oldHardwareScaleFactor); + this.setSize(this._oldSize.width, this._oldSize.height); + } +}; +_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.disableVR = function () { + var _this = this; + if (this._vrDisplay && this._vrDisplay.isPresenting) { + this._vrDisplay.exitPresent() + .then(function () { return _this._onVRFullScreenTriggered(); }) + .catch(function () { return _this._onVRFullScreenTriggered(); }); + } + if (_Misc_domManagement__WEBPACK_IMPORTED_MODULE_4__["DomManagement"].IsWindowObjectExist()) { + window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted); + window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted); + if (this._onVrDisplayConnect) { + window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect); + if (this._onVrDisplayDisconnect) { + window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect); + } + if (this._onVrDisplayPresentChange) { + window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange); + } + this._onVrDisplayConnect = null; + this._onVrDisplayDisconnect = null; + } + } +}; +_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype._connectVREvents = function (canvas, document) { + this._onVRDisplayPointerRestricted = function () { + if (canvas) { + canvas.requestPointerLock(); + } + }; + this._onVRDisplayPointerUnrestricted = function () { + if (!document.exitPointerLock) { + return; + } + document.exitPointerLock(); + }; + if (_Misc_domManagement__WEBPACK_IMPORTED_MODULE_4__["DomManagement"].IsWindowObjectExist()) { + window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false); + window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false); + } +}; +_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype._submitVRFrame = function () { + // Submit frame to the vr device, if enabled + if (this._vrDisplay && this._vrDisplay.isPresenting) { + // TODO: We should only submit the frame if we read frameData successfully. + try { + this._vrDisplay.submitFrame(); + } + catch (e) { + _Misc_tools__WEBPACK_IMPORTED_MODULE_3__["Tools"].Warn("webVR submitFrame has had an unexpected failure: " + e); + } + } +}; +_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.isVRPresenting = function () { + return this._vrDisplay && this._vrDisplay.isPresenting; +}; +_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype._requestVRFrame = function () { + this._frameHandler = _Misc_tools__WEBPACK_IMPORTED_MODULE_3__["Tools"].QueueNewFrame(this._bindedRenderFunction, this._vrDisplay); +}; + + +/***/ }), + +/***/ "./Engines/Extensions/index.ts": +/*!*************************************!*\ + !*** ./Engines/Extensions/index.ts ***! + \*************************************/ +/*! exports provided: _OcclusionDataStorage, _forceTransformFeedbackToBundle */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _engine_occlusionQuery__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./engine.occlusionQuery */ "./Engines/Extensions/engine.occlusionQuery.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_OcclusionDataStorage", function() { return _engine_occlusionQuery__WEBPACK_IMPORTED_MODULE_0__["_OcclusionDataStorage"]; }); + +/* harmony import */ var _engine_transformFeedback__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./engine.transformFeedback */ "./Engines/Extensions/engine.transformFeedback.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_forceTransformFeedbackToBundle", function() { return _engine_transformFeedback__WEBPACK_IMPORTED_MODULE_1__["_forceTransformFeedbackToBundle"]; }); + + + + + +/***/ }), + +/***/ "./Engines/Native/nativeShaderProcessor.ts": +/*!*************************************************!*\ + !*** ./Engines/Native/nativeShaderProcessor.ts ***! + \*************************************************/ +/*! exports provided: NativeShaderProcessor */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NativeShaderProcessor", function() { return NativeShaderProcessor; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _WebGL_webGL2ShaderProcessors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../WebGL/webGL2ShaderProcessors */ "./Engines/WebGL/webGL2ShaderProcessors.ts"); +/* harmony import */ var _Meshes_buffer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Meshes/buffer */ "./Meshes/buffer.ts"); + +var _a; + + +// These must match the values for bgfx::Attrib::Enum +var attributeLocations = (_a = {}, + _a[_Meshes_buffer__WEBPACK_IMPORTED_MODULE_2__["VertexBuffer"].PositionKind] = 0, + _a[_Meshes_buffer__WEBPACK_IMPORTED_MODULE_2__["VertexBuffer"].NormalKind] = 1, + _a[_Meshes_buffer__WEBPACK_IMPORTED_MODULE_2__["VertexBuffer"].TangentKind] = 2, + _a[_Meshes_buffer__WEBPACK_IMPORTED_MODULE_2__["VertexBuffer"].UVKind] = 10, + _a[_Meshes_buffer__WEBPACK_IMPORTED_MODULE_2__["VertexBuffer"].UV2Kind] = 11, + _a[_Meshes_buffer__WEBPACK_IMPORTED_MODULE_2__["VertexBuffer"].ColorKind] = 4, + _a[_Meshes_buffer__WEBPACK_IMPORTED_MODULE_2__["VertexBuffer"].MatricesIndicesKind] = 8, + _a[_Meshes_buffer__WEBPACK_IMPORTED_MODULE_2__["VertexBuffer"].MatricesWeightsKind] = 9, + _a); +/** @hidden */ +var NativeShaderProcessor = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](NativeShaderProcessor, _super); + function NativeShaderProcessor() { + return _super !== null && _super.apply(this, arguments) || this; + } + NativeShaderProcessor.prototype.linePreProcessor = function (line) { + for (var _i = 0, _a = this._replacements; _i < _a.length; _i++) { + var replacement = _a[_i]; + line = line.replace(replacement.searchValue, replacement.replaceValue); + } + return line; + }; + NativeShaderProcessor.prototype.attributeProcessor = function (attribute) { + var match = attribute.match(/attribute\s+\w+\s+(\w+)\s*;/); + var name = match[1]; + var location = attributeLocations[name]; + if (location === undefined) { + throw new Error("Unsupported attribute " + name); + } + return "layout(location=" + location + ") " + _super.prototype.attributeProcessor.call(this, attribute); + }; + NativeShaderProcessor.prototype.varyingProcessor = function (varying, isFragment) { + var location; + if (isFragment) { + location = this._varyingLocationMap[varying]; + } + else { + location = this._varyingLocationCount++; + this._varyingLocationMap[varying] = location; + } + return "layout(location=" + location + ") " + _super.prototype.varyingProcessor.call(this, varying, isFragment); + }; + NativeShaderProcessor.prototype.uniformProcessor = function (uniform) { + var match = uniform.match(/uniform\s+(\w+)\s+(\w+)\s*;/); + var type = match[1]; + var name = match[2]; + switch (type) { + case "sampler2D": + case "samplerCube": { + var suffix = type.substr(7); + var binding = this._textureCount++; + this._replacements.push({ searchValue: new RegExp("\\b" + name + "\\b"), replaceValue: "sampler" + suffix + "(" + name + "Texture, " + name + ")" }); + return "layout(binding=" + binding + ") uniform texture" + suffix + " " + name + "Texture;\nlayout(binding=" + binding + ") uniform sampler " + name + ";"; + } + } + this._uniforms.push(uniform); + return this._uniforms.length === 1 ? "" : ""; + }; + NativeShaderProcessor.prototype.preProcessor = function (code, defines, isFragment) { + if (!isFragment) { + this._varyingLocationCount = 0; + this._varyingLocationMap = {}; + } + this._replacements = []; + this._textureCount = 0; + this._uniforms = []; + return code; + }; + NativeShaderProcessor.prototype.postProcessor = function (code, defines, isFragment) { + code = _super.prototype.postProcessor.call(this, code, defines, isFragment); + code = code.replace("", "uniform Frame {\n" + this._uniforms.join("\n") + "\n};"); + code = code.replace("out vec4 glFragColor", "layout(location=0) out vec4 glFragColor"); + return code; + }; + return NativeShaderProcessor; +}(_WebGL_webGL2ShaderProcessors__WEBPACK_IMPORTED_MODULE_1__["WebGL2ShaderProcessor"])); + + + +/***/ }), + +/***/ "./Engines/Processors/Expressions/Operators/shaderDefineAndOperator.ts": +/*!*****************************************************************************!*\ + !*** ./Engines/Processors/Expressions/Operators/shaderDefineAndOperator.ts ***! + \*****************************************************************************/ +/*! exports provided: ShaderDefineAndOperator */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ShaderDefineAndOperator", function() { return ShaderDefineAndOperator; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _shaderDefineExpression__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../shaderDefineExpression */ "./Engines/Processors/Expressions/shaderDefineExpression.ts"); + + +/** @hidden */ +var ShaderDefineAndOperator = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ShaderDefineAndOperator, _super); + function ShaderDefineAndOperator() { + return _super !== null && _super.apply(this, arguments) || this; + } + ShaderDefineAndOperator.prototype.isTrue = function (preprocessors) { + return this.leftOperand.isTrue(preprocessors) && this.rightOperand.isTrue(preprocessors); + }; + return ShaderDefineAndOperator; +}(_shaderDefineExpression__WEBPACK_IMPORTED_MODULE_1__["ShaderDefineExpression"])); + + + +/***/ }), + +/***/ "./Engines/Processors/Expressions/Operators/shaderDefineArithmeticOperator.ts": +/*!************************************************************************************!*\ + !*** ./Engines/Processors/Expressions/Operators/shaderDefineArithmeticOperator.ts ***! + \************************************************************************************/ +/*! exports provided: ShaderDefineArithmeticOperator */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ShaderDefineArithmeticOperator", function() { return ShaderDefineArithmeticOperator; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _shaderDefineExpression__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../shaderDefineExpression */ "./Engines/Processors/Expressions/shaderDefineExpression.ts"); + + +/** @hidden */ +var ShaderDefineArithmeticOperator = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ShaderDefineArithmeticOperator, _super); + function ShaderDefineArithmeticOperator(define, operand, testValue) { + var _this = _super.call(this) || this; + _this.define = define; + _this.operand = operand; + _this.testValue = testValue; + return _this; + } + ShaderDefineArithmeticOperator.prototype.isTrue = function (preprocessors) { + var value = preprocessors[this.define]; + if (value === undefined) { + return false; + } + var condition = false; + var left = parseInt(value); + var right = parseInt(this.testValue); + switch (this.operand) { + case ">": + condition = left > right; + break; + case "<": + condition = left < right; + break; + case "<=": + condition = left <= right; + break; + case ">=": + condition = left >= right; + break; + case "==": + condition = left === right; + break; + } + return condition; + }; + return ShaderDefineArithmeticOperator; +}(_shaderDefineExpression__WEBPACK_IMPORTED_MODULE_1__["ShaderDefineExpression"])); + + + +/***/ }), + +/***/ "./Engines/Processors/Expressions/Operators/shaderDefineIsDefinedOperator.ts": +/*!***********************************************************************************!*\ + !*** ./Engines/Processors/Expressions/Operators/shaderDefineIsDefinedOperator.ts ***! + \***********************************************************************************/ +/*! exports provided: ShaderDefineIsDefinedOperator */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ShaderDefineIsDefinedOperator", function() { return ShaderDefineIsDefinedOperator; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _shaderDefineExpression__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../shaderDefineExpression */ "./Engines/Processors/Expressions/shaderDefineExpression.ts"); + + +/** @hidden */ +var ShaderDefineIsDefinedOperator = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ShaderDefineIsDefinedOperator, _super); + function ShaderDefineIsDefinedOperator(define, not) { + if (not === void 0) { not = false; } + var _this = _super.call(this) || this; + _this.define = define; + _this.not = not; + return _this; + } + ShaderDefineIsDefinedOperator.prototype.isTrue = function (preprocessors) { + var condition = preprocessors[this.define] !== undefined; + if (this.not) { + condition = !condition; + } + return condition; + }; + return ShaderDefineIsDefinedOperator; +}(_shaderDefineExpression__WEBPACK_IMPORTED_MODULE_1__["ShaderDefineExpression"])); + + + +/***/ }), + +/***/ "./Engines/Processors/Expressions/Operators/shaderDefineOrOperator.ts": +/*!****************************************************************************!*\ + !*** ./Engines/Processors/Expressions/Operators/shaderDefineOrOperator.ts ***! + \****************************************************************************/ +/*! exports provided: ShaderDefineOrOperator */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ShaderDefineOrOperator", function() { return ShaderDefineOrOperator; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _shaderDefineExpression__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../shaderDefineExpression */ "./Engines/Processors/Expressions/shaderDefineExpression.ts"); + + +/** @hidden */ +var ShaderDefineOrOperator = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ShaderDefineOrOperator, _super); + function ShaderDefineOrOperator() { + return _super !== null && _super.apply(this, arguments) || this; + } + ShaderDefineOrOperator.prototype.isTrue = function (preprocessors) { + return this.leftOperand.isTrue(preprocessors) || this.rightOperand.isTrue(preprocessors); + }; + return ShaderDefineOrOperator; +}(_shaderDefineExpression__WEBPACK_IMPORTED_MODULE_1__["ShaderDefineExpression"])); + + + +/***/ }), + +/***/ "./Engines/Processors/Expressions/shaderDefineExpression.ts": +/*!******************************************************************!*\ + !*** ./Engines/Processors/Expressions/shaderDefineExpression.ts ***! + \******************************************************************/ +/*! exports provided: ShaderDefineExpression */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ShaderDefineExpression", function() { return ShaderDefineExpression; }); +/** @hidden */ +var ShaderDefineExpression = /** @class */ (function () { + function ShaderDefineExpression() { + } + ShaderDefineExpression.prototype.isTrue = function (preprocessors) { + return true; + }; + return ShaderDefineExpression; +}()); + + + +/***/ }), + +/***/ "./Engines/Processors/shaderCodeConditionNode.ts": +/*!*******************************************************!*\ + !*** ./Engines/Processors/shaderCodeConditionNode.ts ***! + \*******************************************************/ +/*! exports provided: ShaderCodeConditionNode */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ShaderCodeConditionNode", function() { return ShaderCodeConditionNode; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _shaderCodeNode__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./shaderCodeNode */ "./Engines/Processors/shaderCodeNode.ts"); + + +/** @hidden */ +var ShaderCodeConditionNode = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ShaderCodeConditionNode, _super); + function ShaderCodeConditionNode() { + return _super !== null && _super.apply(this, arguments) || this; + } + ShaderCodeConditionNode.prototype.process = function (preprocessors, options) { + for (var index = 0; index < this.children.length; index++) { + var node = this.children[index]; + if (node.isValid(preprocessors)) { + return node.process(preprocessors, options); + } + } + return ""; + }; + return ShaderCodeConditionNode; +}(_shaderCodeNode__WEBPACK_IMPORTED_MODULE_1__["ShaderCodeNode"])); + + + +/***/ }), + +/***/ "./Engines/Processors/shaderCodeCursor.ts": +/*!************************************************!*\ + !*** ./Engines/Processors/shaderCodeCursor.ts ***! + \************************************************/ +/*! exports provided: ShaderCodeCursor */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ShaderCodeCursor", function() { return ShaderCodeCursor; }); +/** @hidden */ +var ShaderCodeCursor = /** @class */ (function () { + function ShaderCodeCursor() { + } + Object.defineProperty(ShaderCodeCursor.prototype, "currentLine", { + get: function () { + return this._lines[this.lineIndex]; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ShaderCodeCursor.prototype, "canRead", { + get: function () { + return this.lineIndex < this._lines.length - 1; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ShaderCodeCursor.prototype, "lines", { + set: function (value) { + this._lines = []; + for (var _i = 0, value_1 = value; _i < value_1.length; _i++) { + var line = value_1[_i]; + var split = line.split(";"); + for (var index = 0; index < split.length; index++) { + var subLine = split[index]; + subLine = subLine.trim(); + if (!subLine) { + continue; + } + this._lines.push(subLine + (index !== split.length - 1 ? ";" : "")); + } + } + }, + enumerable: true, + configurable: true + }); + return ShaderCodeCursor; +}()); + + + +/***/ }), + +/***/ "./Engines/Processors/shaderCodeNode.ts": +/*!**********************************************!*\ + !*** ./Engines/Processors/shaderCodeNode.ts ***! + \**********************************************/ +/*! exports provided: ShaderCodeNode */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ShaderCodeNode", function() { return ShaderCodeNode; }); +/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Misc/tools */ "./Misc/tools.ts"); + +/** @hidden */ +var ShaderCodeNode = /** @class */ (function () { + function ShaderCodeNode() { + this.children = []; + } + ShaderCodeNode.prototype.isValid = function (preprocessors) { + return true; + }; + ShaderCodeNode.prototype.process = function (preprocessors, options) { + var result = ""; + if (this.line) { + var value = this.line; + var processor = options.processor; + if (processor) { + if (processor.linePreProcessor) { + value = processor.linePreProcessor(value, options.isFragment); + } + if (processor.attributeProcessor && _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].StartsWith(this.line, "attribute")) { + value = processor.attributeProcessor(this.line); + } + else if (processor.varyingProcessor && _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].StartsWith(this.line, "varying")) { + value = processor.varyingProcessor(this.line, options.isFragment); + } + else if ((processor.uniformProcessor || processor.uniformBufferProcessor) && _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].StartsWith(this.line, "uniform")) { + var regex = /uniform (.+) (.+)/; + if (regex.test(this.line)) { // uniform + if (processor.uniformProcessor) { + value = processor.uniformProcessor(this.line, options.isFragment); + } + } + else { // Uniform buffer + if (processor.uniformBufferProcessor) { + value = processor.uniformBufferProcessor(this.line, options.isFragment); + options.lookForClosingBracketForUniformBuffer = true; + } + } + } + if (processor.endOfUniformBufferProcessor) { + if (options.lookForClosingBracketForUniformBuffer && this.line.indexOf("}") !== -1) { + options.lookForClosingBracketForUniformBuffer = false; + value = processor.endOfUniformBufferProcessor(this.line, options.isFragment); + } + } + } + result += value + "\r\n"; + } + this.children.forEach(function (child) { + result += child.process(preprocessors, options); + }); + if (this.additionalDefineKey) { + preprocessors[this.additionalDefineKey] = this.additionalDefineValue || "true"; + } + return result; + }; + return ShaderCodeNode; +}()); + + + +/***/ }), + +/***/ "./Engines/Processors/shaderCodeTestNode.ts": +/*!**************************************************!*\ + !*** ./Engines/Processors/shaderCodeTestNode.ts ***! + \**************************************************/ +/*! exports provided: ShaderCodeTestNode */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ShaderCodeTestNode", function() { return ShaderCodeTestNode; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _shaderCodeNode__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./shaderCodeNode */ "./Engines/Processors/shaderCodeNode.ts"); + + +/** @hidden */ +var ShaderCodeTestNode = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ShaderCodeTestNode, _super); + function ShaderCodeTestNode() { + return _super !== null && _super.apply(this, arguments) || this; + } + ShaderCodeTestNode.prototype.isValid = function (preprocessors) { + return this.testExpression.isTrue(preprocessors); + }; + return ShaderCodeTestNode; +}(_shaderCodeNode__WEBPACK_IMPORTED_MODULE_1__["ShaderCodeNode"])); + + + +/***/ }), + +/***/ "./Engines/Processors/shaderProcessor.ts": +/*!***********************************************!*\ + !*** ./Engines/Processors/shaderProcessor.ts ***! + \***********************************************/ +/*! exports provided: ShaderProcessor */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ShaderProcessor", function() { return ShaderProcessor; }); +/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Misc/tools */ "./Misc/tools.ts"); +/* harmony import */ var _shaderCodeNode__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./shaderCodeNode */ "./Engines/Processors/shaderCodeNode.ts"); +/* harmony import */ var _shaderCodeCursor__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./shaderCodeCursor */ "./Engines/Processors/shaderCodeCursor.ts"); +/* harmony import */ var _shaderCodeConditionNode__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./shaderCodeConditionNode */ "./Engines/Processors/shaderCodeConditionNode.ts"); +/* harmony import */ var _shaderCodeTestNode__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./shaderCodeTestNode */ "./Engines/Processors/shaderCodeTestNode.ts"); +/* harmony import */ var _Expressions_Operators_shaderDefineIsDefinedOperator__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Expressions/Operators/shaderDefineIsDefinedOperator */ "./Engines/Processors/Expressions/Operators/shaderDefineIsDefinedOperator.ts"); +/* harmony import */ var _Expressions_Operators_shaderDefineOrOperator__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Expressions/Operators/shaderDefineOrOperator */ "./Engines/Processors/Expressions/Operators/shaderDefineOrOperator.ts"); +/* harmony import */ var _Expressions_Operators_shaderDefineAndOperator__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Expressions/Operators/shaderDefineAndOperator */ "./Engines/Processors/Expressions/Operators/shaderDefineAndOperator.ts"); +/* harmony import */ var _Expressions_Operators_shaderDefineArithmeticOperator__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./Expressions/Operators/shaderDefineArithmeticOperator */ "./Engines/Processors/Expressions/Operators/shaderDefineArithmeticOperator.ts"); + + + + + + + + + +/** @hidden */ +var ShaderProcessor = /** @class */ (function () { + function ShaderProcessor() { + } + ShaderProcessor.Process = function (sourceCode, options, callback) { + var _this = this; + this._ProcessIncludes(sourceCode, options, function (codeWithIncludes) { + var migratedCode = _this._ProcessShaderConversion(codeWithIncludes, options); + callback(migratedCode); + }); + }; + ShaderProcessor._ProcessPrecision = function (source, options) { + var shouldUseHighPrecisionShader = options.shouldUseHighPrecisionShader; + if (source.indexOf("precision highp float") === -1) { + if (!shouldUseHighPrecisionShader) { + source = "precision mediump float;\n" + source; + } + else { + source = "precision highp float;\n" + source; + } + } + else { + if (!shouldUseHighPrecisionShader) { // Moving highp to mediump + source = source.replace("precision highp float", "precision mediump float"); + } + } + return source; + }; + ShaderProcessor._ExtractOperation = function (expression) { + var regex = /defined\((.+)\)/; + var match = regex.exec(expression); + if (match && match.length) { + return new _Expressions_Operators_shaderDefineIsDefinedOperator__WEBPACK_IMPORTED_MODULE_5__["ShaderDefineIsDefinedOperator"](match[1].trim(), expression[0] === "!"); + } + var operators = ["==", ">=", "<=", "<", ">"]; + var operator = ""; + var indexOperator = 0; + for (var _i = 0, operators_1 = operators; _i < operators_1.length; _i++) { + operator = operators_1[_i]; + indexOperator = expression.indexOf(operator); + if (indexOperator > -1) { + break; + } + } + if (indexOperator === -1) { + return new _Expressions_Operators_shaderDefineIsDefinedOperator__WEBPACK_IMPORTED_MODULE_5__["ShaderDefineIsDefinedOperator"](expression); + } + var define = expression.substring(0, indexOperator).trim(); + var value = expression.substring(indexOperator + operator.length).trim(); + return new _Expressions_Operators_shaderDefineArithmeticOperator__WEBPACK_IMPORTED_MODULE_8__["ShaderDefineArithmeticOperator"](define, operator, value); + }; + ShaderProcessor._BuildSubExpression = function (expression) { + var indexOr = expression.indexOf("||"); + if (indexOr === -1) { + var indexAnd = expression.indexOf("&&"); + if (indexAnd > -1) { + var andOperator = new _Expressions_Operators_shaderDefineAndOperator__WEBPACK_IMPORTED_MODULE_7__["ShaderDefineAndOperator"](); + var leftPart = expression.substring(0, indexAnd).trim(); + var rightPart = expression.substring(indexAnd + 2).trim(); + andOperator.leftOperand = this._BuildSubExpression(leftPart); + andOperator.rightOperand = this._BuildSubExpression(rightPart); + return andOperator; + } + else { + return this._ExtractOperation(expression); + } + } + else { + var orOperator = new _Expressions_Operators_shaderDefineOrOperator__WEBPACK_IMPORTED_MODULE_6__["ShaderDefineOrOperator"](); + var leftPart = expression.substring(0, indexOr).trim(); + var rightPart = expression.substring(indexOr + 2).trim(); + orOperator.leftOperand = this._BuildSubExpression(leftPart); + orOperator.rightOperand = this._BuildSubExpression(rightPart); + return orOperator; + } + }; + ShaderProcessor._BuildExpression = function (line, start) { + var node = new _shaderCodeTestNode__WEBPACK_IMPORTED_MODULE_4__["ShaderCodeTestNode"](); + var command = line.substring(0, start); + var expression = line.substring(start).trim(); + if (command === "#ifdef") { + node.testExpression = new _Expressions_Operators_shaderDefineIsDefinedOperator__WEBPACK_IMPORTED_MODULE_5__["ShaderDefineIsDefinedOperator"](expression); + } + else if (command === "#ifndef") { + node.testExpression = new _Expressions_Operators_shaderDefineIsDefinedOperator__WEBPACK_IMPORTED_MODULE_5__["ShaderDefineIsDefinedOperator"](expression, true); + } + else { + node.testExpression = this._BuildSubExpression(expression); + } + return node; + }; + ShaderProcessor._MoveCursorWithinIf = function (cursor, rootNode, ifNode) { + var line = cursor.currentLine; + while (this._MoveCursor(cursor, ifNode)) { + line = cursor.currentLine; + var first5 = line.substring(0, 5).toLowerCase(); + if (first5 === "#else") { + var elseNode = new _shaderCodeNode__WEBPACK_IMPORTED_MODULE_1__["ShaderCodeNode"](); + rootNode.children.push(elseNode); + this._MoveCursor(cursor, elseNode); + return; + } + else if (first5 === "#elif") { + var elifNode = this._BuildExpression(line, 5); + rootNode.children.push(elifNode); + ifNode = elifNode; + } + } + }; + ShaderProcessor._MoveCursor = function (cursor, rootNode) { + while (cursor.canRead) { + cursor.lineIndex++; + var line = cursor.currentLine; + var keywords = /(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/; + var matches = keywords.exec(line); + if (matches && matches.length) { + var keyword = matches[0]; + switch (keyword) { + case "#ifdef": { + var newRootNode = new _shaderCodeConditionNode__WEBPACK_IMPORTED_MODULE_3__["ShaderCodeConditionNode"](); + rootNode.children.push(newRootNode); + var ifNode = this._BuildExpression(line, 6); + newRootNode.children.push(ifNode); + this._MoveCursorWithinIf(cursor, newRootNode, ifNode); + break; + } + case "#else": + case "#elif": + return true; + case "#endif": + return false; + case "#ifndef": { + var newRootNode = new _shaderCodeConditionNode__WEBPACK_IMPORTED_MODULE_3__["ShaderCodeConditionNode"](); + rootNode.children.push(newRootNode); + var ifNode = this._BuildExpression(line, 7); + newRootNode.children.push(ifNode); + this._MoveCursorWithinIf(cursor, newRootNode, ifNode); + break; + } + case "#if": { + var newRootNode = new _shaderCodeConditionNode__WEBPACK_IMPORTED_MODULE_3__["ShaderCodeConditionNode"](); + var ifNode = this._BuildExpression(line, 3); + rootNode.children.push(newRootNode); + newRootNode.children.push(ifNode); + this._MoveCursorWithinIf(cursor, newRootNode, ifNode); + break; + } + } + } + else { + var newNode = new _shaderCodeNode__WEBPACK_IMPORTED_MODULE_1__["ShaderCodeNode"](); + newNode.line = line; + rootNode.children.push(newNode); + // Detect additional defines + if (line[0] === "#" && line[1] === "d") { + var split = line.replace(";", "").split(" "); + newNode.additionalDefineKey = split[1]; + if (split.length === 3) { + newNode.additionalDefineValue = split[2]; + } + } + } + } + return false; + }; + ShaderProcessor._EvaluatePreProcessors = function (sourceCode, preprocessors, options) { + var rootNode = new _shaderCodeNode__WEBPACK_IMPORTED_MODULE_1__["ShaderCodeNode"](); + var cursor = new _shaderCodeCursor__WEBPACK_IMPORTED_MODULE_2__["ShaderCodeCursor"](); + cursor.lineIndex = -1; + cursor.lines = sourceCode.split("\n"); + // Decompose (We keep it in 2 steps so it is easier to maintain and perf hit is insignificant) + this._MoveCursor(cursor, rootNode); + // Recompose + return rootNode.process(preprocessors, options); + }; + ShaderProcessor._PreparePreProcessors = function (options) { + var defines = options.defines; + var preprocessors = {}; + for (var _i = 0, defines_1 = defines; _i < defines_1.length; _i++) { + var define = defines_1[_i]; + var keyValue = define.replace("#define", "").replace(";", "").trim(); + var split = keyValue.split(" "); + preprocessors[split[0]] = split.length > 1 ? split[1] : ""; + } + preprocessors["GL_ES"] = "true"; + preprocessors["__VERSION__"] = options.version; + preprocessors[options.platformName] = "true"; + return preprocessors; + }; + ShaderProcessor._ProcessShaderConversion = function (sourceCode, options) { + var preparedSourceCode = this._ProcessPrecision(sourceCode, options); + if (!options.processor) { + return preparedSourceCode; + } + // Already converted + if (preparedSourceCode.indexOf("#version 3") !== -1) { + return preparedSourceCode.replace("#version 300 es", ""); + } + var defines = options.defines; + var preprocessors = this._PreparePreProcessors(options); + // General pre processing + if (options.processor.preProcessor) { + preparedSourceCode = options.processor.preProcessor(preparedSourceCode, defines, options.isFragment); + } + preparedSourceCode = this._EvaluatePreProcessors(preparedSourceCode, preprocessors, options); + // Post processing + if (options.processor.postProcessor) { + preparedSourceCode = options.processor.postProcessor(preparedSourceCode, defines, options.isFragment); + } + return preparedSourceCode; + }; + ShaderProcessor._ProcessIncludes = function (sourceCode, options, callback) { + var _this = this; + var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g; + var match = regex.exec(sourceCode); + var returnValue = new String(sourceCode); + while (match != null) { + var includeFile = match[1]; + // Uniform declaration + if (includeFile.indexOf("__decl__") !== -1) { + includeFile = includeFile.replace(/__decl__/, ""); + if (options.supportsUniformBuffers) { + includeFile = includeFile.replace(/Vertex/, "Ubo"); + includeFile = includeFile.replace(/Fragment/, "Ubo"); + } + includeFile = includeFile + "Declaration"; + } + if (options.includesShadersStore[includeFile]) { + // Substitution + var includeContent = options.includesShadersStore[includeFile]; + if (match[2]) { + var splits = match[3].split(","); + for (var index = 0; index < splits.length; index += 2) { + var source = new RegExp(splits[index], "g"); + var dest = splits[index + 1]; + includeContent = includeContent.replace(source, dest); + } + } + if (match[4]) { + var indexString = match[5]; + if (indexString.indexOf("..") !== -1) { + var indexSplits = indexString.split(".."); + var minIndex = parseInt(indexSplits[0]); + var maxIndex = parseInt(indexSplits[1]); + var sourceIncludeContent = includeContent.slice(0); + includeContent = ""; + if (isNaN(maxIndex)) { + maxIndex = options.indexParameters[indexSplits[1]]; + } + for (var i = minIndex; i < maxIndex; i++) { + if (!options.supportsUniformBuffers) { + // Ubo replacement + sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) { + return p1 + "{X}"; + }); + } + includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n"; + } + } + else { + if (!options.supportsUniformBuffers) { + // Ubo replacement + includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) { + return p1 + "{X}"; + }); + } + includeContent = includeContent.replace(/\{X\}/g, indexString); + } + } + // Replace + returnValue = returnValue.replace(match[0], includeContent); + } + else { + var includeShaderUrl = options.shadersRepository + "ShadersInclude/" + includeFile + ".fx"; + _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].LoadFile(includeShaderUrl, function (fileContent) { + options.includesShadersStore[includeFile] = fileContent; + _this._ProcessIncludes(returnValue, options, callback); + }); + return; + } + match = regex.exec(sourceCode); + } + callback(returnValue); + }; + return ShaderProcessor; +}()); + + + +/***/ }), + +/***/ "./Engines/WebGL/webGL2ShaderProcessors.ts": +/*!*************************************************!*\ + !*** ./Engines/WebGL/webGL2ShaderProcessors.ts ***! + \*************************************************/ +/*! exports provided: WebGL2ShaderProcessor */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WebGL2ShaderProcessor", function() { return WebGL2ShaderProcessor; }); +/** @hidden */ +var WebGL2ShaderProcessor = /** @class */ (function () { + function WebGL2ShaderProcessor() { + } + WebGL2ShaderProcessor.prototype.attributeProcessor = function (attribute) { + return attribute.replace("attribute", "in"); + }; + WebGL2ShaderProcessor.prototype.varyingProcessor = function (varying, isFragment) { + return varying.replace("varying", isFragment ? "in" : "out"); + }; + WebGL2ShaderProcessor.prototype.postProcessor = function (code, defines, isFragment) { + var hasDrawBuffersExtension = code.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1; + // Remove extensions + var regex = /#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g; + code = code.replace(regex, ""); + // Replace instructions + code = code.replace(/texture2D\s*\(/g, "texture("); + if (isFragment) { + code = code.replace(/texture2DLodEXT\s*\(/g, "textureLod("); + code = code.replace(/textureCubeLodEXT\s*\(/g, "textureLod("); + code = code.replace(/textureCube\s*\(/g, "texture("); + code = code.replace(/gl_FragDepthEXT/g, "gl_FragDepth"); + code = code.replace(/gl_FragColor/g, "glFragColor"); + code = code.replace(/gl_FragData/g, "glFragData"); + code = code.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main("); + } + else { + var hasMultiviewExtension = defines.indexOf("#define MULTIVIEW") !== -1; + if (hasMultiviewExtension) { + return "#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n" + code; + } + } + return code; + }; + return WebGL2ShaderProcessor; +}()); + + + +/***/ }), + +/***/ "./Engines/WebGL/webGLPipelineContext.ts": +/*!***********************************************!*\ + !*** ./Engines/WebGL/webGLPipelineContext.ts ***! + \***********************************************/ +/*! exports provided: WebGLPipelineContext */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WebGLPipelineContext", function() { return WebGLPipelineContext; }); +/** @hidden */ +var WebGLPipelineContext = /** @class */ (function () { + function WebGLPipelineContext() { + } + Object.defineProperty(WebGLPipelineContext.prototype, "isAsync", { + get: function () { + return this.isParallelCompiled; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(WebGLPipelineContext.prototype, "isReady", { + get: function () { + if (this.program) { + if (this.isParallelCompiled) { + return this.engine._isRenderingStateCompiled(this); + } + return true; + } + return false; + }, + enumerable: true, + configurable: true + }); + WebGLPipelineContext.prototype._handlesSpectorRebuildCallback = function (onCompiled) { + if (onCompiled && this.program) { + onCompiled(this.program); + } + }; + return WebGLPipelineContext; +}()); + + + +/***/ }), + +/***/ "./Engines/constants.ts": +/*!******************************!*\ + !*** ./Engines/constants.ts ***! + \******************************/ +/*! exports provided: Constants */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Constants", function() { return Constants; }); +/** Defines the cross module used constants to avoid circular dependncies */ +var Constants = /** @class */ (function () { + function Constants() { + } + /** Defines that alpha blending is disabled */ + Constants.ALPHA_DISABLE = 0; + /** Defines that alpha blending to SRC ALPHA * SRC + DEST */ + Constants.ALPHA_ADD = 1; + /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */ + Constants.ALPHA_COMBINE = 2; + /** Defines that alpha blending to DEST - SRC * DEST */ + Constants.ALPHA_SUBTRACT = 3; + /** Defines that alpha blending to SRC * DEST */ + Constants.ALPHA_MULTIPLY = 4; + /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */ + Constants.ALPHA_MAXIMIZED = 5; + /** Defines that alpha blending to SRC + DEST */ + Constants.ALPHA_ONEONE = 6; + /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */ + Constants.ALPHA_PREMULTIPLIED = 7; + /** + * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST + * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA + */ + Constants.ALPHA_PREMULTIPLIED_PORTERDUFF = 8; + /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */ + Constants.ALPHA_INTERPOLATE = 9; + /** + * Defines that alpha blending to SRC + (1 - SRC) * DEST + * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA + */ + Constants.ALPHA_SCREENMODE = 10; + /** Defines that the ressource is not delayed*/ + Constants.DELAYLOADSTATE_NONE = 0; + /** Defines that the ressource was successfully delay loaded */ + Constants.DELAYLOADSTATE_LOADED = 1; + /** Defines that the ressource is currently delay loading */ + Constants.DELAYLOADSTATE_LOADING = 2; + /** Defines that the ressource is delayed and has not started loading */ + Constants.DELAYLOADSTATE_NOTLOADED = 4; + // Depht or Stencil test Constants. + /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */ + Constants.NEVER = 0x0200; + /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn */ + Constants.ALWAYS = 0x0207; + /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */ + Constants.LESS = 0x0201; + /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */ + Constants.EQUAL = 0x0202; + /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value */ + Constants.LEQUAL = 0x0203; + /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */ + Constants.GREATER = 0x0204; + /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value */ + Constants.GEQUAL = 0x0206; + /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value */ + Constants.NOTEQUAL = 0x0205; + // Stencil Actions Constants. + /** Passed to stencilOperation to specify that stencil value must be kept */ + Constants.KEEP = 0x1E00; + /** Passed to stencilOperation to specify that stencil value must be replaced */ + Constants.REPLACE = 0x1E01; + /** Passed to stencilOperation to specify that stencil value must be incremented */ + Constants.INCR = 0x1E02; + /** Passed to stencilOperation to specify that stencil value must be decremented */ + Constants.DECR = 0x1E03; + /** Passed to stencilOperation to specify that stencil value must be inverted */ + Constants.INVERT = 0x150A; + /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */ + Constants.INCR_WRAP = 0x8507; + /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */ + Constants.DECR_WRAP = 0x8508; + /** Texture is not repeating outside of 0..1 UVs */ + Constants.TEXTURE_CLAMP_ADDRESSMODE = 0; + /** Texture is repeating outside of 0..1 UVs */ + Constants.TEXTURE_WRAP_ADDRESSMODE = 1; + /** Texture is repeating and mirrored */ + Constants.TEXTURE_MIRROR_ADDRESSMODE = 2; + /** ALPHA */ + Constants.TEXTUREFORMAT_ALPHA = 0; + /** LUMINANCE */ + Constants.TEXTUREFORMAT_LUMINANCE = 1; + /** LUMINANCE_ALPHA */ + Constants.TEXTUREFORMAT_LUMINANCE_ALPHA = 2; + /** RGB */ + Constants.TEXTUREFORMAT_RGB = 4; + /** RGBA */ + Constants.TEXTUREFORMAT_RGBA = 5; + /** RED */ + Constants.TEXTUREFORMAT_RED = 6; + /** RED (2nd reference) */ + Constants.TEXTUREFORMAT_R = 6; + /** RG */ + Constants.TEXTUREFORMAT_RG = 7; + /** RED_INTEGER */ + Constants.TEXTUREFORMAT_RED_INTEGER = 8; + /** RED_INTEGER (2nd reference) */ + Constants.TEXTUREFORMAT_R_INTEGER = 8; + /** RG_INTEGER */ + Constants.TEXTUREFORMAT_RG_INTEGER = 9; + /** RGB_INTEGER */ + Constants.TEXTUREFORMAT_RGB_INTEGER = 10; + /** RGBA_INTEGER */ + Constants.TEXTUREFORMAT_RGBA_INTEGER = 11; + /** UNSIGNED_BYTE */ + Constants.TEXTURETYPE_UNSIGNED_BYTE = 0; + /** UNSIGNED_BYTE (2nd reference) */ + Constants.TEXTURETYPE_UNSIGNED_INT = 0; + /** FLOAT */ + Constants.TEXTURETYPE_FLOAT = 1; + /** HALF_FLOAT */ + Constants.TEXTURETYPE_HALF_FLOAT = 2; + /** BYTE */ + Constants.TEXTURETYPE_BYTE = 3; + /** SHORT */ + Constants.TEXTURETYPE_SHORT = 4; + /** UNSIGNED_SHORT */ + Constants.TEXTURETYPE_UNSIGNED_SHORT = 5; + /** INT */ + Constants.TEXTURETYPE_INT = 6; + /** UNSIGNED_INT */ + Constants.TEXTURETYPE_UNSIGNED_INTEGER = 7; + /** UNSIGNED_SHORT_4_4_4_4 */ + Constants.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8; + /** UNSIGNED_SHORT_5_5_5_1 */ + Constants.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9; + /** UNSIGNED_SHORT_5_6_5 */ + Constants.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10; + /** UNSIGNED_INT_2_10_10_10_REV */ + Constants.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11; + /** UNSIGNED_INT_24_8 */ + Constants.TEXTURETYPE_UNSIGNED_INT_24_8 = 12; + /** UNSIGNED_INT_10F_11F_11F_REV */ + Constants.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13; + /** UNSIGNED_INT_5_9_9_9_REV */ + Constants.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14; + /** FLOAT_32_UNSIGNED_INT_24_8_REV */ + Constants.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15; + /** nearest is mag = nearest and min = nearest and mip = linear */ + Constants.TEXTURE_NEAREST_SAMPLINGMODE = 1; + /** Bilinear is mag = linear and min = linear and mip = nearest */ + Constants.TEXTURE_BILINEAR_SAMPLINGMODE = 2; + /** Trilinear is mag = linear and min = linear and mip = linear */ + Constants.TEXTURE_TRILINEAR_SAMPLINGMODE = 3; + /** nearest is mag = nearest and min = nearest and mip = linear */ + Constants.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1; + /** Bilinear is mag = linear and min = linear and mip = nearest */ + Constants.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2; + /** Trilinear is mag = linear and min = linear and mip = linear */ + Constants.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3; + /** mag = nearest and min = nearest and mip = nearest */ + Constants.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4; + /** mag = nearest and min = linear and mip = nearest */ + Constants.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5; + /** mag = nearest and min = linear and mip = linear */ + Constants.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6; + /** mag = nearest and min = linear and mip = none */ + Constants.TEXTURE_NEAREST_LINEAR = 7; + /** mag = nearest and min = nearest and mip = none */ + Constants.TEXTURE_NEAREST_NEAREST = 8; + /** mag = linear and min = nearest and mip = nearest */ + Constants.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9; + /** mag = linear and min = nearest and mip = linear */ + Constants.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10; + /** mag = linear and min = linear and mip = none */ + Constants.TEXTURE_LINEAR_LINEAR = 11; + /** mag = linear and min = nearest and mip = none */ + Constants.TEXTURE_LINEAR_NEAREST = 12; + /** Explicit coordinates mode */ + Constants.TEXTURE_EXPLICIT_MODE = 0; + /** Spherical coordinates mode */ + Constants.TEXTURE_SPHERICAL_MODE = 1; + /** Planar coordinates mode */ + Constants.TEXTURE_PLANAR_MODE = 2; + /** Cubic coordinates mode */ + Constants.TEXTURE_CUBIC_MODE = 3; + /** Projection coordinates mode */ + Constants.TEXTURE_PROJECTION_MODE = 4; + /** Skybox coordinates mode */ + Constants.TEXTURE_SKYBOX_MODE = 5; + /** Inverse Cubic coordinates mode */ + Constants.TEXTURE_INVCUBIC_MODE = 6; + /** Equirectangular coordinates mode */ + Constants.TEXTURE_EQUIRECTANGULAR_MODE = 7; + /** Equirectangular Fixed coordinates mode */ + Constants.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8; + /** Equirectangular Fixed Mirrored coordinates mode */ + Constants.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9; + // Texture rescaling mode + /** Defines that texture rescaling will use a floor to find the closer power of 2 size */ + Constants.SCALEMODE_FLOOR = 1; + /** Defines that texture rescaling will look for the nearest power of 2 size */ + Constants.SCALEMODE_NEAREST = 2; + /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */ + Constants.SCALEMODE_CEILING = 3; + /** + * The dirty texture flag value + */ + Constants.MATERIAL_TextureDirtyFlag = 1; + /** + * The dirty light flag value + */ + Constants.MATERIAL_LightDirtyFlag = 2; + /** + * The dirty fresnel flag value + */ + Constants.MATERIAL_FresnelDirtyFlag = 4; + /** + * The dirty attribute flag value + */ + Constants.MATERIAL_AttributesDirtyFlag = 8; + /** + * The dirty misc flag value + */ + Constants.MATERIAL_MiscDirtyFlag = 16; + /** + * The all dirty flag value + */ + Constants.MATERIAL_AllDirtyFlag = 31; + /** + * Returns the triangle fill mode + */ + Constants.MATERIAL_TriangleFillMode = 0; + /** + * Returns the wireframe mode + */ + Constants.MATERIAL_WireFrameFillMode = 1; + /** + * Returns the point fill mode + */ + Constants.MATERIAL_PointFillMode = 2; + /** + * Returns the point list draw mode + */ + Constants.MATERIAL_PointListDrawMode = 3; + /** + * Returns the line list draw mode + */ + Constants.MATERIAL_LineListDrawMode = 4; + /** + * Returns the line loop draw mode + */ + Constants.MATERIAL_LineLoopDrawMode = 5; + /** + * Returns the line strip draw mode + */ + Constants.MATERIAL_LineStripDrawMode = 6; + /** + * Returns the triangle strip draw mode + */ + Constants.MATERIAL_TriangleStripDrawMode = 7; + /** + * Returns the triangle fan draw mode + */ + Constants.MATERIAL_TriangleFanDrawMode = 8; + /** + * Stores the clock-wise side orientation + */ + Constants.MATERIAL_ClockWiseSideOrientation = 0; + /** + * Stores the counter clock-wise side orientation + */ + Constants.MATERIAL_CounterClockWiseSideOrientation = 1; + /** + * Nothing + * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers + */ + Constants.ACTION_NothingTrigger = 0; + /** + * On pick + * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers + */ + Constants.ACTION_OnPickTrigger = 1; + /** + * On left pick + * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers + */ + Constants.ACTION_OnLeftPickTrigger = 2; + /** + * On right pick + * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers + */ + Constants.ACTION_OnRightPickTrigger = 3; + /** + * On center pick + * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers + */ + Constants.ACTION_OnCenterPickTrigger = 4; + /** + * On pick down + * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers + */ + Constants.ACTION_OnPickDownTrigger = 5; + /** + * On double pick + * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers + */ + Constants.ACTION_OnDoublePickTrigger = 6; + /** + * On pick up + * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers + */ + Constants.ACTION_OnPickUpTrigger = 7; + /** + * On pick out. + * This trigger will only be raised if you also declared a OnPickDown + * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers + */ + Constants.ACTION_OnPickOutTrigger = 16; + /** + * On long press + * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers + */ + Constants.ACTION_OnLongPressTrigger = 8; + /** + * On pointer over + * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers + */ + Constants.ACTION_OnPointerOverTrigger = 9; + /** + * On pointer out + * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers + */ + Constants.ACTION_OnPointerOutTrigger = 10; + /** + * On every frame + * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers + */ + Constants.ACTION_OnEveryFrameTrigger = 11; + /** + * On intersection enter + * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers + */ + Constants.ACTION_OnIntersectionEnterTrigger = 12; + /** + * On intersection exit + * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers + */ + Constants.ACTION_OnIntersectionExitTrigger = 13; + /** + * On key down + * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers + */ + Constants.ACTION_OnKeyDownTrigger = 14; + /** + * On key up + * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers + */ + Constants.ACTION_OnKeyUpTrigger = 15; + /** + * Billboard mode will only apply to Y axis + */ + Constants.PARTICLES_BILLBOARDMODE_Y = 2; + /** + * Billboard mode will apply to all axes + */ + Constants.PARTICLES_BILLBOARDMODE_ALL = 7; + /** + * Special billboard mode where the particle will be biilboard to the camera but rotated to align with direction + */ + Constants.PARTICLES_BILLBOARDMODE_STRETCHED = 8; + /** + * Gets or sets base Assets URL + */ + Constants.PARTICLES_BaseAssetsUrl = "https://assets.babylonjs.com/particles"; + /** Default culling strategy : this is an exclusion test and it's the more accurate. + * Test order : + * Is the bounding sphere outside the frustum ? + * If not, are the bounding box vertices outside the frustum ? + * It not, then the cullable object is in the frustum. + */ + Constants.MESHES_CULLINGSTRATEGY_STANDARD = 0; + /** Culling strategy : Bounding Sphere Only. + * This is an exclusion test. It's faster than the standard strategy because the bounding box is not tested. + * It's also less accurate than the standard because some not visible objects can still be selected. + * Test : is the bounding sphere outside the frustum ? + * If not, then the cullable object is in the frustum. + */ + Constants.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1; + /** Culling strategy : Optimistic Inclusion. + * This in an inclusion test first, then the standard exclusion test. + * This can be faster when a cullable object is expected to be almost always in the camera frustum. + * This could also be a little slower than the standard test when the tested object center is not the frustum but one of its bounding box vertex is still inside. + * Anyway, it's as accurate as the standard strategy. + * Test : + * Is the cullable object bounding sphere center in the frustum ? + * If not, apply the default culling strategy. + */ + Constants.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION = 2; + /** Culling strategy : Optimistic Inclusion then Bounding Sphere Only. + * This in an inclusion test first, then the bounding sphere only exclusion test. + * This can be the fastest test when a cullable object is expected to be almost always in the camera frustum. + * This could also be a little slower than the BoundingSphereOnly strategy when the tested object center is not in the frustum but its bounding sphere still intersects it. + * It's less accurate than the standard strategy and as accurate as the BoundingSphereOnly strategy. + * Test : + * Is the cullable object bounding sphere center in the frustum ? + * If not, apply the Bounding Sphere Only strategy. No Bounding Box is tested here. + */ + Constants.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY = 3; + /** + * No logging while loading + */ + Constants.SCENELOADER_NO_LOGGING = 0; + /** + * Minimal logging while loading + */ + Constants.SCENELOADER_MINIMAL_LOGGING = 1; + /** + * Summary logging while loading + */ + Constants.SCENELOADER_SUMMARY_LOGGING = 2; + /** + * Detailled logging while loading + */ + Constants.SCENELOADER_DETAILED_LOGGING = 3; + return Constants; +}()); + + + +/***/ }), + +/***/ "./Engines/engine.ts": +/*!***************************!*\ + !*** ./Engines/engine.ts ***! + \***************************/ +/*! exports provided: InstancingAttributeInfo, DepthTextureCreationOptions, EngineCapabilities, Engine */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InstancingAttributeInfo", function() { return InstancingAttributeInfo; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DepthTextureCreationOptions", function() { return DepthTextureCreationOptions; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EngineCapabilities", function() { return EngineCapabilities; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Engine", function() { return Engine; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _Misc_performanceMonitor__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/performanceMonitor */ "./Misc/performanceMonitor.ts"); +/* harmony import */ var _Misc_stringDictionary__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Misc/stringDictionary */ "./Misc/stringDictionary.ts"); +/* harmony import */ var _Misc_promise__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Misc/promise */ "./Misc/promise.ts"); +/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Misc/tools */ "./Misc/tools.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Maths_math_scalar__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Maths/math.scalar */ "./Maths/math.scalar.ts"); +/* harmony import */ var _Materials_effect__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Materials/effect */ "./Materials/effect.ts"); +/* harmony import */ var _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Materials/Textures/internalTexture */ "./Materials/Textures/internalTexture.ts"); +/* harmony import */ var _States_index__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../States/index */ "./States/index.ts"); +/* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./constants */ "./Engines/constants.ts"); +/* harmony import */ var _Misc_domManagement__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../Misc/domManagement */ "./Misc/domManagement.ts"); +/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts"); +/* harmony import */ var _engineStore__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./engineStore */ "./Engines/engineStore.ts"); +/* harmony import */ var _Materials_Textures_renderTargetCreationOptions__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../Materials/Textures/renderTargetCreationOptions */ "./Materials/Textures/renderTargetCreationOptions.ts"); +/* harmony import */ var _Misc_devTools__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../Misc/devTools */ "./Misc/devTools.ts"); +/* harmony import */ var _WebGL_webGLPipelineContext__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./WebGL/webGLPipelineContext */ "./Engines/WebGL/webGLPipelineContext.ts"); +/* harmony import */ var _Meshes_WebGL_webGLDataBuffer__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../Meshes/WebGL/webGLDataBuffer */ "./Meshes/WebGL/webGLDataBuffer.ts"); +/* harmony import */ var _WebGL_webGL2ShaderProcessors__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./WebGL/webGL2ShaderProcessors */ "./Engines/WebGL/webGL2ShaderProcessors.ts"); + + + + + + + + + + + + + + + + + + + + +/** + * Keeps track of all the buffer info used in engine. + */ +var BufferPointer = /** @class */ (function () { + function BufferPointer() { + } + return BufferPointer; +}()); +/** + * Interface for attribute information associated with buffer instanciation + */ +var InstancingAttributeInfo = /** @class */ (function () { + function InstancingAttributeInfo() { + } + return InstancingAttributeInfo; +}()); + +/** + * Define options used to create a depth texture + */ +var DepthTextureCreationOptions = /** @class */ (function () { + function DepthTextureCreationOptions() { + } + return DepthTextureCreationOptions; +}()); + +/** + * Class used to describe the capabilities of the engine relatively to the current browser + */ +var EngineCapabilities = /** @class */ (function () { + function EngineCapabilities() { + } + return EngineCapabilities; +}()); + +/** + * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio + */ +var Engine = /** @class */ (function () { + /** + * Creates a new engine + * @param canvasOrContext defines the canvas or WebGL context to use for rendering. If you provide a WebGL context, Babylon.js will not hook events on the canvas (like pointers, keyboards, etc...) so no event observables will be available. This is mostly used when Babylon.js is used as a plugin on a system which alreay used the WebGL context + * @param antialias defines enable antialiasing (default: false) + * @param options defines further options to be sent to the getContext() function + * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false) + */ + function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) { + var _this = this; + if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; } + /** + * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required + */ + this.forcePOTTextures = false; + /** + * Gets a boolean indicating if the engine is currently rendering in fullscreen mode + */ + this.isFullscreen = false; + /** + * Gets a boolean indicating if the pointer is currently locked + */ + this.isPointerLock = false; + /** + * Gets or sets a boolean indicating if back faces must be culled (true by default) + */ + this.cullBackFaces = true; + /** + * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun + */ + this.renderEvenInBackground = true; + /** + * Gets or sets a boolean indicating that cache can be kept between frames + */ + this.preventCacheWipeBetweenFrames = false; + /** + * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest + **/ + this.enableOfflineSupport = false; + /** + * Gets or sets a boolean to enable/disable checking manifest if IndexedDB support is enabled (js will always consider the database is up to date) + **/ + this.disableManifestCheck = false; + /** + * Gets the list of created scenes + */ + this.scenes = new Array(); + /** + * Event raised when a new scene is created + */ + this.onNewSceneAddedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + /** + * Gets the list of created postprocesses + */ + this.postProcesses = new Array(); + /** Gets or sets a boolean indicating if the engine should validate programs after compilation */ + this.validateShaderPrograms = false; + // Observables + /** + * Observable event triggered each time the rendering canvas is resized + */ + this.onResizeObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + /** + * Observable event triggered each time the canvas loses focus + */ + this.onCanvasBlurObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + /** + * Observable event triggered each time the canvas gains focus + */ + this.onCanvasFocusObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + /** + * Observable event triggered each time the canvas receives pointerout event + */ + this.onCanvasPointerOutObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + /** + * Observable event triggered before each texture is initialized + */ + this.onBeforeTextureInitObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + // Uniform buffers list + /** + * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported + */ + this.disableUniformBuffers = true; + /** @hidden */ + this._uniformBuffers = new Array(); + // Observables + /** + * Observable raised when the engine begins a new frame + */ + this.onBeginFrameObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + /** + * If set, will be used to request the next animation frame for the render loop + */ + this.customAnimationFrameRequester = null; + /** + * Observable raised when the engine ends the current frame + */ + this.onEndFrameObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + /** + * Observable raised when the engine is about to compile a shader + */ + this.onBeforeShaderCompilationObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + /** + * Observable raised when the engine has jsut compiled a shader + */ + this.onAfterShaderCompilationObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + this._windowIsBackground = false; + this._webGLVersion = 1.0; + this._highPrecisionShadersAllowed = true; + /** @hidden */ + this._badOS = false; + /** @hidden */ + this._badDesktopOS = false; + this._colorWrite = true; + /** @hidden */ + this._drawCalls = new _Misc_tools__WEBPACK_IMPORTED_MODULE_5__["PerfCounter"](); + this._renderingQueueLaunched = false; + this._activeRenderLoops = new Array(); + // Deterministic lockstepMaxSteps + this._deterministicLockstep = false; + this._lockstepMaxSteps = 4; + // Lost context + /** + * Observable signaled when a context lost event is raised + */ + this.onContextLostObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + /** + * Observable signaled when a context restored event is raised + */ + this.onContextRestoredObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + this._contextWasLost = false; + /** @hidden */ + this._doNotHandleContextLost = false; + // FPS + this._performanceMonitor = new _Misc_performanceMonitor__WEBPACK_IMPORTED_MODULE_2__["PerformanceMonitor"](); + this._fps = 60; + this._deltaTime = 0; + /** + * Turn this value on if you want to pause FPS computation when in background + */ + this.disablePerformanceMonitorInBackground = false; + /** + * Gets or sets a boolean indicating that vertex array object must be disabled even if they are supported + */ + this.disableVertexArrayObjects = false; + // States + /** @hidden */ + this._depthCullingState = new _States_index__WEBPACK_IMPORTED_MODULE_10__["_DepthCullingState"](); + /** @hidden */ + this._stencilState = new _States_index__WEBPACK_IMPORTED_MODULE_10__["_StencilState"](); + /** @hidden */ + this._alphaState = new _States_index__WEBPACK_IMPORTED_MODULE_10__["_AlphaState"](); + /** @hidden */ + this._alphaMode = Engine.ALPHA_DISABLE; + // Cache + /** @hidden */ + this._internalTexturesCache = new Array(); + /** @hidden */ + this._activeChannel = 0; + this._currentTextureChannel = -1; + /** @hidden */ + this._boundTexturesCache = {}; + this._compiledEffects = {}; + this._vertexAttribArraysEnabled = []; + this._uintIndicesCurrentlySet = false; + this._currentBoundBuffer = new Array(); + /** @hidden */ + this._currentFramebuffer = null; + this._currentBufferPointers = new Array(); + this._currentInstanceLocations = new Array(); + this._currentInstanceBuffers = new Array(); + this._vaoRecordInProgress = false; + this._mustWipeVertexAttributes = false; + this._nextFreeTextureSlots = new Array(); + this._maxSimultaneousTextures = 0; + this._activeRequests = new Array(); + // Hardware supported Compressed Textures + this._texturesSupported = new Array(); + /** + * Defines whether the engine has been created with the premultipliedAlpha option on or not. + */ + this.premultipliedAlpha = true; + this._viewportCached = new _Maths_math__WEBPACK_IMPORTED_MODULE_6__["Vector4"](0, 0, 0, 0); + this._unpackFlipYCached = null; + /** + * In case you are sharing the context with other applications, it might + * be interested to not cache the unpack flip y state to ensure a consistent + * value would be set. + */ + this.enableUnpackFlipYCached = true; + this._boundUniforms = {}; + // Register promises + _Misc_promise__WEBPACK_IMPORTED_MODULE_4__["PromisePolyfill"].Apply(); + var canvas = null; + Engine.Instances.push(this); + if (!canvasOrContext) { + return; + } + options = options || {}; + if (canvasOrContext.getContext) { + canvas = canvasOrContext; + this._renderingCanvas = canvas; + if (antialias != null) { + options.antialias = antialias; + } + if (options.deterministicLockstep === undefined) { + options.deterministicLockstep = false; + } + if (options.lockstepMaxSteps === undefined) { + options.lockstepMaxSteps = 4; + } + if (options.preserveDrawingBuffer === undefined) { + options.preserveDrawingBuffer = false; + } + if (options.audioEngine === undefined) { + options.audioEngine = true; + } + if (options.stencil === undefined) { + options.stencil = true; + } + if (options.premultipliedAlpha === false) { + this.premultipliedAlpha = false; + } + this._deterministicLockstep = options.deterministicLockstep; + this._lockstepMaxSteps = options.lockstepMaxSteps; + this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false; + // Exceptions + if (navigator && navigator.userAgent) { + var ua = navigator.userAgent; + for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) { + var exception = _a[_i]; + var key = exception.key; + var targets = exception.targets; + var check = new RegExp(key); + if (check.test(ua)) { + if (exception.capture && exception.captureConstraint) { + var capture = exception.capture; + var constraint = exception.captureConstraint; + var regex = new RegExp(capture); + var matches = regex.exec(ua); + if (matches && matches.length > 0) { + var capturedValue = parseInt(matches[matches.length - 1]); + if (capturedValue >= constraint) { + continue; + } + } + } + for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) { + var target = targets_1[_b]; + switch (target) { + case "uniformBuffer": + this.disableUniformBuffers = true; + break; + case "vao": + this.disableVertexArrayObjects = true; + break; + } + } + } + } + } + // Context lost + if (!this._doNotHandleContextLost) { + this._onContextLost = function (evt) { + evt.preventDefault(); + _this._contextWasLost = true; + _Misc_logger__WEBPACK_IMPORTED_MODULE_13__["Logger"].Warn("WebGL context lost."); + _this.onContextLostObservable.notifyObservers(_this); + }; + this._onContextRestored = function () { + // Adding a timeout to avoid race condition at browser level + setTimeout(function () { + // Rebuild gl context + _this._initGLContext(); + // Rebuild effects + _this._rebuildEffects(); + // Rebuild textures + _this._rebuildInternalTextures(); + // Rebuild buffers + _this._rebuildBuffers(); + // Cache + _this.wipeCaches(true); + _Misc_logger__WEBPACK_IMPORTED_MODULE_13__["Logger"].Warn("WebGL context successfully restored."); + _this.onContextRestoredObservable.notifyObservers(_this); + _this._contextWasLost = false; + }, 0); + }; + canvas.addEventListener("webglcontextlost", this._onContextLost, false); + canvas.addEventListener("webglcontextrestored", this._onContextRestored, false); + options.powerPreference = "high-performance"; + } + // GL + if (!options.disableWebGL2Support) { + try { + this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options)); + if (this._gl) { + this._webGLVersion = 2.0; + // Prevent weird browsers to lie :-) + if (!this._gl.deleteQuery) { + this._webGLVersion = 1.0; + } + } + } + catch (e) { + // Do nothing + } + } + if (!this._gl) { + if (!canvas) { + throw new Error("The provided canvas is null or undefined."); + } + try { + this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options)); + } + catch (e) { + throw new Error("WebGL not supported"); + } + } + if (!this._gl) { + throw new Error("WebGL not supported"); + } + // Ensures a consistent color space unpacking of textures cross browser. + this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, this._gl.NONE); + this._onCanvasFocus = function () { + _this.onCanvasFocusObservable.notifyObservers(_this); + }; + this._onCanvasBlur = function () { + _this.onCanvasBlurObservable.notifyObservers(_this); + }; + canvas.addEventListener("focus", this._onCanvasFocus); + canvas.addEventListener("blur", this._onCanvasBlur); + this._onBlur = function () { + if (_this.disablePerformanceMonitorInBackground) { + _this._performanceMonitor.disable(); + } + _this._windowIsBackground = true; + }; + this._onFocus = function () { + if (_this.disablePerformanceMonitorInBackground) { + _this._performanceMonitor.enable(); + } + _this._windowIsBackground = false; + }; + this._onCanvasPointerOut = function (ev) { + _this.onCanvasPointerOutObservable.notifyObservers(ev); + }; + if (_Misc_domManagement__WEBPACK_IMPORTED_MODULE_12__["DomManagement"].IsWindowObjectExist()) { + window.addEventListener("blur", this._onBlur); + window.addEventListener("focus", this._onFocus); + } + canvas.addEventListener("pointerout", this._onCanvasPointerOut); + if (!options.doNotHandleTouchAction) { + this._disableTouchAction(); + } + } + else { + this._gl = canvasOrContext; + this._renderingCanvas = this._gl.canvas; + if (this._gl.renderbufferStorageMultisample) { + this._webGLVersion = 2.0; + } + var attributes = this._gl.getContextAttributes(); + if (attributes) { + options.stencil = attributes.stencil; + } + } + if (options.useHighPrecisionFloats !== undefined) { + this._highPrecisionShadersAllowed = options.useHighPrecisionFloats; + } + // Viewport + var devicePixelRatio = _Misc_domManagement__WEBPACK_IMPORTED_MODULE_12__["DomManagement"].IsWindowObjectExist() ? (window.devicePixelRatio || 1.0) : 1.0; + var limitDeviceRatio = options.limitDeviceRatio || devicePixelRatio; + this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, devicePixelRatio) : 1.0; + this.resize(); + this._isStencilEnable = options.stencil ? true : false; + this._initGLContext(); + if (canvas) { + var anyDoc_1 = document; + // Fullscreen + this._onFullscreenChange = function () { + if (anyDoc_1.fullscreen !== undefined) { + _this.isFullscreen = anyDoc_1.fullscreen; + } + else if (anyDoc_1.mozFullScreen !== undefined) { + _this.isFullscreen = anyDoc_1.mozFullScreen; + } + else if (anyDoc_1.webkitIsFullScreen !== undefined) { + _this.isFullscreen = anyDoc_1.webkitIsFullScreen; + } + else if (anyDoc_1.msIsFullScreen !== undefined) { + _this.isFullscreen = anyDoc_1.msIsFullScreen; + } + // Pointer lock + if (_this.isFullscreen && _this._pointerLockRequested && canvas) { + _Misc_tools__WEBPACK_IMPORTED_MODULE_5__["Tools"].RequestPointerlock(canvas); + } + }; + document.addEventListener("fullscreenchange", this._onFullscreenChange, false); + document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false); + document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false); + document.addEventListener("msfullscreenchange", this._onFullscreenChange, false); + // Pointer lock + this._onPointerLockChange = function () { + _this.isPointerLock = (anyDoc_1.mozPointerLockElement === canvas || + anyDoc_1.webkitPointerLockElement === canvas || + anyDoc_1.msPointerLockElement === canvas || + anyDoc_1.pointerLockElement === canvas); + }; + document.addEventListener("pointerlockchange", this._onPointerLockChange, false); + document.addEventListener("mspointerlockchange", this._onPointerLockChange, false); + document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false); + document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false); + this._connectVREvents(canvas, anyDoc_1); + } + // Create Audio Engine if needed. + if (!Engine.audioEngine && options.audioEngine && Engine.AudioEngineFactory) { + Engine.audioEngine = Engine.AudioEngineFactory(this.getRenderingCanvas()); + } + // Prepare buffer pointers + for (var i = 0; i < this._caps.maxVertexAttribs; i++) { + this._currentBufferPointers[i] = new BufferPointer(); + } + // Load WebVR Devices + this._prepareVRComponent(); + if (options.autoEnableWebVR) { + this.initWebVR(); + } + // Shader processor + if (this.webGLVersion > 1) { + this._shaderProcessor = new _WebGL_webGL2ShaderProcessors__WEBPACK_IMPORTED_MODULE_19__["WebGL2ShaderProcessor"](); + } + // Detect if we are running on a faulty buggy OS. + this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent); + // Detect if we are running on a faulty buggy desktop OS. + this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent); + console.log("Babylon.js v" + Engine.Version + " - " + this.description); + this.enableOfflineSupport = Engine.OfflineProviderFactory !== undefined; + } + Object.defineProperty(Engine, "Instances", { + /** Gets the list of created engines */ + get: function () { + return _engineStore__WEBPACK_IMPORTED_MODULE_14__["EngineStore"].Instances; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Engine, "LastCreatedEngine", { + /** + * Gets the latest created engine + */ + get: function () { + return _engineStore__WEBPACK_IMPORTED_MODULE_14__["EngineStore"].LastCreatedEngine; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Engine, "LastCreatedScene", { + /** + * Gets the latest created scene + */ + get: function () { + return _engineStore__WEBPACK_IMPORTED_MODULE_14__["EngineStore"].LastCreatedScene; + }, + enumerable: true, + configurable: true + }); + /** + * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation + * @param flag defines which part of the materials must be marked as dirty + * @param predicate defines a predicate used to filter which materials should be affected + */ + Engine.MarkAllMaterialsAsDirty = function (flag, predicate) { + for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) { + var engine = Engine.Instances[engineIndex]; + for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) { + engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate); + } + } + }; + Object.defineProperty(Engine, "NpmPackage", { + /** + * Returns the current npm package of the sdk + */ + // Not mixed with Version for tooling purpose. + get: function () { + return "babylonjs@4.1.0-alpha.2"; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Engine, "Version", { + /** + * Returns the current version of the framework + */ + get: function () { + return "4.1.0-alpha.2"; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Engine.prototype, "description", { + /** + * Returns a string describing the current engine + */ + get: function () { + var description = "WebGL" + this.webGLVersion; + if (this._caps.parallelShaderCompile) { + description += " - Parallel shader compilation"; + } + return description; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Engine, "ShadersRepository", { + /** + * Gets or sets the relative url used to load shaders if using the engine in non-minified mode + */ + get: function () { + return _Materials_effect__WEBPACK_IMPORTED_MODULE_8__["Effect"].ShadersRepository; + }, + set: function (value) { + _Materials_effect__WEBPACK_IMPORTED_MODULE_8__["Effect"].ShadersRepository = value; + }, + enumerable: true, + configurable: true + }); + /** + * Method called to create the default loading screen. + * This can be overriden in your own app. + * @param canvas The rendering canvas element + * @returns The loading screen + */ + Engine.DefaultLoadingScreenFactory = function (canvas) { + throw _Misc_devTools__WEBPACK_IMPORTED_MODULE_16__["_DevTools"].WarnImport("LoadingScreen"); + }; + Object.defineProperty(Engine.prototype, "supportsUniformBuffers", { + /** + * Gets a boolean indicating that the engine supports uniform buffers + * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets + */ + get: function () { + return this.webGLVersion > 1 && !this.disableUniformBuffers; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Engine.prototype, "_shouldUseHighPrecisionShader", { + /** @hidden */ + get: function () { + return this._caps.highPrecisionShaderSupported && this._highPrecisionShadersAllowed; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Engine.prototype, "needPOTTextures", { + /** + * Gets a boolean indicating that only power of 2 textures are supported + * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them + */ + get: function () { + return this._webGLVersion < 2 || this.forcePOTTextures; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Engine.prototype, "doNotHandleContextLost", { + /** + * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events + * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost + */ + get: function () { + return this._doNotHandleContextLost; + }, + set: function (value) { + this._doNotHandleContextLost = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Engine.prototype, "performanceMonitor", { + /** + * Gets the performance monitor attached to this engine + * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation + */ + get: function () { + return this._performanceMonitor; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Engine.prototype, "texturesSupported", { + /** + * Gets the list of texture formats supported + */ + get: function () { + return this._texturesSupported; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Engine.prototype, "textureFormatInUse", { + /** + * Gets the list of texture formats in use + */ + get: function () { + return this._textureFormatInUse; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Engine.prototype, "currentViewport", { + /** + * Gets the current viewport + */ + get: function () { + return this._cachedViewport; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Engine.prototype, "emptyTexture", { + /** + * Gets the default empty texture + */ + get: function () { + if (!this._emptyTexture) { + this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE); + } + return this._emptyTexture; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Engine.prototype, "emptyTexture3D", { + /** + * Gets the default empty 3D texture + */ + get: function () { + if (!this._emptyTexture3D) { + this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE); + } + return this._emptyTexture3D; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Engine.prototype, "emptyCubeTexture", { + /** + * Gets the default empty cube texture + */ + get: function () { + if (!this._emptyCubeTexture) { + var faceData = new Uint8Array(4); + var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData]; + this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE); + } + return this._emptyCubeTexture; + }, + enumerable: true, + configurable: true + }); + // WebVR + /** + * Initializes a webVR display and starts listening to display change events + * The onVRDisplayChangedObservable will be notified upon these changes + * @returns The onVRDisplayChangedObservable + */ + Engine.prototype.initWebVR = function () { + throw _Misc_devTools__WEBPACK_IMPORTED_MODULE_16__["_DevTools"].WarnImport("WebVRCamera"); + }; + /** @hidden */ + Engine.prototype._prepareVRComponent = function () { + // Do nothing as the engine side effect will overload it + }; + /** @hidden */ + Engine.prototype._connectVREvents = function (canvas, document) { + // Do nothing as the engine side effect will overload it + }; + /** @hidden */ + Engine.prototype._submitVRFrame = function () { + // Do nothing as the engine side effect will overload it + }; + /** + * Call this function to leave webVR mode + * Will do nothing if webVR is not supported or if there is no webVR device + * @see http://doc.babylonjs.com/how_to/webvr_camera + */ + Engine.prototype.disableVR = function () { + // Do nothing as the engine side effect will overload it + }; + /** + * Gets a boolean indicating that the system is in VR mode and is presenting + * @returns true if VR mode is engaged + */ + Engine.prototype.isVRPresenting = function () { + return false; + }; + /** @hidden */ + Engine.prototype._requestVRFrame = function () { + // Do nothing as the engine side effect will overload it + }; + Engine.prototype._disableTouchAction = function () { + if (!this._renderingCanvas) { + return; + } + this._renderingCanvas.setAttribute("touch-action", "none"); + this._renderingCanvas.style.touchAction = "none"; + this._renderingCanvas.style.msTouchAction = "none"; + }; + Engine.prototype._rebuildInternalTextures = function () { + var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies + for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) { + var internalTexture = currentState_1[_i]; + internalTexture._rebuild(); + } + }; + Engine.prototype._rebuildEffects = function () { + for (var key in this._compiledEffects) { + var effect = this._compiledEffects[key]; + effect._prepareEffect(); + } + _Materials_effect__WEBPACK_IMPORTED_MODULE_8__["Effect"].ResetCache(); + }; + /** + * Gets a boolean indicating if all created effects are ready + * @returns true if all effects are ready + */ + Engine.prototype.areAllEffectsReady = function () { + for (var key in this._compiledEffects) { + var effect = this._compiledEffects[key]; + if (!effect.isReady()) { + return false; + } + } + return true; + }; + Engine.prototype._rebuildBuffers = function () { + // Index / Vertex + for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) { + var scene = _a[_i]; + scene.resetCachedMaterial(); + scene._rebuildGeometries(); + scene._rebuildTextures(); + } + // Uniforms + for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) { + var uniformBuffer = _c[_b]; + uniformBuffer._rebuild(); + } + }; + Engine.prototype._initGLContext = function () { + // Caps + this._caps = new EngineCapabilities(); + this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS); + this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS); + this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS); + this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE); + this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE); + this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE); + this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS); + this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS); + this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS); + this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS); + // Infos + this._glVersion = this._gl.getParameter(this._gl.VERSION); + var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info"); + if (rendererInfo != null) { + this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL); + this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL); + } + if (!this._glVendor) { + this._glVendor = "Unknown vendor"; + } + if (!this._glRenderer) { + this._glRenderer = "Unknown renderer"; + } + // Constants + this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit). + if (this._gl.RGBA16F !== 0x881A) { + this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format. + } + if (this._gl.RGBA32F !== 0x8814) { + this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format. + } + if (this._gl.DEPTH24_STENCIL8 !== 35056) { + this._gl.DEPTH24_STENCIL8 = 35056; + } + // Extensions + this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null); + this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc'); + this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc'); + this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc'); + this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1'); + this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') || + this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3 + this._caps.textureAnisotropicFilterExtension = this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic'); + this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0; + this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null; + this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null; + this._caps.highPrecisionShaderSupported = false; + this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query"); + if (this._caps.timerQuery) { + if (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; + } + // Checks if some of the format renders first to allow the use of webgl inspector. + this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float'); + this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false; + this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false; + this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false; + this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false; + this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false; + if (this._webGLVersion > 1) { + this._gl.HALF_FLOAT_OES = 0x140B; + } + this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer(); + this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false; + this._caps.multiview = this._gl.getExtension('OVR_multiview2'); + // Draw buffers + if (this._webGLVersion > 1) { + this._caps.drawBuffersExtension = true; + } + else { + var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers'); + if (drawBuffersExtension !== null) { + this._caps.drawBuffersExtension = true; + this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension); + this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER; + for (var i = 0; i < 16; i++) { + this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"]; + } + } + else { + this._caps.drawBuffersExtension = false; + } + } + // Shader compiler threads + this._caps.parallelShaderCompile = this._gl.getExtension('KHR_parallel_shader_compile'); + // Depth Texture + if (this._webGLVersion > 1) { + this._caps.depthTextureExtension = true; + } + else { + var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture'); + if (depthTextureExtension != null) { + this._caps.depthTextureExtension = true; + this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL; + } + } + // Vertex array object + if (this.disableVertexArrayObjects) { + this._caps.vertexArrayObject = false; + } + else if (this._webGLVersion > 1) { + this._caps.vertexArrayObject = true; + } + else { + var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object'); + if (vertexArrayObjectExtension != null) { + this._caps.vertexArrayObject = true; + this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension); + this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension); + this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension); + } + else { + this._caps.vertexArrayObject = false; + } + } + // Instances count + if (this._webGLVersion > 1) { + this._caps.instancedArrays = true; + } + else { + var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays'); + if (instanceExtension != null) { + this._caps.instancedArrays = true; + this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension); + this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension); + this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension); + } + else { + this._caps.instancedArrays = false; + } + } + // Intelligently add supported compressed formats in order to check for. + // Check for ASTC support first as it is most powerful and to be very cross platform. + // Next PVRTC & DXT, which are probably superior to ETC1/2. + // Likely no hardware which supports both PVR & DXT, so order matters little. + // ETC2 is newer and handles ETC1 (no alpha capability), so check for first. + if (this._caps.astc) { + this.texturesSupported.push('-astc.ktx'); + } + if (this._caps.s3tc) { + this.texturesSupported.push('-dxt.ktx'); + } + if (this._caps.pvrtc) { + this.texturesSupported.push('-pvrtc.ktx'); + } + if (this._caps.etc2) { + this.texturesSupported.push('-etc2.ktx'); + } + if (this._caps.etc1) { + this.texturesSupported.push('-etc1.ktx'); + } + if (this._gl.getShaderPrecisionFormat) { + var vertex_highp = this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER, this._gl.HIGH_FLOAT); + var fragment_highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT); + if (vertex_highp && fragment_highp) { + this._caps.highPrecisionShaderSupported = vertex_highp.precision !== 0 && fragment_highp.precision !== 0; + } + } + // Depth buffer + this.setDepthBuffer(true); + this.setDepthFunctionToLessOrEqual(); + this.setDepthWrite(true); + // Texture maps + this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits; + for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) { + this._nextFreeTextureSlots.push(slot); + } + }; + Object.defineProperty(Engine.prototype, "webGLVersion", { + /** + * Gets version of the current webGL context + */ + get: function () { + return this._webGLVersion; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Engine.prototype, "isStencilEnable", { + /** + * Returns true if the stencil buffer has been enabled through the creation option of the context. + */ + get: function () { + return this._isStencilEnable; + }, + enumerable: true, + configurable: true + }); + /** @hidden */ + Engine.prototype._prepareWorkingCanvas = function () { + if (this._workingCanvas) { + return; + } + this._workingCanvas = document.createElement("canvas"); + var context = this._workingCanvas.getContext("2d"); + if (context) { + this._workingContext = context; + } + }; + /** + * Reset the texture cache to empty state + */ + Engine.prototype.resetTextureCache = function () { + for (var key in this._boundTexturesCache) { + if (!this._boundTexturesCache.hasOwnProperty(key)) { + continue; + } + this._boundTexturesCache[key] = null; + } + this._currentTextureChannel = -1; + }; + /** + * Gets a boolean indicating that the engine is running in deterministic lock step mode + * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep + * @returns true if engine is in deterministic lock step mode + */ + Engine.prototype.isDeterministicLockStep = function () { + return this._deterministicLockstep; + }; + /** + * Gets the max steps when engine is running in deterministic lock step + * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep + * @returns the max steps + */ + Engine.prototype.getLockstepMaxSteps = function () { + return this._lockstepMaxSteps; + }; + /** + * Gets an object containing information about the current webGL context + * @returns an object containing the vender, the renderer and the version of the current webGL context + */ + Engine.prototype.getGlInfo = function () { + return { + vendor: this._glVendor, + renderer: this._glRenderer, + version: this._glVersion + }; + }; + /** + * Gets current aspect ratio + * @param camera defines the camera to use to get the aspect ratio + * @param useScreen defines if screen size must be used (or the current render target if any) + * @returns a number defining the aspect ratio + */ + Engine.prototype.getAspectRatio = function (camera, useScreen) { + if (useScreen === void 0) { useScreen = false; } + var viewport = camera.viewport; + return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height); + }; + /** + * Gets current screen aspect ratio + * @returns a number defining the aspect ratio + */ + Engine.prototype.getScreenAspectRatio = function () { + return (this.getRenderWidth(true)) / (this.getRenderHeight(true)); + }; + /** + * Gets the current render width + * @param useScreen defines if screen size must be used (or the current render target if any) + * @returns a number defining the current render width + */ + Engine.prototype.getRenderWidth = function (useScreen) { + if (useScreen === void 0) { useScreen = false; } + if (!useScreen && this._currentRenderTarget) { + return this._currentRenderTarget.width; + } + return this._gl.drawingBufferWidth; + }; + /** + * Gets the current render height + * @param useScreen defines if screen size must be used (or the current render target if any) + * @returns a number defining the current render height + */ + Engine.prototype.getRenderHeight = function (useScreen) { + if (useScreen === void 0) { useScreen = false; } + if (!useScreen && this._currentRenderTarget) { + return this._currentRenderTarget.height; + } + return this._gl.drawingBufferHeight; + }; + /** + * Gets the HTML canvas attached with the current webGL context + * @returns a HTML canvas + */ + Engine.prototype.getRenderingCanvas = function () { + return this._renderingCanvas; + }; + /** + * Gets the client rect of the HTML canvas attached with the current webGL context + * @returns a client rectanglee + */ + Engine.prototype.getRenderingCanvasClientRect = function () { + if (!this._renderingCanvas) { + return null; + } + return this._renderingCanvas.getBoundingClientRect(); + }; + /** + * Defines the hardware scaling level. + * By default the hardware scaling level is computed from the window device ratio. + * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas. + * @param level defines the level to use + */ + Engine.prototype.setHardwareScalingLevel = function (level) { + this._hardwareScalingLevel = level; + this.resize(); + }; + /** + * Gets the current hardware scaling level. + * By default the hardware scaling level is computed from the window device ratio. + * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas. + * @returns a number indicating the current hardware scaling level + */ + Engine.prototype.getHardwareScalingLevel = function () { + return this._hardwareScalingLevel; + }; + /** + * Gets the list of loaded textures + * @returns an array containing all loaded textures + */ + Engine.prototype.getLoadedTexturesCache = function () { + return this._internalTexturesCache; + }; + /** + * Gets the object containing all engine capabilities + * @returns the EngineCapabilities object + */ + Engine.prototype.getCaps = function () { + return this._caps; + }; + /** + * Gets the current depth function + * @returns a number defining the depth function + */ + Engine.prototype.getDepthFunction = function () { + return this._depthCullingState.depthFunc; + }; + /** + * Sets the current depth function + * @param depthFunc defines the function to use + */ + Engine.prototype.setDepthFunction = function (depthFunc) { + this._depthCullingState.depthFunc = depthFunc; + }; + /** + * Sets the current depth function to GREATER + */ + Engine.prototype.setDepthFunctionToGreater = function () { + this._depthCullingState.depthFunc = this._gl.GREATER; + }; + /** + * Sets the current depth function to GEQUAL + */ + Engine.prototype.setDepthFunctionToGreaterOrEqual = function () { + this._depthCullingState.depthFunc = this._gl.GEQUAL; + }; + /** + * Sets the current depth function to LESS + */ + Engine.prototype.setDepthFunctionToLess = function () { + this._depthCullingState.depthFunc = this._gl.LESS; + }; + /** + * Caches the the state of the stencil buffer + */ + Engine.prototype.cacheStencilState = function () { + this._cachedStencilBuffer = this.getStencilBuffer(); + this._cachedStencilFunction = this.getStencilFunction(); + this._cachedStencilMask = this.getStencilMask(); + this._cachedStencilOperationPass = this.getStencilOperationPass(); + this._cachedStencilOperationFail = this.getStencilOperationFail(); + this._cachedStencilOperationDepthFail = this.getStencilOperationDepthFail(); + this._cachedStencilReference = this.getStencilFunctionReference(); + }; + /** + * Restores the state of the stencil buffer + */ + Engine.prototype.restoreStencilState = function () { + this.setStencilFunction(this._cachedStencilFunction); + this.setStencilMask(this._cachedStencilMask); + this.setStencilBuffer(this._cachedStencilBuffer); + this.setStencilOperationPass(this._cachedStencilOperationPass); + this.setStencilOperationFail(this._cachedStencilOperationFail); + this.setStencilOperationDepthFail(this._cachedStencilOperationDepthFail); + this.setStencilFunctionReference(this._cachedStencilReference); + }; + /** + * Sets the current depth function to LEQUAL + */ + Engine.prototype.setDepthFunctionToLessOrEqual = function () { + this._depthCullingState.depthFunc = this._gl.LEQUAL; + }; + /** + * Gets a boolean indicating if stencil buffer is enabled + * @returns the current stencil buffer state + */ + Engine.prototype.getStencilBuffer = function () { + return this._stencilState.stencilTest; + }; + /** + * Enable or disable the stencil buffer + * @param enable defines if the stencil buffer must be enabled or disabled + */ + Engine.prototype.setStencilBuffer = function (enable) { + this._stencilState.stencilTest = enable; + }; + /** + * Gets the current stencil mask + * @returns a number defining the new stencil mask to use + */ + Engine.prototype.getStencilMask = function () { + return this._stencilState.stencilMask; + }; + /** + * Sets the current stencil mask + * @param mask defines the new stencil mask to use + */ + Engine.prototype.setStencilMask = function (mask) { + this._stencilState.stencilMask = mask; + }; + /** + * Gets the current stencil function + * @returns a number defining the stencil function to use + */ + Engine.prototype.getStencilFunction = function () { + return this._stencilState.stencilFunc; + }; + /** + * Gets the current stencil reference value + * @returns a number defining the stencil reference value to use + */ + Engine.prototype.getStencilFunctionReference = function () { + return this._stencilState.stencilFuncRef; + }; + /** + * Gets the current stencil mask + * @returns a number defining the stencil mask to use + */ + Engine.prototype.getStencilFunctionMask = function () { + return this._stencilState.stencilFuncMask; + }; + /** + * Sets the current stencil function + * @param stencilFunc defines the new stencil function to use + */ + Engine.prototype.setStencilFunction = function (stencilFunc) { + this._stencilState.stencilFunc = stencilFunc; + }; + /** + * Sets the current stencil reference + * @param reference defines the new stencil reference to use + */ + Engine.prototype.setStencilFunctionReference = function (reference) { + this._stencilState.stencilFuncRef = reference; + }; + /** + * Sets the current stencil mask + * @param mask defines the new stencil mask to use + */ + Engine.prototype.setStencilFunctionMask = function (mask) { + this._stencilState.stencilFuncMask = mask; + }; + /** + * Gets the current stencil operation when stencil fails + * @returns a number defining stencil operation to use when stencil fails + */ + Engine.prototype.getStencilOperationFail = function () { + return this._stencilState.stencilOpStencilFail; + }; + /** + * Gets the current stencil operation when depth fails + * @returns a number defining stencil operation to use when depth fails + */ + Engine.prototype.getStencilOperationDepthFail = function () { + return this._stencilState.stencilOpDepthFail; + }; + /** + * Gets the current stencil operation when stencil passes + * @returns a number defining stencil operation to use when stencil passes + */ + Engine.prototype.getStencilOperationPass = function () { + return this._stencilState.stencilOpStencilDepthPass; + }; + /** + * Sets the stencil operation to use when stencil fails + * @param operation defines the stencil operation to use when stencil fails + */ + Engine.prototype.setStencilOperationFail = function (operation) { + this._stencilState.stencilOpStencilFail = operation; + }; + /** + * Sets the stencil operation to use when depth fails + * @param operation defines the stencil operation to use when depth fails + */ + Engine.prototype.setStencilOperationDepthFail = function (operation) { + this._stencilState.stencilOpDepthFail = operation; + }; + /** + * Sets the stencil operation to use when stencil passes + * @param operation defines the stencil operation to use when stencil passes + */ + Engine.prototype.setStencilOperationPass = function (operation) { + this._stencilState.stencilOpStencilDepthPass = operation; + }; + /** + * Sets a boolean indicating if the dithering state is enabled or disabled + * @param value defines the dithering state + */ + Engine.prototype.setDitheringState = function (value) { + if (value) { + this._gl.enable(this._gl.DITHER); + } + else { + this._gl.disable(this._gl.DITHER); + } + }; + /** + * Sets a boolean indicating if the rasterizer state is enabled or disabled + * @param value defines the rasterizer state + */ + Engine.prototype.setRasterizerState = function (value) { + if (value) { + this._gl.disable(this._gl.RASTERIZER_DISCARD); + } + else { + this._gl.enable(this._gl.RASTERIZER_DISCARD); + } + }; + /** + * stop executing a render loop function and remove it from the execution array + * @param renderFunction defines the function to be removed. If not provided all functions will be removed. + */ + Engine.prototype.stopRenderLoop = function (renderFunction) { + if (!renderFunction) { + this._activeRenderLoops = []; + return; + } + var index = this._activeRenderLoops.indexOf(renderFunction); + if (index >= 0) { + this._activeRenderLoops.splice(index, 1); + } + }; + /** @hidden */ + Engine.prototype._renderLoop = function () { + if (!this._contextWasLost) { + var shouldRender = true; + if (!this.renderEvenInBackground && this._windowIsBackground) { + shouldRender = false; + } + if (shouldRender) { + // Start new frame + this.beginFrame(); + for (var index = 0; index < this._activeRenderLoops.length; index++) { + var renderFunction = this._activeRenderLoops[index]; + renderFunction(); + } + // Present + this.endFrame(); + } + } + if (this._activeRenderLoops.length > 0) { + // Register new frame + if (this.customAnimationFrameRequester) { + this.customAnimationFrameRequester.requestID = this._queueNewFrame(this.customAnimationFrameRequester.renderFunction || this._bindedRenderFunction, this.customAnimationFrameRequester); + this._frameHandler = this.customAnimationFrameRequester.requestID; + } + else if (this.isVRPresenting()) { + this._requestVRFrame(); + } + else { + this._frameHandler = this._queueNewFrame(this._bindedRenderFunction); + } + } + else { + this._renderingQueueLaunched = false; + } + }; + /** + * Can be used to override the current requestAnimationFrame requester. + * @hidden + */ + Engine.prototype._queueNewFrame = function (bindedRenderFunction, requester) { + return _Misc_tools__WEBPACK_IMPORTED_MODULE_5__["Tools"].QueueNewFrame(bindedRenderFunction, requester); + }; + /** + * Register and execute a render loop. The engine can have more than one render function + * @param renderFunction defines the function to continuously execute + */ + Engine.prototype.runRenderLoop = function (renderFunction) { + if (this._activeRenderLoops.indexOf(renderFunction) !== -1) { + return; + } + this._activeRenderLoops.push(renderFunction); + if (!this._renderingQueueLaunched) { + this._renderingQueueLaunched = true; + this._bindedRenderFunction = this._renderLoop.bind(this); + this._frameHandler = this._queueNewFrame(this._bindedRenderFunction); + } + }; + /** + * Toggle full screen mode + * @param requestPointerLock defines if a pointer lock should be requested from the user + */ + Engine.prototype.switchFullscreen = function (requestPointerLock) { + if (this.isFullscreen) { + this.exitFullscreen(); + } + else { + this.enterFullscreen(requestPointerLock); + } + }; + /** + * Enters full screen mode + * @param requestPointerLock defines if a pointer lock should be requested from the user + */ + Engine.prototype.enterFullscreen = function (requestPointerLock) { + if (!this.isFullscreen) { + this._pointerLockRequested = requestPointerLock; + if (this._renderingCanvas) { + _Misc_tools__WEBPACK_IMPORTED_MODULE_5__["Tools"].RequestFullscreen(this._renderingCanvas); + } + } + }; + /** + * Exits full screen mode + */ + Engine.prototype.exitFullscreen = function () { + if (this.isFullscreen) { + _Misc_tools__WEBPACK_IMPORTED_MODULE_5__["Tools"].ExitFullscreen(); + } + }; + /** + * Enters Pointerlock mode + */ + Engine.prototype.enterPointerlock = function () { + if (this._renderingCanvas) { + _Misc_tools__WEBPACK_IMPORTED_MODULE_5__["Tools"].RequestPointerlock(this._renderingCanvas); + } + }; + /** + * Exits Pointerlock mode + */ + Engine.prototype.exitPointerlock = function () { + _Misc_tools__WEBPACK_IMPORTED_MODULE_5__["Tools"].ExitPointerlock(); + }; + /** + * Clear the current render buffer or the current render target (if any is set up) + * @param color defines the color to use + * @param backBuffer defines if the back buffer must be cleared + * @param depth defines if the depth buffer must be cleared + * @param stencil defines if the stencil buffer must be cleared + */ + Engine.prototype.clear = function (color, backBuffer, depth, stencil) { + if (stencil === void 0) { stencil = false; } + this.applyStates(); + var mode = 0; + if (backBuffer && color) { + this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0); + mode |= this._gl.COLOR_BUFFER_BIT; + } + if (depth) { + this._gl.clearDepth(1.0); + mode |= this._gl.DEPTH_BUFFER_BIT; + } + if (stencil) { + this._gl.clearStencil(0); + mode |= this._gl.STENCIL_BUFFER_BIT; + } + this._gl.clear(mode); + }; + /** + * Executes a scissor clear (ie. a clear on a specific portion of the screen) + * @param x defines the x-coordinate of the top left corner of the clear rectangle + * @param y defines the y-coordinate of the corner of the clear rectangle + * @param width defines the width of the clear rectangle + * @param height defines the height of the clear rectangle + * @param clearColor defines the clear color + */ + Engine.prototype.scissorClear = function (x, y, width, height, clearColor) { + this.enableScissor(x, y, width, height); + this.clear(clearColor, true, true, true); + this.disableScissor(); + }; + /** + * Enable scissor test on a specific rectangle (ie. render will only be executed on a specific portion of the screen) + * @param x defines the x-coordinate of the top left corner of the clear rectangle + * @param y defines the y-coordinate of the corner of the clear rectangle + * @param width defines the width of the clear rectangle + * @param height defines the height of the clear rectangle + */ + Engine.prototype.enableScissor = function (x, y, width, height) { + var gl = this._gl; + // Change state + gl.enable(gl.SCISSOR_TEST); + gl.scissor(x, y, width, height); + }; + /** + * Disable previously set scissor test rectangle + */ + Engine.prototype.disableScissor = function () { + var gl = this._gl; + gl.disable(gl.SCISSOR_TEST); + }; + /** @hidden */ + Engine.prototype._viewport = function (x, y, width, height) { + if (x !== this._viewportCached.x || + y !== this._viewportCached.y || + width !== this._viewportCached.z || + height !== this._viewportCached.w) { + this._viewportCached.x = x; + this._viewportCached.y = y; + this._viewportCached.z = width; + this._viewportCached.w = height; + this._gl.viewport(x, y, width, height); + } + }; + /** + * Set the WebGL's viewport + * @param viewport defines the viewport element to be used + * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used + * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used + */ + Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) { + var width = requiredWidth || this.getRenderWidth(); + var height = requiredHeight || this.getRenderHeight(); + var x = viewport.x || 0; + var y = viewport.y || 0; + this._cachedViewport = viewport; + this._viewport(x * width, y * height, width * viewport.width, height * viewport.height); + }; + /** + * Directly set the WebGL Viewport + * @param x defines the x coordinate of the viewport (in screen space) + * @param y defines the y coordinate of the viewport (in screen space) + * @param width defines the width of the viewport (in screen space) + * @param height defines the height of the viewport (in screen space) + * @return the current viewport Object (if any) that is being replaced by this call. You can restore this viewport later on to go back to the original state + */ + Engine.prototype.setDirectViewport = function (x, y, width, height) { + var currentViewport = this._cachedViewport; + this._cachedViewport = null; + this._viewport(x, y, width, height); + return currentViewport; + }; + /** + * Begin a new frame + */ + Engine.prototype.beginFrame = function () { + this.onBeginFrameObservable.notifyObservers(this); + this._measureFps(); + }; + /** + * Enf the current frame + */ + Engine.prototype.endFrame = function () { + // Force a flush in case we are using a bad OS. + if (this._badOS) { + this.flushFramebuffer(); + } + this._submitVRFrame(); + this.onEndFrameObservable.notifyObservers(this); + }; + /** + * Resize the view according to the canvas' size + */ + Engine.prototype.resize = function () { + // We're not resizing the size of the canvas while in VR mode & presenting + if (!this.isVRPresenting()) { + var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth; + var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight; + this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel); + } + }; + /** + * Force a specific size of the canvas + * @param width defines the new canvas' width + * @param height defines the new canvas' height + */ + Engine.prototype.setSize = function (width, height) { + if (!this._renderingCanvas) { + return; + } + if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) { + return; + } + this._renderingCanvas.width = width; + this._renderingCanvas.height = height; + for (var index = 0; index < this.scenes.length; index++) { + var scene = this.scenes[index]; + for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) { + var cam = scene.cameras[camIndex]; + cam._currentRenderId = 0; + } + } + if (this.onResizeObservable.hasObservers) { + this.onResizeObservable.notifyObservers(this); + } + }; + /** + * Binds the frame buffer to the specified texture. + * @param texture The texture to render to or null for the default canvas + * @param faceIndex The face of the texture to render to in case of cube texture + * @param requiredWidth The width of the target to render to + * @param requiredHeight The height of the target to render to + * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true + * @param depthStencilTexture The depth stencil texture to use to render + * @param lodLevel defines le lod level to bind to the frame buffer + */ + Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) { + if (lodLevel === void 0) { lodLevel = 0; } + if (this._currentRenderTarget) { + this.unBindFramebuffer(this._currentRenderTarget); + } + this._currentRenderTarget = texture; + this._bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer); + var gl = this._gl; + if (texture.isCube) { + if (faceIndex === undefined) { + faceIndex = 0; + } + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel); + if (depthStencilTexture) { + if (depthStencilTexture._generateStencilBuffer) { + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel); + } + else { + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel); + } + } + } + if (this._cachedViewport && !forceFullscreenViewport) { + this.setViewport(this._cachedViewport, requiredWidth, requiredHeight); + } + else { + if (!requiredWidth) { + requiredWidth = texture.width; + if (lodLevel) { + requiredWidth = requiredWidth / Math.pow(2, lodLevel); + } + } + if (!requiredHeight) { + requiredHeight = texture.height; + if (lodLevel) { + requiredHeight = requiredHeight / Math.pow(2, lodLevel); + } + } + this._viewport(0, 0, requiredWidth, requiredHeight); + } + this.wipeCaches(); + }; + /** @hidden */ + Engine.prototype._bindUnboundFramebuffer = function (framebuffer) { + if (this._currentFramebuffer !== framebuffer) { + this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer); + this._currentFramebuffer = framebuffer; + } + }; + /** + * Unbind the current render target texture from the webGL context + * @param texture defines the render target texture to unbind + * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated + * @param onBeforeUnbind defines a function which will be called before the effective unbind + */ + Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) { + if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; } + this._currentRenderTarget = null; + // If MSAA, we need to bitblt back to main texture + var gl = this._gl; + if (texture._MSAAFramebuffer) { + gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer); + gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer); + gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST); + } + if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) { + this._bindTextureDirectly(gl.TEXTURE_2D, texture, true); + gl.generateMipmap(gl.TEXTURE_2D); + this._bindTextureDirectly(gl.TEXTURE_2D, null); + } + if (onBeforeUnbind) { + if (texture._MSAAFramebuffer) { + // Bind the correct framebuffer + this._bindUnboundFramebuffer(texture._framebuffer); + } + onBeforeUnbind(); + } + this._bindUnboundFramebuffer(null); + }; + /** + * Force the mipmap generation for the given render target texture + * @param texture defines the render target texture to use + */ + Engine.prototype.generateMipMapsForCubemap = function (texture) { + if (texture.generateMipMaps) { + var gl = this._gl; + this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true); + gl.generateMipmap(gl.TEXTURE_CUBE_MAP); + this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null); + } + }; + /** + * Force a webGL flush (ie. a flush of all waiting webGL commands) + */ + Engine.prototype.flushFramebuffer = function () { + this._gl.flush(); + }; + /** + * Unbind the current render target and bind the default framebuffer + */ + Engine.prototype.restoreDefaultFramebuffer = function () { + if (this._currentRenderTarget) { + this.unBindFramebuffer(this._currentRenderTarget); + } + else { + this._bindUnboundFramebuffer(null); + } + if (this._cachedViewport) { + this.setViewport(this._cachedViewport); + } + this.wipeCaches(); + }; + // UBOs + /** + * Create an uniform buffer + * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets + * @param elements defines the content of the uniform buffer + * @returns the webGL uniform buffer + */ + Engine.prototype.createUniformBuffer = function (elements) { + var ubo = this._gl.createBuffer(); + if (!ubo) { + throw new Error("Unable to create uniform buffer"); + } + var result = new _Meshes_WebGL_webGLDataBuffer__WEBPACK_IMPORTED_MODULE_18__["WebGLDataBuffer"](ubo); + this.bindUniformBuffer(result); + if (elements instanceof Float32Array) { + this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW); + } + else { + this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW); + } + this.bindUniformBuffer(null); + result.references = 1; + return result; + }; + /** + * Create a dynamic uniform buffer + * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets + * @param elements defines the content of the uniform buffer + * @returns the webGL uniform buffer + */ + Engine.prototype.createDynamicUniformBuffer = function (elements) { + var ubo = this._gl.createBuffer(); + if (!ubo) { + throw new Error("Unable to create dynamic uniform buffer"); + } + var result = new _Meshes_WebGL_webGLDataBuffer__WEBPACK_IMPORTED_MODULE_18__["WebGLDataBuffer"](ubo); + this.bindUniformBuffer(result); + if (elements instanceof Float32Array) { + this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW); + } + else { + this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW); + } + this.bindUniformBuffer(null); + result.references = 1; + return result; + }; + /** + * Update an existing uniform buffer + * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets + * @param uniformBuffer defines the target uniform buffer + * @param elements defines the content to update + * @param offset defines the offset in the uniform buffer where update should start + * @param count defines the size of the data to update + */ + Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) { + this.bindUniformBuffer(uniformBuffer); + if (offset === undefined) { + offset = 0; + } + if (count === undefined) { + if (elements instanceof Float32Array) { + this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements); + } + else { + this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements)); + } + } + else { + if (elements instanceof Float32Array) { + this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count)); + } + else { + this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count)); + } + } + this.bindUniformBuffer(null); + }; + // VBOs + Engine.prototype._resetVertexBufferBinding = function () { + this.bindArrayBuffer(null); + this._cachedVertexBuffers = null; + }; + /** + * Creates a vertex buffer + * @param data the data for the vertex buffer + * @returns the new WebGL static buffer + */ + Engine.prototype.createVertexBuffer = function (data) { + var vbo = this._gl.createBuffer(); + if (!vbo) { + throw new Error("Unable to create vertex buffer"); + } + var dataBuffer = new _Meshes_WebGL_webGLDataBuffer__WEBPACK_IMPORTED_MODULE_18__["WebGLDataBuffer"](vbo); + this.bindArrayBuffer(dataBuffer); + if (data instanceof Array) { + this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW); + } + else { + this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW); + } + this._resetVertexBufferBinding(); + dataBuffer.references = 1; + return dataBuffer; + }; + /** + * Creates a dynamic vertex buffer + * @param data the data for the dynamic vertex buffer + * @returns the new WebGL dynamic buffer + */ + Engine.prototype.createDynamicVertexBuffer = function (data) { + var vbo = this._gl.createBuffer(); + if (!vbo) { + throw new Error("Unable to create dynamic vertex buffer"); + } + var result = new _Meshes_WebGL_webGLDataBuffer__WEBPACK_IMPORTED_MODULE_18__["WebGLDataBuffer"](vbo); + this.bindArrayBuffer(result); + if (data instanceof Array) { + this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW); + } + else { + this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW); + } + this._resetVertexBufferBinding(); + result.references = 1; + return result; + }; + /** + * Update a dynamic index buffer + * @param indexBuffer defines the target index buffer + * @param indices defines the data to update + * @param offset defines the offset in the target index buffer where update should start + */ + Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) { + if (offset === void 0) { offset = 0; } + // Force cache update + this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null; + this.bindIndexBuffer(indexBuffer); + var arrayBuffer; + if (indices instanceof Uint16Array || indices instanceof Uint32Array) { + arrayBuffer = indices; + } + else { + arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices); + } + this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW); + this._resetIndexBufferBinding(); + }; + /** + * Updates a dynamic vertex buffer. + * @param vertexBuffer the vertex buffer to update + * @param data the data used to update the vertex buffer + * @param byteOffset the byte offset of the data + * @param byteLength the byte length of the data + */ + Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) { + this.bindArrayBuffer(vertexBuffer); + if (byteOffset === undefined) { + byteOffset = 0; + } + if (byteLength === undefined) { + if (data instanceof Array) { + this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data)); + } + else { + this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data); + } + } + else { + if (data instanceof Array) { + this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength)); + } + else { + if (data instanceof ArrayBuffer) { + data = new Uint8Array(data, byteOffset, byteLength); + } + else { + data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength); + } + this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data); + } + } + this._resetVertexBufferBinding(); + }; + Engine.prototype._resetIndexBufferBinding = function () { + this.bindIndexBuffer(null); + this._cachedIndexBuffer = null; + }; + /** + * Creates a new index buffer + * @param indices defines the content of the index buffer + * @param updatable defines if the index buffer must be updatable + * @returns a new webGL buffer + */ + Engine.prototype.createIndexBuffer = function (indices, updatable) { + var vbo = this._gl.createBuffer(); + var dataBuffer = new _Meshes_WebGL_webGLDataBuffer__WEBPACK_IMPORTED_MODULE_18__["WebGLDataBuffer"](vbo); + if (!vbo) { + throw new Error("Unable to create index buffer"); + } + this.bindIndexBuffer(dataBuffer); + var data = this._normalizeIndexData(indices); + this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, data, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW); + this._resetIndexBufferBinding(); + dataBuffer.references = 1; + dataBuffer.is32Bits = (data.BYTES_PER_ELEMENT === 4); + return dataBuffer; + }; + Engine.prototype._normalizeIndexData = function (indices) { + if (indices instanceof Uint16Array) { + return indices; + } + // Check 32 bit support + if (this._caps.uintIndices) { + if (indices instanceof Uint32Array) { + return indices; + } + else { + // number[] or Int32Array, check if 32 bit is necessary + for (var index = 0; index < indices.length; index++) { + if (indices[index] > 65535) { + return new Uint32Array(indices); + } + } + return new Uint16Array(indices); + } + } + // No 32 bit support, force conversion to 16 bit (values greater 16 bit are lost) + return new Uint16Array(indices); + }; + /** + * Bind a webGL buffer to the webGL context + * @param buffer defines the buffer to bind + */ + Engine.prototype.bindArrayBuffer = function (buffer) { + if (!this._vaoRecordInProgress) { + this._unbindVertexArrayObject(); + } + this.bindBuffer(buffer, this._gl.ARRAY_BUFFER); + }; + /** + * Bind an uniform buffer to the current webGL context + * @param buffer defines the buffer to bind + */ + Engine.prototype.bindUniformBuffer = function (buffer) { + this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer ? buffer.underlyingResource : null); + }; + /** + * Bind a buffer to the current webGL context at a given location + * @param buffer defines the buffer to bind + * @param location defines the index where to bind the buffer + */ + Engine.prototype.bindUniformBufferBase = function (buffer, location) { + this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer ? buffer.underlyingResource : null); + }; + /** + * Bind a specific block at a given index in a specific shader program + * @param pipelineContext defines the pipeline context to use + * @param blockName defines the block name + * @param index defines the index where to bind the block + */ + Engine.prototype.bindUniformBlock = function (pipelineContext, blockName, index) { + var program = pipelineContext.program; + var uniformLocation = this._gl.getUniformBlockIndex(program, blockName); + this._gl.uniformBlockBinding(program, uniformLocation, index); + }; + Engine.prototype.bindIndexBuffer = function (buffer) { + if (!this._vaoRecordInProgress) { + this._unbindVertexArrayObject(); + } + this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER); + }; + Engine.prototype.bindBuffer = function (buffer, target) { + if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) { + this._gl.bindBuffer(target, buffer ? buffer.underlyingResource : null); + this._currentBoundBuffer[target] = buffer; + } + }; + /** + * update the bound buffer with the given data + * @param data defines the data to update + */ + Engine.prototype.updateArrayBuffer = function (data) { + this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data); + }; + Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) { + var pointer = this._currentBufferPointers[indx]; + var changed = false; + if (!pointer.active) { + changed = true; + pointer.active = true; + pointer.index = indx; + pointer.size = size; + pointer.type = type; + pointer.normalized = normalized; + pointer.stride = stride; + pointer.offset = offset; + pointer.buffer = buffer; + } + else { + if (pointer.buffer !== buffer) { + pointer.buffer = buffer; + changed = true; + } + if (pointer.size !== size) { + pointer.size = size; + changed = true; + } + if (pointer.type !== type) { + pointer.type = type; + changed = true; + } + if (pointer.normalized !== normalized) { + pointer.normalized = normalized; + changed = true; + } + if (pointer.stride !== stride) { + pointer.stride = stride; + changed = true; + } + if (pointer.offset !== offset) { + pointer.offset = offset; + changed = true; + } + } + if (changed || this._vaoRecordInProgress) { + this.bindArrayBuffer(buffer); + this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset); + } + }; + Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) { + if (indexBuffer == null) { + return; + } + if (this._cachedIndexBuffer !== indexBuffer) { + this._cachedIndexBuffer = indexBuffer; + this.bindIndexBuffer(indexBuffer); + this._uintIndicesCurrentlySet = indexBuffer.is32Bits; + } + }; + Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) { + var attributes = effect.getAttributesNames(); + if (!this._vaoRecordInProgress) { + this._unbindVertexArrayObject(); + } + this.unbindAllAttributes(); + for (var index = 0; index < attributes.length; index++) { + var order = effect.getAttributeLocation(index); + if (order >= 0) { + var vertexBuffer = vertexBuffers[attributes[index]]; + if (!vertexBuffer) { + continue; + } + this._gl.enableVertexAttribArray(order); + if (!this._vaoRecordInProgress) { + this._vertexAttribArraysEnabled[order] = true; + } + var buffer = vertexBuffer.getBuffer(); + if (buffer) { + this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset); + if (vertexBuffer.getIsInstanced()) { + this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor()); + if (!this._vaoRecordInProgress) { + this._currentInstanceLocations.push(order); + this._currentInstanceBuffers.push(buffer); + } + } + } + } + } + }; + /** + * Records a vertex array object + * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects + * @param vertexBuffers defines the list of vertex buffers to store + * @param indexBuffer defines the index buffer to store + * @param effect defines the effect to store + * @returns the new vertex array object + */ + Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) { + var vao = this._gl.createVertexArray(); + this._vaoRecordInProgress = true; + this._gl.bindVertexArray(vao); + this._mustWipeVertexAttributes = true; + this._bindVertexBuffersAttributes(vertexBuffers, effect); + this.bindIndexBuffer(indexBuffer); + this._vaoRecordInProgress = false; + this._gl.bindVertexArray(null); + return vao; + }; + /** + * Bind a specific vertex array object + * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects + * @param vertexArrayObject defines the vertex array object to bind + * @param indexBuffer defines the index buffer to bind + */ + Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) { + if (this._cachedVertexArrayObject !== vertexArrayObject) { + this._cachedVertexArrayObject = vertexArrayObject; + this._gl.bindVertexArray(vertexArrayObject); + this._cachedVertexBuffers = null; + this._cachedIndexBuffer = null; + this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits; + this._mustWipeVertexAttributes = true; + } + }; + /** + * Bind webGl buffers directly to the webGL context + * @param vertexBuffer defines the vertex buffer to bind + * @param indexBuffer defines the index buffer to bind + * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer + * @param vertexStrideSize defines the vertex stride of the vertex buffer + * @param effect defines the effect associated with the vertex buffer + */ + Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) { + if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) { + this._cachedVertexBuffers = vertexBuffer; + this._cachedEffectForVertexBuffers = effect; + var attributesCount = effect.getAttributesCount(); + this._unbindVertexArrayObject(); + this.unbindAllAttributes(); + var offset = 0; + for (var index = 0; index < attributesCount; index++) { + if (index < vertexDeclaration.length) { + var order = effect.getAttributeLocation(index); + if (order >= 0) { + this._gl.enableVertexAttribArray(order); + this._vertexAttribArraysEnabled[order] = true; + this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset); + } + offset += vertexDeclaration[index] * 4; + } + } + } + this._bindIndexBufferWithCache(indexBuffer); + }; + Engine.prototype._unbindVertexArrayObject = function () { + if (!this._cachedVertexArrayObject) { + return; + } + this._cachedVertexArrayObject = null; + this._gl.bindVertexArray(null); + }; + /** + * Bind a list of vertex buffers to the webGL context + * @param vertexBuffers defines the list of vertex buffers to bind + * @param indexBuffer defines the index buffer to bind + * @param effect defines the effect associated with the vertex buffers + */ + Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) { + if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) { + this._cachedVertexBuffers = vertexBuffers; + this._cachedEffectForVertexBuffers = effect; + this._bindVertexBuffersAttributes(vertexBuffers, effect); + } + this._bindIndexBufferWithCache(indexBuffer); + }; + /** + * Unbind all instance attributes + */ + Engine.prototype.unbindInstanceAttributes = function () { + var boundBuffer; + for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) { + var instancesBuffer = this._currentInstanceBuffers[i]; + if (boundBuffer != instancesBuffer && instancesBuffer.references) { + boundBuffer = instancesBuffer; + this.bindArrayBuffer(instancesBuffer); + } + var offsetLocation = this._currentInstanceLocations[i]; + this._gl.vertexAttribDivisor(offsetLocation, 0); + } + this._currentInstanceBuffers.length = 0; + this._currentInstanceLocations.length = 0; + }; + /** + * Release and free the memory of a vertex array object + * @param vao defines the vertex array object to delete + */ + Engine.prototype.releaseVertexArrayObject = function (vao) { + this._gl.deleteVertexArray(vao); + }; + /** @hidden */ + Engine.prototype._releaseBuffer = function (buffer) { + buffer.references--; + if (buffer.references === 0) { + this._deleteBuffer(buffer); + return true; + } + return false; + }; + Engine.prototype._deleteBuffer = function (buffer) { + this._gl.deleteBuffer(buffer.underlyingResource); + }; + /** + * Creates a webGL buffer to use with instanciation + * @param capacity defines the size of the buffer + * @returns the webGL buffer + */ + Engine.prototype.createInstancesBuffer = function (capacity) { + var buffer = this._gl.createBuffer(); + if (!buffer) { + throw new Error("Unable to create instance buffer"); + } + var result = new _Meshes_WebGL_webGLDataBuffer__WEBPACK_IMPORTED_MODULE_18__["WebGLDataBuffer"](buffer); + result.capacity = capacity; + this.bindArrayBuffer(result); + this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW); + return result; + }; + /** + * Delete a webGL buffer used with instanciation + * @param buffer defines the webGL buffer to delete + */ + Engine.prototype.deleteInstancesBuffer = function (buffer) { + this._gl.deleteBuffer(buffer); + }; + /** + * Update the content of a webGL buffer used with instanciation and bind it to the webGL context + * @param instancesBuffer defines the webGL buffer to update and bind + * @param data defines the data to store in the buffer + * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer + */ + Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) { + this.bindArrayBuffer(instancesBuffer); + if (data) { + this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data); + } + if (offsetLocations[0].index !== undefined) { + var stride = 0; + for (var i = 0; i < offsetLocations.length; i++) { + var ai = offsetLocations[i]; + stride += ai.attributeSize * 4; + } + for (var i = 0; i < offsetLocations.length; i++) { + var ai = offsetLocations[i]; + if (!this._vertexAttribArraysEnabled[ai.index]) { + this._gl.enableVertexAttribArray(ai.index); + this._vertexAttribArraysEnabled[ai.index] = true; + } + this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset); + this._gl.vertexAttribDivisor(ai.index, 1); + this._currentInstanceLocations.push(ai.index); + this._currentInstanceBuffers.push(instancesBuffer); + } + } + else { + for (var index = 0; index < 4; index++) { + var offsetLocation = offsetLocations[index]; + if (!this._vertexAttribArraysEnabled[offsetLocation]) { + this._gl.enableVertexAttribArray(offsetLocation); + this._vertexAttribArraysEnabled[offsetLocation] = true; + } + this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16); + this._gl.vertexAttribDivisor(offsetLocation, 1); + this._currentInstanceLocations.push(offsetLocation); + this._currentInstanceBuffers.push(instancesBuffer); + } + } + }; + /** + * Apply all cached states (depth, culling, stencil and alpha) + */ + Engine.prototype.applyStates = function () { + this._depthCullingState.apply(this._gl); + this._stencilState.apply(this._gl); + this._alphaState.apply(this._gl); + }; + /** + * Send a draw order + * @param useTriangles defines if triangles must be used to draw (else wireframe will be used) + * @param indexStart defines the starting index + * @param indexCount defines the number of index to draw + * @param instancesCount defines the number of instances to draw (if instanciation is enabled) + */ + Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) { + this.drawElementsType(useTriangles ? _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].MATERIAL_TriangleFillMode : _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].MATERIAL_WireFrameFillMode, indexStart, indexCount, instancesCount); + }; + /** + * Draw a list of points + * @param verticesStart defines the index of first vertex to draw + * @param verticesCount defines the count of vertices to draw + * @param instancesCount defines the number of instances to draw (if instanciation is enabled) + */ + Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) { + this.drawArraysType(_constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].MATERIAL_PointFillMode, verticesStart, verticesCount, instancesCount); + }; + /** + * Draw a list of unindexed primitives + * @param useTriangles defines if triangles must be used to draw (else wireframe will be used) + * @param verticesStart defines the index of first vertex to draw + * @param verticesCount defines the count of vertices to draw + * @param instancesCount defines the number of instances to draw (if instanciation is enabled) + */ + Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) { + this.drawArraysType(useTriangles ? _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].MATERIAL_TriangleFillMode : _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].MATERIAL_WireFrameFillMode, verticesStart, verticesCount, instancesCount); + }; + /** + * Draw a list of indexed primitives + * @param fillMode defines the primitive to use + * @param indexStart defines the starting index + * @param indexCount defines the number of index to draw + * @param instancesCount defines the number of instances to draw (if instanciation is enabled) + */ + Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) { + // Apply states + this.applyStates(); + this._drawCalls.addCount(1, false); + // Render + var drawMode = this._drawMode(fillMode); + var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT; + var mult = this._uintIndicesCurrentlySet ? 4 : 2; + if (instancesCount) { + this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount); + } + else { + this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult); + } + }; + /** + * Draw a list of unindexed primitives + * @param fillMode defines the primitive to use + * @param verticesStart defines the index of first vertex to draw + * @param verticesCount defines the count of vertices to draw + * @param instancesCount defines the number of instances to draw (if instanciation is enabled) + */ + Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) { + // Apply states + this.applyStates(); + this._drawCalls.addCount(1, false); + var drawMode = this._drawMode(fillMode); + if (instancesCount) { + this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount); + } + else { + this._gl.drawArrays(drawMode, verticesStart, verticesCount); + } + }; + Engine.prototype._drawMode = function (fillMode) { + switch (fillMode) { + // Triangle views + case _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].MATERIAL_TriangleFillMode: + return this._gl.TRIANGLES; + case _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].MATERIAL_PointFillMode: + return this._gl.POINTS; + case _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].MATERIAL_WireFrameFillMode: + return this._gl.LINES; + // Draw modes + case _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].MATERIAL_PointListDrawMode: + return this._gl.POINTS; + case _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].MATERIAL_LineListDrawMode: + return this._gl.LINES; + case _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].MATERIAL_LineLoopDrawMode: + return this._gl.LINE_LOOP; + case _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].MATERIAL_LineStripDrawMode: + return this._gl.LINE_STRIP; + case _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].MATERIAL_TriangleStripDrawMode: + return this._gl.TRIANGLE_STRIP; + case _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].MATERIAL_TriangleFanDrawMode: + return this._gl.TRIANGLE_FAN; + default: + return this._gl.TRIANGLES; + } + }; + // Shaders + /** @hidden */ + Engine.prototype._releaseEffect = function (effect) { + if (this._compiledEffects[effect._key]) { + delete this._compiledEffects[effect._key]; + this._deletePipelineContext(effect.getPipelineContext()); + } + }; + /** @hidden */ + Engine.prototype._deletePipelineContext = function (pipelineContext) { + var webGLPipelineContext = pipelineContext; + if (webGLPipelineContext && webGLPipelineContext.program) { + webGLPipelineContext.program.__SPECTOR_rebuildProgram = null; + if (webGLPipelineContext.transformFeedback) { + this.deleteTransformFeedback(webGLPipelineContext.transformFeedback); + webGLPipelineContext.transformFeedback = null; + } + this._gl.deleteProgram(webGLPipelineContext.program); + } + }; + /** + * Create a new effect (used to store vertex/fragment shaders) + * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx) + * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object + * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use + * @param samplers defines an array of string used to represent textures + * @param defines defines the string containing the defines to use to compile the shaders + * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails + * @param onCompiled defines a function to call when the effect creation is successful + * @param onError defines a function to call when the effect creation has failed + * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights) + * @returns the new Effect + */ + Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) { + var vertex = baseName.vertexElement || baseName.vertex || baseName; + var fragment = baseName.fragmentElement || baseName.fragment || baseName; + var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines); + if (this._compiledEffects[name]) { + var compiledEffect = this._compiledEffects[name]; + if (onCompiled && compiledEffect.isReady()) { + onCompiled(compiledEffect); + } + return compiledEffect; + } + var effect = new _Materials_effect__WEBPACK_IMPORTED_MODULE_8__["Effect"](baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters); + effect._key = name; + this._compiledEffects[name] = effect; + return effect; + }; + Engine._concatenateShader = function (source, defines, shaderVersion) { + return shaderVersion + (defines ? defines + "\n" : "") + source; + }; + Engine.prototype._compileShader = function (source, type, defines, shaderVersion) { + return this._compileRawShader(Engine._concatenateShader(source, defines, shaderVersion), type); + }; + Engine.prototype._compileRawShader = function (source, type) { + var gl = this._gl; + var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER); + if (!shader) { + throw new Error("Something went wrong while compile the shader."); + } + gl.shaderSource(shader, source); + gl.compileShader(shader); + return shader; + }; + /** + * Directly creates a webGL program + * @param pipelineContext defines the pipeline context to attach to + * @param vertexCode defines the vertex shader code to use + * @param fragmentCode defines the fragment shader code to use + * @param context defines the webGL context to use (if not set, the current one will be used) + * @param transformFeedbackVaryings defines the list of transform feedback varyings to use + * @returns the new webGL program + */ + Engine.prototype.createRawShaderProgram = function (pipelineContext, vertexCode, fragmentCode, context, transformFeedbackVaryings) { + if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; } + context = context || this._gl; + var vertexShader = this._compileRawShader(vertexCode, "vertex"); + var fragmentShader = this._compileRawShader(fragmentCode, "fragment"); + return this._createShaderProgram(pipelineContext, vertexShader, fragmentShader, context, transformFeedbackVaryings); + }; + /** + * Creates a webGL program + * @param pipelineContext defines the pipeline context to attach to + * @param vertexCode defines the vertex shader code to use + * @param fragmentCode defines the fragment shader code to use + * @param defines defines the string containing the defines to use to compile the shaders + * @param context defines the webGL context to use (if not set, the current one will be used) + * @param transformFeedbackVaryings defines the list of transform feedback varyings to use + * @returns the new webGL program + */ + Engine.prototype.createShaderProgram = function (pipelineContext, vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) { + if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; } + context = context || this._gl; + this.onBeforeShaderCompilationObservable.notifyObservers(this); + var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : ""; + var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion); + var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion); + var program = this._createShaderProgram(pipelineContext, vertexShader, fragmentShader, context, transformFeedbackVaryings); + this.onAfterShaderCompilationObservable.notifyObservers(this); + return program; + }; + /** + * Creates a new pipeline context + * @returns the new pipeline + */ + Engine.prototype.createPipelineContext = function () { + var pipelineContext = new _WebGL_webGLPipelineContext__WEBPACK_IMPORTED_MODULE_17__["WebGLPipelineContext"](); + pipelineContext.engine = this; + if (this._caps.parallelShaderCompile) { + pipelineContext.isParallelCompiled = true; + } + return pipelineContext; + }; + Engine.prototype._createShaderProgram = function (pipelineContext, vertexShader, fragmentShader, context, transformFeedbackVaryings) { + if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; } + var shaderProgram = context.createProgram(); + pipelineContext.program = shaderProgram; + if (!shaderProgram) { + throw new Error("Unable to create program"); + } + context.attachShader(shaderProgram, vertexShader); + context.attachShader(shaderProgram, fragmentShader); + if (this.webGLVersion > 1 && transformFeedbackVaryings) { + var transformFeedback = this.createTransformFeedback(); + this.bindTransformFeedback(transformFeedback); + this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings); + pipelineContext.transformFeedback = transformFeedback; + } + context.linkProgram(shaderProgram); + if (this.webGLVersion > 1 && transformFeedbackVaryings) { + this.bindTransformFeedback(null); + } + pipelineContext.context = context; + pipelineContext.vertexShader = vertexShader; + pipelineContext.fragmentShader = fragmentShader; + if (!pipelineContext.isParallelCompiled) { + this._finalizePipelineContext(pipelineContext); + } + return shaderProgram; + }; + Engine.prototype._finalizePipelineContext = function (pipelineContext) { + var context = pipelineContext.context; + var vertexShader = pipelineContext.vertexShader; + var fragmentShader = pipelineContext.fragmentShader; + var program = pipelineContext.program; + var linked = context.getProgramParameter(program, context.LINK_STATUS); + if (!linked) { // Get more info + // Vertex + if (!this._gl.getShaderParameter(vertexShader, this._gl.COMPILE_STATUS)) { + var log = this._gl.getShaderInfoLog(vertexShader); + if (log) { + throw new Error(log); + } + } + // Fragment + if (!this._gl.getShaderParameter(fragmentShader, this._gl.COMPILE_STATUS)) { + var log = this._gl.getShaderInfoLog(fragmentShader); + if (log) { + throw new Error(log); + } + } + var error = context.getProgramInfoLog(program); + if (error) { + throw new Error(error); + } + } + if (this.validateShaderPrograms) { + context.validateProgram(program); + var validated = context.getProgramParameter(program, context.VALIDATE_STATUS); + if (!validated) { + var error = context.getProgramInfoLog(program); + if (error) { + throw new Error(error); + } + } + } + context.deleteShader(vertexShader); + context.deleteShader(fragmentShader); + pipelineContext.vertexShader = undefined; + pipelineContext.fragmentShader = undefined; + if (pipelineContext.onCompiled) { + pipelineContext.onCompiled(); + pipelineContext.onCompiled = undefined; + } + }; + /** @hidden */ + Engine.prototype._preparePipelineContext = function (pipelineContext, vertexSourceCode, fragmentSourceCode, createAsRaw, rebuildRebind, defines, transformFeedbackVaryings) { + var webGLRenderingState = pipelineContext; + if (createAsRaw) { + webGLRenderingState.program = this.createRawShaderProgram(webGLRenderingState, vertexSourceCode, fragmentSourceCode, undefined, transformFeedbackVaryings); + } + else { + webGLRenderingState.program = this.createShaderProgram(webGLRenderingState, vertexSourceCode, fragmentSourceCode, defines, undefined, transformFeedbackVaryings); + } + webGLRenderingState.program.__SPECTOR_rebuildProgram = rebuildRebind; + }; + /** @hidden */ + Engine.prototype._isRenderingStateCompiled = function (pipelineContext) { + var webGLPipelineContext = pipelineContext; + if (this._gl.getProgramParameter(webGLPipelineContext.program, this._caps.parallelShaderCompile.COMPLETION_STATUS_KHR)) { + this._finalizePipelineContext(webGLPipelineContext); + return true; + } + return false; + }; + /** @hidden */ + Engine.prototype._executeWhenRenderingStateIsCompiled = function (pipelineContext, action) { + var webGLPipelineContext = pipelineContext; + if (!webGLPipelineContext.isParallelCompiled) { + action(); + return; + } + webGLPipelineContext.onCompiled = action; + }; + /** + * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names + * @param pipelineContext defines the pipeline context to use + * @param uniformsNames defines the list of uniform names + * @returns an array of webGL uniform locations + */ + Engine.prototype.getUniforms = function (pipelineContext, uniformsNames) { + var results = new Array(); + var webGLPipelineContext = pipelineContext; + for (var index = 0; index < uniformsNames.length; index++) { + results.push(this._gl.getUniformLocation(webGLPipelineContext.program, uniformsNames[index])); + } + return results; + }; + /** + * Gets the lsit of active attributes for a given webGL program + * @param pipelineContext defines the pipeline context to use + * @param attributesNames defines the list of attribute names to get + * @returns an array of indices indicating the offset of each attribute + */ + Engine.prototype.getAttributes = function (pipelineContext, attributesNames) { + var results = []; + var webGLPipelineContext = pipelineContext; + for (var index = 0; index < attributesNames.length; index++) { + try { + results.push(this._gl.getAttribLocation(webGLPipelineContext.program, attributesNames[index])); + } + catch (e) { + results.push(-1); + } + } + return results; + }; + /** + * Activates an effect, mkaing it the current one (ie. the one used for rendering) + * @param effect defines the effect to activate + */ + Engine.prototype.enableEffect = function (effect) { + if (!effect || effect === this._currentEffect) { + return; + } + // Use program + this.bindSamplers(effect); + this._currentEffect = effect; + if (effect.onBind) { + effect.onBind(effect); + } + if (effect._onBindObservable) { + effect._onBindObservable.notifyObservers(effect); + } + }; + /** + * Set the value of an uniform to an array of int32 + * @param uniform defines the webGL uniform location where to store the value + * @param array defines the array of int32 to store + */ + Engine.prototype.setIntArray = function (uniform, array) { + if (!uniform) { + return; + } + this._gl.uniform1iv(uniform, array); + }; + /** + * Set the value of an uniform to an array of int32 (stored as vec2) + * @param uniform defines the webGL uniform location where to store the value + * @param array defines the array of int32 to store + */ + Engine.prototype.setIntArray2 = function (uniform, array) { + if (!uniform || array.length % 2 !== 0) { + return; + } + this._gl.uniform2iv(uniform, array); + }; + /** + * Set the value of an uniform to an array of int32 (stored as vec3) + * @param uniform defines the webGL uniform location where to store the value + * @param array defines the array of int32 to store + */ + Engine.prototype.setIntArray3 = function (uniform, array) { + if (!uniform || array.length % 3 !== 0) { + return; + } + this._gl.uniform3iv(uniform, array); + }; + /** + * Set the value of an uniform to an array of int32 (stored as vec4) + * @param uniform defines the webGL uniform location where to store the value + * @param array defines the array of int32 to store + */ + Engine.prototype.setIntArray4 = function (uniform, array) { + if (!uniform || array.length % 4 !== 0) { + return; + } + this._gl.uniform4iv(uniform, array); + }; + /** + * Set the value of an uniform to an array of float32 + * @param uniform defines the webGL uniform location where to store the value + * @param array defines the array of float32 to store + */ + Engine.prototype.setFloatArray = function (uniform, array) { + if (!uniform) { + return; + } + this._gl.uniform1fv(uniform, array); + }; + /** + * Set the value of an uniform to an array of float32 (stored as vec2) + * @param uniform defines the webGL uniform location where to store the value + * @param array defines the array of float32 to store + */ + Engine.prototype.setFloatArray2 = function (uniform, array) { + if (!uniform || array.length % 2 !== 0) { + return; + } + this._gl.uniform2fv(uniform, array); + }; + /** + * Set the value of an uniform to an array of float32 (stored as vec3) + * @param uniform defines the webGL uniform location where to store the value + * @param array defines the array of float32 to store + */ + Engine.prototype.setFloatArray3 = function (uniform, array) { + if (!uniform || array.length % 3 !== 0) { + return; + } + this._gl.uniform3fv(uniform, array); + }; + /** + * Set the value of an uniform to an array of float32 (stored as vec4) + * @param uniform defines the webGL uniform location where to store the value + * @param array defines the array of float32 to store + */ + Engine.prototype.setFloatArray4 = function (uniform, array) { + if (!uniform || array.length % 4 !== 0) { + return; + } + this._gl.uniform4fv(uniform, array); + }; + /** + * Set the value of an uniform to an array of number + * @param uniform defines the webGL uniform location where to store the value + * @param array defines the array of number to store + */ + Engine.prototype.setArray = function (uniform, array) { + if (!uniform) { + return; + } + this._gl.uniform1fv(uniform, array); + }; + /** + * Set the value of an uniform to an array of number (stored as vec2) + * @param uniform defines the webGL uniform location where to store the value + * @param array defines the array of number to store + */ + Engine.prototype.setArray2 = function (uniform, array) { + if (!uniform || array.length % 2 !== 0) { + return; + } + this._gl.uniform2fv(uniform, array); + }; + /** + * Set the value of an uniform to an array of number (stored as vec3) + * @param uniform defines the webGL uniform location where to store the value + * @param array defines the array of number to store + */ + Engine.prototype.setArray3 = function (uniform, array) { + if (!uniform || array.length % 3 !== 0) { + return; + } + this._gl.uniform3fv(uniform, array); + }; + /** + * Set the value of an uniform to an array of number (stored as vec4) + * @param uniform defines the webGL uniform location where to store the value + * @param array defines the array of number to store + */ + Engine.prototype.setArray4 = function (uniform, array) { + if (!uniform || array.length % 4 !== 0) { + return; + } + this._gl.uniform4fv(uniform, array); + }; + /** + * Set the value of an uniform to an array of float32 (stored as matrices) + * @param uniform defines the webGL uniform location where to store the value + * @param matrices defines the array of float32 to store + */ + Engine.prototype.setMatrices = function (uniform, matrices) { + if (!uniform) { + return; + } + this._gl.uniformMatrix4fv(uniform, false, matrices); + }; + /** + * Set the value of an uniform to a matrix + * @param uniform defines the webGL uniform location where to store the value + * @param matrix defines the matrix to store + */ + Engine.prototype.setMatrix = function (uniform, matrix) { + if (!uniform) { + return; + } + this._gl.uniformMatrix4fv(uniform, false, matrix.toArray()); + }; + /** + * Set the value of an uniform to a matrix (3x3) + * @param uniform defines the webGL uniform location where to store the value + * @param matrix defines the Float32Array representing the 3x3 matrix to store + */ + Engine.prototype.setMatrix3x3 = function (uniform, matrix) { + if (!uniform) { + return; + } + this._gl.uniformMatrix3fv(uniform, false, matrix); + }; + /** + * Set the value of an uniform to a matrix (2x2) + * @param uniform defines the webGL uniform location where to store the value + * @param matrix defines the Float32Array representing the 2x2 matrix to store + */ + Engine.prototype.setMatrix2x2 = function (uniform, matrix) { + if (!uniform) { + return; + } + this._gl.uniformMatrix2fv(uniform, false, matrix); + }; + /** + * Set the value of an uniform to a number (int) + * @param uniform defines the webGL uniform location where to store the value + * @param value defines the int number to store + */ + Engine.prototype.setInt = function (uniform, value) { + if (!uniform) { + return; + } + this._gl.uniform1i(uniform, value); + }; + /** + * Set the value of an uniform to a number (float) + * @param uniform defines the webGL uniform location where to store the value + * @param value defines the float number to store + */ + Engine.prototype.setFloat = function (uniform, value) { + if (!uniform) { + return; + } + this._gl.uniform1f(uniform, value); + }; + /** + * Set the value of an uniform to a vec2 + * @param uniform defines the webGL uniform location where to store the value + * @param x defines the 1st component of the value + * @param y defines the 2nd component of the value + */ + Engine.prototype.setFloat2 = function (uniform, x, y) { + if (!uniform) { + return; + } + this._gl.uniform2f(uniform, x, y); + }; + /** + * Set the value of an uniform to a vec3 + * @param uniform defines the webGL uniform location where to store the value + * @param x defines the 1st component of the value + * @param y defines the 2nd component of the value + * @param z defines the 3rd component of the value + */ + Engine.prototype.setFloat3 = function (uniform, x, y, z) { + if (!uniform) { + return; + } + this._gl.uniform3f(uniform, x, y, z); + }; + /** + * Set the value of an uniform to a boolean + * @param uniform defines the webGL uniform location where to store the value + * @param bool defines the boolean to store + */ + Engine.prototype.setBool = function (uniform, bool) { + if (!uniform) { + return; + } + this._gl.uniform1i(uniform, bool); + }; + /** + * Set the value of an uniform to a vec4 + * @param uniform defines the webGL uniform location where to store the value + * @param x defines the 1st component of the value + * @param y defines the 2nd component of the value + * @param z defines the 3rd component of the value + * @param w defines the 4th component of the value + */ + Engine.prototype.setFloat4 = function (uniform, x, y, z, w) { + if (!uniform) { + return; + } + this._gl.uniform4f(uniform, x, y, z, w); + }; + /** + * Set the value of an uniform to a Color3 + * @param uniform defines the webGL uniform location where to store the value + * @param color3 defines the color to store + */ + Engine.prototype.setColor3 = function (uniform, color3) { + if (!uniform) { + return; + } + this._gl.uniform3f(uniform, color3.r, color3.g, color3.b); + }; + /** + * Set the value of an uniform to a Color3 and an alpha value + * @param uniform defines the webGL uniform location where to store the value + * @param color3 defines the color to store + * @param alpha defines the alpha component to store + */ + Engine.prototype.setColor4 = function (uniform, color3, alpha) { + if (!uniform) { + return; + } + this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha); + }; + /** + * Sets a Color4 on a uniform variable + * @param uniform defines the uniform location + * @param color4 defines the value to be set + */ + Engine.prototype.setDirectColor4 = function (uniform, color4) { + if (!uniform) { + return; + } + this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a); + }; + // States + /** + * Set various states to the webGL context + * @param culling defines backface culling state + * @param zOffset defines the value to apply to zOffset (0 by default) + * @param force defines if states must be applied even if cache is up to date + * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW) + */ + Engine.prototype.setState = function (culling, zOffset, force, reverseSide) { + if (zOffset === void 0) { zOffset = 0; } + if (reverseSide === void 0) { reverseSide = false; } + // Culling + if (this._depthCullingState.cull !== culling || force) { + this._depthCullingState.cull = culling; + } + // Cull face + var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT; + if (this._depthCullingState.cullFace !== cullFace || force) { + this._depthCullingState.cullFace = cullFace; + } + // Z offset + this.setZOffset(zOffset); + // Front face + var frontFace = reverseSide ? this._gl.CW : this._gl.CCW; + if (this._depthCullingState.frontFace !== frontFace || force) { + this._depthCullingState.frontFace = frontFace; + } + }; + /** + * Set the z offset to apply to current rendering + * @param value defines the offset to apply + */ + Engine.prototype.setZOffset = function (value) { + this._depthCullingState.zOffset = value; + }; + /** + * Gets the current value of the zOffset + * @returns the current zOffset state + */ + Engine.prototype.getZOffset = function () { + return this._depthCullingState.zOffset; + }; + /** + * Enable or disable depth buffering + * @param enable defines the state to set + */ + Engine.prototype.setDepthBuffer = function (enable) { + this._depthCullingState.depthTest = enable; + }; + /** + * Gets a boolean indicating if depth writing is enabled + * @returns the current depth writing state + */ + Engine.prototype.getDepthWrite = function () { + return this._depthCullingState.depthMask; + }; + /** + * Enable or disable depth writing + * @param enable defines the state to set + */ + Engine.prototype.setDepthWrite = function (enable) { + this._depthCullingState.depthMask = enable; + }; + /** + * Enable or disable color writing + * @param enable defines the state to set + */ + Engine.prototype.setColorWrite = function (enable) { + this._gl.colorMask(enable, enable, enable, enable); + this._colorWrite = enable; + }; + /** + * Gets a boolean indicating if color writing is enabled + * @returns the current color writing state + */ + Engine.prototype.getColorWrite = function () { + return this._colorWrite; + }; + /** + * Sets alpha constants used by some alpha blending modes + * @param r defines the red component + * @param g defines the green component + * @param b defines the blue component + * @param a defines the alpha component + */ + Engine.prototype.setAlphaConstants = function (r, g, b, a) { + this._alphaState.setAlphaBlendConstants(r, g, b, a); + }; + /** + * Sets the current alpha mode + * @param mode defines the mode to use (one of the Engine.ALPHA_XXX) + * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default) + * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered + */ + Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) { + if (noDepthWriteChange === void 0) { noDepthWriteChange = false; } + if (this._alphaMode === mode) { + return; + } + switch (mode) { + case Engine.ALPHA_DISABLE: + this._alphaState.alphaBlend = false; + break; + case Engine.ALPHA_PREMULTIPLIED: + this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE); + this._alphaState.alphaBlend = true; + break; + case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF: + this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA); + this._alphaState.alphaBlend = true; + break; + case Engine.ALPHA_COMBINE: + this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE); + this._alphaState.alphaBlend = true; + break; + case Engine.ALPHA_ONEONE: + this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE); + this._alphaState.alphaBlend = true; + break; + case Engine.ALPHA_ADD: + this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE); + this._alphaState.alphaBlend = true; + break; + case Engine.ALPHA_SUBTRACT: + this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE); + this._alphaState.alphaBlend = true; + break; + case Engine.ALPHA_MULTIPLY: + this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE); + this._alphaState.alphaBlend = true; + break; + case Engine.ALPHA_MAXIMIZED: + this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE); + this._alphaState.alphaBlend = true; + break; + case Engine.ALPHA_INTERPOLATE: + this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA); + this._alphaState.alphaBlend = true; + break; + case Engine.ALPHA_SCREENMODE: + this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA); + this._alphaState.alphaBlend = true; + break; + } + if (!noDepthWriteChange) { + this.setDepthWrite(mode === Engine.ALPHA_DISABLE); + } + this._alphaMode = mode; + }; + /** + * Gets the current alpha mode + * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered + * @returns the current alpha mode + */ + Engine.prototype.getAlphaMode = function () { + return this._alphaMode; + }; + // Textures + /** + * Clears the list of texture accessible through engine. + * This can help preventing texture load conflict due to name collision. + */ + Engine.prototype.clearInternalTexturesCache = function () { + this._internalTexturesCache = []; + }; + /** + * Force the entire cache to be cleared + * You should not have to use this function unless your engine needs to share the webGL context with another engine + * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states) + */ + Engine.prototype.wipeCaches = function (bruteForce) { + if (this.preventCacheWipeBetweenFrames && !bruteForce) { + return; + } + this._currentEffect = null; + this._viewportCached.x = 0; + this._viewportCached.y = 0; + this._viewportCached.z = 0; + this._viewportCached.w = 0; + if (bruteForce) { + this.resetTextureCache(); + this._currentProgram = null; + this._stencilState.reset(); + this._depthCullingState.reset(); + this.setDepthFunctionToLessOrEqual(); + this._alphaState.reset(); + this._unpackFlipYCached = null; + } + this._resetVertexBufferBinding(); + this._cachedIndexBuffer = null; + this._cachedEffectForVertexBuffers = null; + this._unbindVertexArrayObject(); + this.bindIndexBuffer(null); + }; + /** + * Set the compressed texture format to use, based on the formats you have, and the formats + * supported by the hardware / browser. + * + * Khronos Texture Container (.ktx) files are used to support this. This format has the + * advantage of being specifically designed for OpenGL. Header elements directly correspond + * to API arguments needed to compressed textures. This puts the burden on the container + * generator to house the arcane code for determining these for current & future formats. + * + * for description see https://www.khronos.org/opengles/sdk/tools/KTX/ + * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/ + * + * Note: The result of this call is not taken into account when a texture is base64. + * + * @param formatsAvailable defines the list of those format families you have created + * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.) + * + * Current families are astc, dxt, pvrtc, etc2, & etc1. + * @returns The extension selected. + */ + Engine.prototype.setTextureFormatToUse = function (formatsAvailable) { + for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) { + for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) { + if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) { + return this._textureFormatInUse = this._texturesSupported[i]; + } + } + } + // actively set format to nothing, to allow this to be called more than once + // and possibly fail the 2nd time + this._textureFormatInUse = null; + return null; + }; + /** @hidden */ + Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) { + var gl = this._gl; + var magFilter = gl.NEAREST; + var minFilter = gl.NEAREST; + switch (samplingMode) { + case Engine.TEXTURE_BILINEAR_SAMPLINGMODE: + magFilter = gl.LINEAR; + if (generateMipMaps) { + minFilter = gl.LINEAR_MIPMAP_NEAREST; + } + else { + minFilter = gl.LINEAR; + } + break; + case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE: + magFilter = gl.LINEAR; + if (generateMipMaps) { + minFilter = gl.LINEAR_MIPMAP_LINEAR; + } + else { + minFilter = gl.LINEAR; + } + break; + case Engine.TEXTURE_NEAREST_SAMPLINGMODE: + magFilter = gl.NEAREST; + if (generateMipMaps) { + minFilter = gl.NEAREST_MIPMAP_LINEAR; + } + else { + minFilter = gl.NEAREST; + } + break; + case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST: + magFilter = gl.NEAREST; + if (generateMipMaps) { + minFilter = gl.NEAREST_MIPMAP_NEAREST; + } + else { + minFilter = gl.NEAREST; + } + break; + case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST: + magFilter = gl.NEAREST; + if (generateMipMaps) { + minFilter = gl.LINEAR_MIPMAP_NEAREST; + } + else { + minFilter = gl.LINEAR; + } + break; + case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR: + magFilter = gl.NEAREST; + if (generateMipMaps) { + minFilter = gl.LINEAR_MIPMAP_LINEAR; + } + else { + minFilter = gl.LINEAR; + } + break; + case Engine.TEXTURE_NEAREST_LINEAR: + magFilter = gl.NEAREST; + minFilter = gl.LINEAR; + break; + case Engine.TEXTURE_NEAREST_NEAREST: + magFilter = gl.NEAREST; + minFilter = gl.NEAREST; + break; + case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST: + magFilter = gl.LINEAR; + if (generateMipMaps) { + minFilter = gl.NEAREST_MIPMAP_NEAREST; + } + else { + minFilter = gl.NEAREST; + } + break; + case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR: + magFilter = gl.LINEAR; + if (generateMipMaps) { + minFilter = gl.NEAREST_MIPMAP_LINEAR; + } + else { + minFilter = gl.NEAREST; + } + break; + case Engine.TEXTURE_LINEAR_LINEAR: + magFilter = gl.LINEAR; + minFilter = gl.LINEAR; + break; + case Engine.TEXTURE_LINEAR_NEAREST: + magFilter = gl.LINEAR; + minFilter = gl.NEAREST; + break; + } + return { + min: minFilter, + mag: magFilter + }; + }; + /** @hidden */ + Engine.prototype._createTexture = function () { + var texture = this._gl.createTexture(); + if (!texture) { + throw new Error("Unable to create texture"); + } + return texture; + }; + /** + * Usually called from Texture.ts. + * Passed information to create a WebGLTexture + * @param urlArg defines a value which contains one of the following: + * * A conventional http URL, e.g. 'http://...' or 'file://...' + * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...' + * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg' + * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file + * @param invertY when true, image is flipped when loaded. You probably want true. Certain compressed textures may invert this if their default is inverted (eg. ktx) + * @param scene needed for loading to the correct scene + * @param samplingMode mode with should be used sample / access the texture (Default: Texture.TRILINEAR_SAMPLINGMODE) + * @param onLoad optional callback to be called upon successful completion + * @param onError optional callback to be called upon failure + * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob + * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities + * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures + * @param forcedExtension defines the extension to use to pick the right loader + * @param excludeLoaders array of texture loaders that should be excluded when picking a loader for the texture (default: empty array) + * @returns a InternalTexture for assignment back into BABYLON.Texture + */ + Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension, excludeLoaders) { + var _this = this; + if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; } + if (onLoad === void 0) { onLoad = null; } + if (onError === void 0) { onError = null; } + if (buffer === void 0) { buffer = null; } + if (fallback === void 0) { fallback = null; } + if (format === void 0) { format = null; } + if (forcedExtension === void 0) { forcedExtension = null; } + if (excludeLoaders === void 0) { excludeLoaders = []; } + var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback + var fromData = url.substr(0, 5) === "data:"; + var fromBlob = url.substr(0, 5) === "blob:"; + var isBase64 = fromData && url.indexOf(";base64,") !== -1; + var texture = fallback ? fallback : new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_9__["InternalTexture"](this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_9__["InternalTexture"].DATASOURCE_URL); + // establish the file extension, if possible + var lastDot = url.lastIndexOf('.'); + var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : ""); + var loader = null; + for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) { + var availableLoader = _a[_i]; + if (excludeLoaders.indexOf(availableLoader) === -1 && availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) { + loader = availableLoader; + break; + } + } + if (loader) { + url = loader.transformUrl(url, this._textureFormatInUse); + } + if (scene) { + scene._addPendingData(texture); + } + texture.url = url; + texture.generateMipMaps = !noMipmap; + texture.samplingMode = samplingMode; + texture.invertY = invertY; + if (!this._doNotHandleContextLost) { + // Keep a link to the buffer only if we plan to handle context lost + texture._buffer = buffer; + } + var onLoadObserver = null; + if (onLoad && !fallback) { + onLoadObserver = texture.onLoadedObservable.add(onLoad); + } + if (!fallback) { + this._internalTexturesCache.push(texture); + } + var onInternalError = function (message, exception) { + if (scene) { + scene._removePendingData(texture); + } + var customFallback = false; + if (loader) { + var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse); + if (fallbackUrl) { + // Add Back + customFallback = true; + excludeLoaders.push(loader); + _Misc_tools__WEBPACK_IMPORTED_MODULE_5__["Tools"].Warn(loader.constructor.name + " failed when trying to load " + texture.url + ", falling back to the next supported loader"); + _this.createTexture(urlArg, noMipmap, texture.invertY, scene, samplingMode, null, onError, buffer, texture, undefined, undefined, excludeLoaders); + return; + } + } + if (!customFallback) { + if (onLoadObserver) { + texture.onLoadedObservable.remove(onLoadObserver); + } + if (_Misc_tools__WEBPACK_IMPORTED_MODULE_5__["Tools"].UseFallbackTexture) { + _this.createTexture(_Misc_tools__WEBPACK_IMPORTED_MODULE_5__["Tools"].fallbackTexture, noMipmap, texture.invertY, scene, samplingMode, null, onError, buffer, texture); + return; + } + } + if (onError) { + onError(message || "Unknown error", exception); + } + }; + // processing for non-image formats + if (loader) { + var callback = function (data) { + loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done, loadFailed) { + if (loadFailed) { + onInternalError("TextureLoader failed to load data"); + } + else { + _this._prepareWebGLTexture(texture, scene, width, height, texture.invertY, !loadMipmap, isCompressed, function () { + done(); + return false; + }, samplingMode); + } + }); + }; + if (!buffer) { + this._loadFile(url, callback, undefined, scene ? scene.offlineProvider : undefined, true, function (request, exception) { + onInternalError("Unable to load " + (request ? request.responseURL : url, exception)); + }); + } + else { + callback(buffer); + } + } + else { + var onload = function (img) { + if (fromBlob && !_this._doNotHandleContextLost) { + // We need to store the image if we need to rebuild the texture + // in case of a webgl context lost + texture._buffer = img; + } + _this._prepareWebGLTexture(texture, scene, img.width, img.height, texture.invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) { + var gl = _this._gl; + var isPot = (img.width === potWidth && img.height === potHeight); + var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA); + if (isPot) { + gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img); + return false; + } + var maxTextureSize = _this._caps.maxTextureSize; + if (img.width > maxTextureSize || img.height > maxTextureSize || Engine._RescalePostProcessFactory === null) { + _this._prepareWorkingCanvas(); + if (!_this._workingCanvas || !_this._workingContext) { + return false; + } + _this._workingCanvas.width = potWidth; + _this._workingCanvas.height = potHeight; + _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight); + gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas); + texture.width = potWidth; + texture.height = potHeight; + return false; + } + else { + // Using shaders when possible to rescale because canvas.drawImage is lossy + var source_1 = new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_9__["InternalTexture"](_this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_9__["InternalTexture"].DATASOURCE_TEMP); + _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true); + gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + _this._rescaleTexture(source_1, texture, scene, internalFormat, function () { + _this._releaseTexture(source_1); + _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true); + continuationCallback(); + }); + } + return true; + }, samplingMode); + }; + if (!fromData || isBase64) { + if (buffer instanceof HTMLImageElement) { + onload(buffer); + } + else { + _Misc_tools__WEBPACK_IMPORTED_MODULE_5__["Tools"].LoadImage(url, onload, onInternalError, scene ? scene.offlineProvider : null); + } + } + else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) { + _Misc_tools__WEBPACK_IMPORTED_MODULE_5__["Tools"].LoadImage(buffer, onload, onInternalError, scene ? scene.offlineProvider : null); + } + else { + onload(buffer); + } + } + return texture; + }; + Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) { + var _this = this; + var rtt = this.createRenderTargetTexture({ + width: destination.width, + height: destination.height, + }, { + generateMipMaps: false, + type: Engine.TEXTURETYPE_UNSIGNED_INT, + samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE, + generateDepthBuffer: false, + generateStencilBuffer: false + }); + if (!this._rescalePostProcess && Engine._RescalePostProcessFactory) { + this._rescalePostProcess = Engine._RescalePostProcessFactory(this); + } + this._rescalePostProcess.getEffect().executeWhenCompiled(function () { + _this._rescalePostProcess.onApply = function (effect) { + effect._bindTexture("textureSampler", source); + }; + var hostingScene = scene; + if (!hostingScene) { + hostingScene = _this.scenes[_this.scenes.length - 1]; + } + hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true); + _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true); + _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0); + _this.unBindFramebuffer(rtt); + _this._releaseTexture(rtt); + if (onComplete) { + onComplete(); + } + }); + }; + /** + * Creates a raw texture + * @param data defines the data to store in the texture + * @param width defines the width of the texture + * @param height defines the height of the texture + * @param format defines the format of the data + * @param generateMipMaps defines if the engine should generate the mip levels + * @param invertY defines if data must be stored with Y axis inverted + * @param samplingMode defines the required sampling mode (Texture.NEAREST_SAMPLINGMODE by default) + * @param compression defines the compression used (null by default) + * @param type defines the type fo the data (Engine.TEXTURETYPE_UNSIGNED_INT by default) + * @returns the raw texture inside an InternalTexture + */ + Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) { + if (compression === void 0) { compression = null; } + if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; } + throw _Misc_devTools__WEBPACK_IMPORTED_MODULE_16__["_DevTools"].WarnImport("Engine.RawTexture"); + }; + /** @hidden */ + Engine.prototype._unpackFlipY = function (value) { + if (this._unpackFlipYCached !== value) { + this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0); + if (this.enableUnpackFlipYCached) { + this._unpackFlipYCached = value; + } + } + }; + /** @hidden */ + Engine.prototype._getUnpackAlignement = function () { + return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT); + }; + /** + * Creates a dynamic texture + * @param width defines the width of the texture + * @param height defines the height of the texture + * @param generateMipMaps defines if the engine should generate the mip levels + * @param samplingMode defines the required sampling mode (Texture.NEAREST_SAMPLINGMODE by default) + * @returns the dynamic texture inside an InternalTexture + */ + Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) { + var texture = new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_9__["InternalTexture"](this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_9__["InternalTexture"].DATASOURCE_DYNAMIC); + texture.baseWidth = width; + texture.baseHeight = height; + if (generateMipMaps) { + width = this.needPOTTextures ? _Misc_tools__WEBPACK_IMPORTED_MODULE_5__["Tools"].GetExponentOfTwo(width, this._caps.maxTextureSize) : width; + height = this.needPOTTextures ? _Misc_tools__WEBPACK_IMPORTED_MODULE_5__["Tools"].GetExponentOfTwo(height, this._caps.maxTextureSize) : height; + } + // this.resetTextureCache(); + texture.width = width; + texture.height = height; + texture.isReady = false; + texture.generateMipMaps = generateMipMaps; + texture.samplingMode = samplingMode; + this.updateTextureSamplingMode(samplingMode, texture); + this._internalTexturesCache.push(texture); + return texture; + }; + /** + * Update the sampling mode of a given texture + * @param samplingMode defines the required sampling mode + * @param texture defines the texture to update + */ + Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) { + var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps); + if (texture.isCube) { + this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture); + this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min); + this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null); + } + else if (texture.is3D) { + this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture); + this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min); + this._bindTextureDirectly(this._gl.TEXTURE_3D, null); + } + else { + this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture); + this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min); + this._bindTextureDirectly(this._gl.TEXTURE_2D, null); + } + texture.samplingMode = samplingMode; + }; + /** + * Update the content of a dynamic texture + * @param texture defines the texture to update + * @param canvas defines the canvas containing the source + * @param invertY defines if data must be stored with Y axis inverted + * @param premulAlpha defines if alpha is stored as premultiplied + * @param format defines the format of the data + * @param forceBindTexture if the texture should be forced to be bound eg. after a graphics context loss (Default: false) + */ + Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format, forceBindTexture) { + if (premulAlpha === void 0) { premulAlpha = false; } + if (forceBindTexture === void 0) { forceBindTexture = false; } + if (!texture) { + return; + } + this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true, forceBindTexture); + this._unpackFlipY(invertY); + if (premulAlpha) { + this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1); + } + var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA; + this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas); + if (texture.generateMipMaps) { + this._gl.generateMipmap(this._gl.TEXTURE_2D); + } + this._bindTextureDirectly(this._gl.TEXTURE_2D, null); + if (premulAlpha) { + this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0); + } + texture.isReady = true; + }; + /** + * Update a video texture + * @param texture defines the texture to update + * @param video defines the video element to use + * @param invertY defines if data must be stored with Y axis inverted + */ + Engine.prototype.updateVideoTexture = function (texture, video, invertY) { + if (!texture || texture._isDisabled) { + return; + } + var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true); + this._unpackFlipY(!invertY); // Video are upside down by default + try { + // Testing video texture support + if (this._videoTextureSupported === undefined) { + this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video); + if (this._gl.getError() !== 0) { + this._videoTextureSupported = false; + } + else { + this._videoTextureSupported = true; + } + } + // Copy video through the current working canvas if video texture is not supported + if (!this._videoTextureSupported) { + if (!texture._workingCanvas) { + texture._workingCanvas = document.createElement("canvas"); + var context = texture._workingCanvas.getContext("2d"); + if (!context) { + throw new Error("Unable to get 2d context"); + } + texture._workingContext = context; + texture._workingCanvas.width = texture.width; + texture._workingCanvas.height = texture.height; + } + texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height); + this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas); + } + else { + this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video); + } + if (texture.generateMipMaps) { + this._gl.generateMipmap(this._gl.TEXTURE_2D); + } + if (!wasPreviouslyBound) { + this._bindTextureDirectly(this._gl.TEXTURE_2D, null); + } + // this.resetTextureCache(); + texture.isReady = true; + } + catch (ex) { + // Something unexpected + // Let's disable the texture + texture._isDisabled = true; + } + }; + /** + * Updates a depth texture Comparison Mode and Function. + * If the comparison Function is equal to 0, the mode will be set to none. + * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader. + * @param texture The texture to set the comparison function for + * @param comparisonFunction The comparison function to set, 0 if no comparison required + */ + Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) { + if (this.webGLVersion === 1) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_13__["Logger"].Error("WebGL 1 does not support texture comparison."); + return; + } + var gl = this._gl; + if (texture.isCube) { + this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true); + if (comparisonFunction === 0) { + gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL); + gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE); + } + else { + gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction); + gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE); + } + this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null); + } + else { + this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true); + if (comparisonFunction === 0) { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE); + } + else { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE); + } + this._bindTextureDirectly(this._gl.TEXTURE_2D, null); + } + texture._comparisonFunction = comparisonFunction; + }; + /** @hidden */ + Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) { + var width = size.width || size; + var height = size.height || size; + internalTexture.baseWidth = width; + internalTexture.baseHeight = height; + internalTexture.width = width; + internalTexture.height = height; + internalTexture.isReady = true; + internalTexture.samples = 1; + internalTexture.generateMipMaps = false; + internalTexture._generateDepthBuffer = true; + internalTexture._generateStencilBuffer = generateStencil; + internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE; + internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT; + internalTexture._comparisonFunction = comparisonFunction; + var gl = this._gl; + var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D; + var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false); + gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag); + gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min); + gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + if (comparisonFunction === 0) { + gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL); + gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE); + } + else { + gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction); + gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE); + } + }; + /** + * Creates a depth stencil texture. + * This is only available in WebGL 2 or with the depth texture extension available. + * @param size The size of face edge in the texture. + * @param options The options defining the texture. + * @returns The texture + */ + Engine.prototype.createDepthStencilTexture = function (size, options) { + if (options.isCube) { + var width = size.width || size; + return this._createDepthStencilCubeTexture(width, options); + } + else { + return this._createDepthStencilTexture(size, options); + } + }; + /** + * Creates a depth stencil texture. + * This is only available in WebGL 2 or with the depth texture extension available. + * @param size The size of face edge in the texture. + * @param options The options defining the texture. + * @returns The texture + */ + Engine.prototype._createDepthStencilTexture = function (size, options) { + var internalTexture = new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_9__["InternalTexture"](this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_9__["InternalTexture"].DATASOURCE_DEPTHTEXTURE); + if (!this._caps.depthTextureExtension) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_13__["Logger"].Error("Depth texture is not supported by your browser or hardware."); + return internalTexture; + } + var internalOptions = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options); + var gl = this._gl; + this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true); + this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction); + if (this.webGLVersion > 1) { + if (internalOptions.generateStencil) { + gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null); + } + else { + gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null); + } + } + else { + if (internalOptions.generateStencil) { + gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null); + } + else { + gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null); + } + } + this._bindTextureDirectly(gl.TEXTURE_2D, null); + return internalTexture; + }; + /** + * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture. + * @param renderTarget The render target to set the frame buffer for + */ + Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) { + // Create the framebuffer + var internalTexture = renderTarget.getInternalTexture(); + if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) { + return; + } + var gl = this._gl; + var depthStencilTexture = renderTarget.depthStencilTexture; + this._bindUnboundFramebuffer(internalTexture._framebuffer); + if (depthStencilTexture.isCube) { + if (depthStencilTexture._generateStencilBuffer) { + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0); + } + else { + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0); + } + } + else { + if (depthStencilTexture._generateStencilBuffer) { + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0); + } + else { + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0); + } + } + this._bindUnboundFramebuffer(null); + }; + /** + * Creates a new render target texture + * @param size defines the size of the texture + * @param options defines the options used to create the texture + * @returns a new render target texture stored in an InternalTexture + */ + Engine.prototype.createRenderTargetTexture = function (size, options) { + var fullOptions = new _Materials_Textures_renderTargetCreationOptions__WEBPACK_IMPORTED_MODULE_15__["RenderTargetCreationOptions"](); + if (options !== undefined && typeof options === "object") { + fullOptions.generateMipMaps = options.generateMipMaps; + fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer; + fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer; + fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type; + fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode; + fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format; + } + else { + fullOptions.generateMipMaps = options; + fullOptions.generateDepthBuffer = true; + fullOptions.generateStencilBuffer = false; + fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT; + fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; + fullOptions.format = Engine.TEXTUREFORMAT_RGBA; + } + if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) { + // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE + fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE; + } + else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) { + // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE + fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE; + } + var gl = this._gl; + var texture = new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_9__["InternalTexture"](this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_9__["InternalTexture"].DATASOURCE_RENDERTARGET); + this._bindTextureDirectly(gl.TEXTURE_2D, texture, true); + var width = size.width || size; + var height = size.height || size; + var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false); + if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) { + fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT; + _Misc_logger__WEBPACK_IMPORTED_MODULE_13__["Logger"].Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type"); + } + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null); + // Create the framebuffer + var currentFrameBuffer = this._currentFramebuffer; + var framebuffer = gl.createFramebuffer(); + this._bindUnboundFramebuffer(framebuffer); + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0); + texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height); + if (fullOptions.generateMipMaps) { + this._gl.generateMipmap(this._gl.TEXTURE_2D); + } + // Unbind + this._bindTextureDirectly(gl.TEXTURE_2D, null); + gl.bindRenderbuffer(gl.RENDERBUFFER, null); + this._bindUnboundFramebuffer(currentFrameBuffer); + texture._framebuffer = framebuffer; + texture.baseWidth = width; + texture.baseHeight = height; + texture.width = width; + texture.height = height; + texture.isReady = true; + texture.samples = 1; + texture.generateMipMaps = fullOptions.generateMipMaps ? true : false; + texture.samplingMode = fullOptions.samplingMode; + texture.type = fullOptions.type; + texture.format = fullOptions.format; + texture._generateDepthBuffer = fullOptions.generateDepthBuffer; + texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false; + // this.resetTextureCache(); + this._internalTexturesCache.push(texture); + return texture; + }; + /** @hidden */ + Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) { + if (samples === void 0) { samples = 1; } + var depthStencilBuffer = null; + var gl = this._gl; + // Create the depth/stencil buffer + if (generateStencilBuffer) { + depthStencilBuffer = gl.createRenderbuffer(); + gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer); + if (samples > 1) { + gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height); + } + else { + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height); + } + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer); + } + else if (generateDepthBuffer) { + depthStencilBuffer = gl.createRenderbuffer(); + gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer); + if (samples > 1) { + gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height); + } + else { + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height); + } + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer); + } + return depthStencilBuffer; + }; + /** + * Updates the sample count of a render target texture + * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets + * @param texture defines the texture to update + * @param samples defines the sample count to set + * @returns the effective sample count (could be 0 if multisample render targets are not supported) + */ + Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) { + if (this.webGLVersion < 2 || !texture) { + return 1; + } + if (texture.samples === samples) { + return samples; + } + var gl = this._gl; + samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES)); + // Dispose previous render buffers + if (texture._depthStencilBuffer) { + gl.deleteRenderbuffer(texture._depthStencilBuffer); + texture._depthStencilBuffer = null; + } + if (texture._MSAAFramebuffer) { + gl.deleteFramebuffer(texture._MSAAFramebuffer); + texture._MSAAFramebuffer = null; + } + if (texture._MSAARenderBuffer) { + gl.deleteRenderbuffer(texture._MSAARenderBuffer); + texture._MSAARenderBuffer = null; + } + if (samples > 1) { + var framebuffer = gl.createFramebuffer(); + if (!framebuffer) { + throw new Error("Unable to create multi sampled framebuffer"); + } + texture._MSAAFramebuffer = framebuffer; + this._bindUnboundFramebuffer(texture._MSAAFramebuffer); + var colorRenderbuffer = gl.createRenderbuffer(); + if (!colorRenderbuffer) { + throw new Error("Unable to create multi sampled framebuffer"); + } + gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer); + gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height); + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer); + texture._MSAARenderBuffer = colorRenderbuffer; + } + else { + this._bindUnboundFramebuffer(texture._framebuffer); + } + texture.samples = samples; + texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples); + gl.bindRenderbuffer(gl.RENDERBUFFER, null); + this._bindUnboundFramebuffer(null); + return samples; + }; + /** @hidden */ + Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) { + if (faceIndex === void 0) { faceIndex = 0; } + if (lod === void 0) { lod = 0; } + var gl = this._gl; + var target = gl.TEXTURE_2D; + if (texture.isCube) { + target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex; + } + this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data); + }; + /** @hidden */ + Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) { + if (faceIndex === void 0) { faceIndex = 0; } + if (lod === void 0) { lod = 0; } + var gl = this._gl; + var textureType = this._getWebGLTextureType(texture.type); + var format = this._getInternalFormat(texture.format); + var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format); + this._unpackFlipY(texture.invertY); + var target = gl.TEXTURE_2D; + if (texture.isCube) { + target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex; + } + var lodMaxWidth = Math.round(_Maths_math_scalar__WEBPACK_IMPORTED_MODULE_7__["Scalar"].Log2(texture.width)); + var lodMaxHeight = Math.round(_Maths_math_scalar__WEBPACK_IMPORTED_MODULE_7__["Scalar"].Log2(texture.height)); + var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0)); + var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0)); + gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData); + }; + /** @hidden */ + Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) { + if (faceIndex === void 0) { faceIndex = 0; } + if (lod === void 0) { lod = 0; } + var gl = this._gl; + var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D; + this._bindTextureDirectly(bindTarget, texture, true); + this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod); + this._bindTextureDirectly(bindTarget, null, true); + }; + /** @hidden */ + Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) { + if (faceIndex === void 0) { faceIndex = 0; } + if (lod === void 0) { lod = 0; } + var gl = this._gl; + var textureType = this._getWebGLTextureType(texture.type); + var format = this._getInternalFormat(texture.format); + var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format); + var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D; + this._bindTextureDirectly(bindTarget, texture, true); + this._unpackFlipY(texture.invertY); + var target = gl.TEXTURE_2D; + if (texture.isCube) { + target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex; + } + gl.texImage2D(target, lod, internalFormat, format, textureType, image); + this._bindTextureDirectly(bindTarget, null, true); + }; + /** + * @hidden + */ + Engine.prototype._setCubeMapTextureParams = function (loadMipmap) { + var gl = this._gl; + gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR); + gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null); + }; + /** + * Creates a new raw cube texture + * @param data defines the array of data to use to create each face + * @param size defines the size of the textures + * @param format defines the format of the data + * @param type defines the type of the data (like Engine.TEXTURETYPE_UNSIGNED_INT) + * @param generateMipMaps defines if the engine should generate the mip levels + * @param invertY defines if data must be stored with Y axis inverted + * @param samplingMode defines the required sampling mode (like Texture.NEAREST_SAMPLINGMODE) + * @param compression defines the compression used (null by default) + * @returns the cube texture as an InternalTexture + */ + Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) { + if (compression === void 0) { compression = null; } + throw _Misc_devTools__WEBPACK_IMPORTED_MODULE_16__["_DevTools"].WarnImport("Engine.RawTexture"); + }; + /** + * Creates a new raw 3D texture + * @param data defines the data used to create the texture + * @param width defines the width of the texture + * @param height defines the height of the texture + * @param depth defines the depth of the texture + * @param format defines the format of the texture + * @param generateMipMaps defines if the engine must generate mip levels + * @param invertY defines if data must be stored with Y axis inverted + * @param samplingMode defines the required sampling mode (like Texture.NEAREST_SAMPLINGMODE) + * @param compression defines the compressed used (can be null) + * @param textureType defines the compressed used (can be null) + * @returns a new raw 3D texture (stored in an InternalTexture) + */ + Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) { + if (compression === void 0) { compression = null; } + if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; } + throw _Misc_devTools__WEBPACK_IMPORTED_MODULE_16__["_DevTools"].WarnImport("Engine.RawTexture"); + }; + Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) { + var gl = this._gl; + if (!gl) { + return; + } + var filters = this._getSamplingParameters(samplingMode, !noMipmap); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min); + if (!noMipmap && !isCompressed) { + gl.generateMipmap(gl.TEXTURE_2D); + } + this._bindTextureDirectly(gl.TEXTURE_2D, null); + // this.resetTextureCache(); + if (scene) { + scene._removePendingData(texture); + } + texture.onLoadedObservable.notifyObservers(texture); + texture.onLoadedObservable.clear(); + }; + Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) { + var _this = this; + if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; } + var maxTextureSize = this.getCaps().maxTextureSize; + var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? _Misc_tools__WEBPACK_IMPORTED_MODULE_5__["Tools"].GetExponentOfTwo(width, maxTextureSize) : width); + var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? _Misc_tools__WEBPACK_IMPORTED_MODULE_5__["Tools"].GetExponentOfTwo(height, maxTextureSize) : height); + var gl = this._gl; + if (!gl) { + return; + } + if (!texture._webGLTexture) { + // this.resetTextureCache(); + if (scene) { + scene._removePendingData(texture); + } + return; + } + this._bindTextureDirectly(gl.TEXTURE_2D, texture, true); + this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false)); + texture.baseWidth = width; + texture.baseHeight = height; + texture.width = potWidth; + texture.height = potHeight; + texture.isReady = true; + if (processFunction(potWidth, potHeight, function () { + _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode); + })) { + // Returning as texture needs extra async steps + return; + } + this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode); + }; + /** @hidden */ + Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) { + // Create new RGBA data container. + var rgbaData; + if (textureType === Engine.TEXTURETYPE_FLOAT) { + rgbaData = new Float32Array(width * height * 4); + } + else { + rgbaData = new Uint32Array(width * height * 4); + } + // Convert each pixel. + for (var x = 0; x < width; x++) { + for (var y = 0; y < height; y++) { + var index = (y * width + x) * 3; + var newIndex = (y * width + x) * 4; + // Map Old Value to new value. + rgbaData[newIndex + 0] = rgbData[index + 0]; + rgbaData[newIndex + 1] = rgbData[index + 1]; + rgbaData[newIndex + 2] = rgbData[index + 2]; + // Add fully opaque alpha channel. + rgbaData[newIndex + 3] = 1; + } + } + return rgbaData; + }; + /** @hidden */ + Engine.prototype._releaseFramebufferObjects = function (texture) { + var gl = this._gl; + if (texture._framebuffer) { + gl.deleteFramebuffer(texture._framebuffer); + texture._framebuffer = null; + } + if (texture._depthStencilBuffer) { + gl.deleteRenderbuffer(texture._depthStencilBuffer); + texture._depthStencilBuffer = null; + } + if (texture._MSAAFramebuffer) { + gl.deleteFramebuffer(texture._MSAAFramebuffer); + texture._MSAAFramebuffer = null; + } + if (texture._MSAARenderBuffer) { + gl.deleteRenderbuffer(texture._MSAARenderBuffer); + texture._MSAARenderBuffer = null; + } + }; + /** @hidden */ + Engine.prototype._releaseTexture = function (texture) { + this._releaseFramebufferObjects(texture); + this._deleteTexture(texture._webGLTexture); + // Unbind channels + this.unbindAllTextures(); + var index = this._internalTexturesCache.indexOf(texture); + if (index !== -1) { + this._internalTexturesCache.splice(index, 1); + } + // Integrated fixed lod samplers. + if (texture._lodTextureHigh) { + texture._lodTextureHigh.dispose(); + } + if (texture._lodTextureMid) { + texture._lodTextureMid.dispose(); + } + if (texture._lodTextureLow) { + texture._lodTextureLow.dispose(); + } + // Integrated irradiance map. + if (texture._irradianceTexture) { + texture._irradianceTexture.dispose(); + } + // Set output texture of post process to null if the texture has been released/disposed + this.scenes.forEach(function (scene) { + scene.postProcesses.forEach(function (postProcess) { + if (postProcess._outputTexture == texture) { + postProcess._outputTexture = null; + } + }); + scene.cameras.forEach(function (camera) { + camera._postProcesses.forEach(function (postProcess) { + if (postProcess) { + if (postProcess._outputTexture == texture) { + postProcess._outputTexture = null; + } + } + }); + }); + }); + }; + Engine.prototype._deleteTexture = function (texture) { + this._gl.deleteTexture(texture); + }; + Engine.prototype._setProgram = function (program) { + if (this._currentProgram !== program) { + this._gl.useProgram(program); + this._currentProgram = program; + } + }; + /** + * Binds an effect to the webGL context + * @param effect defines the effect to bind + */ + Engine.prototype.bindSamplers = function (effect) { + var webGLPipelineContext = effect.getPipelineContext(); + this._setProgram(webGLPipelineContext.program); + var samplers = effect.getSamplers(); + for (var index = 0; index < samplers.length; index++) { + var uniform = effect.getUniform(samplers[index]); + if (uniform) { + this._boundUniforms[index] = uniform; + } + } + this._currentEffect = null; + }; + Engine.prototype._activateCurrentTexture = function () { + if (this._currentTextureChannel !== this._activeChannel) { + this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel); + this._currentTextureChannel = this._activeChannel; + } + }; + /** @hidden */ + Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) { + if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; } + if (force === void 0) { force = false; } + var wasPreviouslyBound = false; + var isTextureForRendering = texture && texture._associatedChannel > -1; + if (forTextureDataUpdate && isTextureForRendering) { + this._activeChannel = texture._associatedChannel; + } + var currentTextureBound = this._boundTexturesCache[this._activeChannel]; + if (currentTextureBound !== texture || force) { + this._activateCurrentTexture(); + if (texture && texture.isMultiview) { + this._gl.bindTexture(target, texture ? texture._colorTextureArray : null); + } + else { + this._gl.bindTexture(target, texture ? texture._webGLTexture : null); + } + this._boundTexturesCache[this._activeChannel] = texture; + if (texture) { + texture._associatedChannel = this._activeChannel; + } + } + else if (forTextureDataUpdate) { + wasPreviouslyBound = true; + this._activateCurrentTexture(); + } + if (isTextureForRendering && !forTextureDataUpdate) { + this._bindSamplerUniformToChannel(texture._associatedChannel, this._activeChannel); + } + return wasPreviouslyBound; + }; + /** @hidden */ + Engine.prototype._bindTexture = function (channel, texture) { + if (channel === undefined) { + return; + } + if (texture) { + texture._associatedChannel = channel; + } + this._activeChannel = channel; + this._bindTextureDirectly(this._gl.TEXTURE_2D, texture); + }; + /** + * Sets a texture to the webGL context from a postprocess + * @param channel defines the channel to use + * @param postProcess defines the source postprocess + */ + Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) { + this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null); + }; + /** + * Binds the output of the passed in post process to the texture channel specified + * @param channel The channel the texture should be bound to + * @param postProcess The post process which's output should be bound + */ + Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) { + this._bindTexture(channel, postProcess ? postProcess._outputTexture : null); + }; + /** + * Unbind all textures from the webGL context + */ + Engine.prototype.unbindAllTextures = function () { + for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) { + this._activeChannel = channel; + this._bindTextureDirectly(this._gl.TEXTURE_2D, null); + this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null); + if (this.webGLVersion > 1) { + this._bindTextureDirectly(this._gl.TEXTURE_3D, null); + } + } + }; + /** + * Sets a texture to the according uniform. + * @param channel The texture channel + * @param uniform The uniform to set + * @param texture The texture to apply + */ + Engine.prototype.setTexture = function (channel, uniform, texture) { + if (channel === undefined) { + return; + } + if (uniform) { + this._boundUniforms[channel] = uniform; + } + this._setTexture(channel, texture); + }; + /** + * Sets a depth stencil texture from a render target to the according uniform. + * @param channel The texture channel + * @param uniform The uniform to set + * @param texture The render target texture containing the depth stencil texture to apply + */ + Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) { + if (channel === undefined) { + return; + } + if (uniform) { + this._boundUniforms[channel] = uniform; + } + if (!texture || !texture.depthStencilTexture) { + this._setTexture(channel, null); + } + else { + this._setTexture(channel, texture, false, true); + } + }; + Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) { + var uniform = this._boundUniforms[sourceSlot]; + if (uniform._currentState === destination) { + return; + } + this._gl.uniform1i(uniform, destination); + uniform._currentState = destination; + }; + Engine.prototype._getTextureWrapMode = function (mode) { + switch (mode) { + case Engine.TEXTURE_WRAP_ADDRESSMODE: + return this._gl.REPEAT; + case Engine.TEXTURE_CLAMP_ADDRESSMODE: + return this._gl.CLAMP_TO_EDGE; + case Engine.TEXTURE_MIRROR_ADDRESSMODE: + return this._gl.MIRRORED_REPEAT; + } + return this._gl.REPEAT; + }; + Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) { + if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; } + if (depthStencilTexture === void 0) { depthStencilTexture = false; } + // Not ready? + if (!texture) { + if (this._boundTexturesCache[channel] != null) { + this._activeChannel = channel; + this._bindTextureDirectly(this._gl.TEXTURE_2D, null); + this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null); + if (this.webGLVersion > 1) { + this._bindTextureDirectly(this._gl.TEXTURE_3D, null); + } + } + return false; + } + // Video + if (texture.video) { + this._activeChannel = channel; + texture.update(); + } + else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading + texture.delayLoad(); + return false; + } + var internalTexture; + if (depthStencilTexture) { + internalTexture = texture.depthStencilTexture; + } + else if (texture.isReady()) { + internalTexture = texture.getInternalTexture(); + } + else if (texture.isCube) { + internalTexture = this.emptyCubeTexture; + } + else if (texture.is3D) { + internalTexture = this.emptyTexture3D; + } + else { + internalTexture = this.emptyTexture; + } + if (!isPartOfTextureArray && internalTexture) { + internalTexture._associatedChannel = channel; + } + var needToBind = true; + if (this._boundTexturesCache[channel] === internalTexture) { + if (!isPartOfTextureArray) { + this._bindSamplerUniformToChannel(internalTexture._associatedChannel, channel); + } + needToBind = false; + } + this._activeChannel = channel; + if (internalTexture && internalTexture.isMultiview) { + if (needToBind) { + this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY, internalTexture, isPartOfTextureArray); + } + } + else if (internalTexture && internalTexture.is3D) { + if (needToBind) { + this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray); + } + if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) { + internalTexture._cachedWrapU = texture.wrapU; + this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture); + } + if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) { + internalTexture._cachedWrapV = texture.wrapV; + this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture); + } + if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) { + internalTexture._cachedWrapR = texture.wrapR; + this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture); + } + this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture); + } + else if (internalTexture && internalTexture.isCube) { + if (needToBind) { + this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray); + } + if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) { + internalTexture._cachedCoordinatesMode = texture.coordinatesMode; + // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT. + var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE; + this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture); + this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode); + } + this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture); + } + else { + if (needToBind) { + this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray); + } + if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) { + internalTexture._cachedWrapU = texture.wrapU; + this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture); + } + if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) { + internalTexture._cachedWrapV = texture.wrapV; + this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture); + } + this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture); + } + return true; + }; + /** + * Sets an array of texture to the webGL context + * @param channel defines the channel where the texture array must be set + * @param uniform defines the associated uniform location + * @param textures defines the array of textures to bind + */ + Engine.prototype.setTextureArray = function (channel, uniform, textures) { + if (channel === undefined || !uniform) { + return; + } + this._boundUniforms[channel] = uniform; + if (!this._textureUnits || this._textureUnits.length !== textures.length) { + this._textureUnits = new Int32Array(textures.length); + } + for (var i = 0; i < textures.length; i++) { + var texture = textures[i].getInternalTexture(); + if (texture) { + this._textureUnits[channel + i] = channel + i; + texture._associatedChannel = channel + i; + } + else { + this._textureUnits[channel + i] = -1; + } + } + this._gl.uniform1iv(uniform, this._textureUnits); + for (var index = 0; index < textures.length; index++) { + this._setTexture(this._textureUnits[index], textures[index], true); + } + }; + /** @hidden */ + Engine.prototype._setAnisotropicLevel = function (target, texture) { + var internalTexture = texture.getInternalTexture(); + if (!internalTexture) { + return; + } + var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension; + var value = texture.anisotropicFilteringLevel; + if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST + && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR + && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) { + value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear + } + if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) { + this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture); + internalTexture._cachedAnisotropicFilteringLevel = value; + } + }; + Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) { + this._bindTextureDirectly(target, texture, true, true); + this._gl.texParameterf(target, parameter, value); + }; + Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) { + if (texture) { + this._bindTextureDirectly(target, texture, true, true); + } + this._gl.texParameteri(target, parameter, value); + }; + /** + * Reads pixels from the current frame buffer. Please note that this function can be slow + * @param x defines the x coordinate of the rectangle where pixels must be read + * @param y defines the y coordinate of the rectangle where pixels must be read + * @param width defines the width of the rectangle where pixels must be read + * @param height defines the height of the rectangle where pixels must be read + * @returns a Uint8Array containing RGBA colors + */ + Engine.prototype.readPixels = function (x, y, width, height) { + var data = new Uint8Array(height * width * 4); + this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data); + return data; + }; + /** + * Add an externaly attached data from its key. + * This method call will fail and return false, if such key already exists. + * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method. + * @param key the unique key that identifies the data + * @param data the data object to associate to the key for this Engine instance + * @return true if no such key were already present and the data was added successfully, false otherwise + */ + Engine.prototype.addExternalData = function (key, data) { + if (!this._externalData) { + this._externalData = new _Misc_stringDictionary__WEBPACK_IMPORTED_MODULE_3__["StringDictionary"](); + } + return this._externalData.add(key, data); + }; + /** + * Get an externaly attached data from its key + * @param key the unique key that identifies the data + * @return the associated data, if present (can be null), or undefined if not present + */ + Engine.prototype.getExternalData = function (key) { + if (!this._externalData) { + this._externalData = new _Misc_stringDictionary__WEBPACK_IMPORTED_MODULE_3__["StringDictionary"](); + } + return this._externalData.get(key); + }; + /** + * Get an externaly attached data from its key, create it using a factory if it's not already present + * @param key the unique key that identifies the data + * @param factory the factory that will be called to create the instance if and only if it doesn't exists + * @return the associated data, can be null if the factory returned null. + */ + Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) { + if (!this._externalData) { + this._externalData = new _Misc_stringDictionary__WEBPACK_IMPORTED_MODULE_3__["StringDictionary"](); + } + return this._externalData.getOrAddWithFactory(key, factory); + }; + /** + * Remove an externaly attached data from the Engine instance + * @param key the unique key that identifies the data + * @return true if the data was successfully removed, false if it doesn't exist + */ + Engine.prototype.removeExternalData = function (key) { + if (!this._externalData) { + this._externalData = new _Misc_stringDictionary__WEBPACK_IMPORTED_MODULE_3__["StringDictionary"](); + } + return this._externalData.remove(key); + }; + /** + * Unbind all vertex attributes from the webGL context + */ + Engine.prototype.unbindAllAttributes = function () { + if (this._mustWipeVertexAttributes) { + this._mustWipeVertexAttributes = false; + for (var i = 0; i < this._caps.maxVertexAttribs; i++) { + this._gl.disableVertexAttribArray(i); + this._vertexAttribArraysEnabled[i] = false; + this._currentBufferPointers[i].active = false; + } + return; + } + for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) { + if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) { + continue; + } + this._gl.disableVertexAttribArray(i); + this._vertexAttribArraysEnabled[i] = false; + this._currentBufferPointers[i].active = false; + } + }; + /** + * Force the engine to release all cached effects. This means that next effect compilation will have to be done completely even if a similar effect was already compiled + */ + Engine.prototype.releaseEffects = function () { + for (var name in this._compiledEffects) { + var webGLPipelineContext = this._compiledEffects[name].getPipelineContext(); + this._deletePipelineContext(webGLPipelineContext); + } + this._compiledEffects = {}; + }; + /** + * Dispose and release all associated resources + */ + Engine.prototype.dispose = function () { + this.hideLoadingUI(); + this.stopRenderLoop(); + this.onNewSceneAddedObservable.clear(); + // Release postProcesses + while (this.postProcesses.length) { + this.postProcesses[0].dispose(); + } + // Empty texture + if (this._emptyTexture) { + this._releaseTexture(this._emptyTexture); + this._emptyTexture = null; + } + if (this._emptyCubeTexture) { + this._releaseTexture(this._emptyCubeTexture); + this._emptyCubeTexture = null; + } + // Rescale PP + if (this._rescalePostProcess) { + this._rescalePostProcess.dispose(); + } + // Release scenes + while (this.scenes.length) { + this.scenes[0].dispose(); + } + // Release audio engine + if (Engine.Instances.length === 1 && Engine.audioEngine) { + Engine.audioEngine.dispose(); + } + // Release effects + this.releaseEffects(); + // Unbind + this.unbindAllAttributes(); + this._boundUniforms = []; + if (this._dummyFramebuffer) { + this._gl.deleteFramebuffer(this._dummyFramebuffer); + } + //WebVR + this.disableVR(); + // Events + if (_Misc_domManagement__WEBPACK_IMPORTED_MODULE_12__["DomManagement"].IsWindowObjectExist()) { + window.removeEventListener("blur", this._onBlur); + window.removeEventListener("focus", this._onFocus); + if (this._renderingCanvas) { + this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus); + this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur); + this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut); + if (!this._doNotHandleContextLost) { + this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost); + this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored); + } + } + 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); + } + // Remove from Instances + var index = Engine.Instances.indexOf(this); + if (index >= 0) { + Engine.Instances.splice(index, 1); + } + this._workingCanvas = null; + this._workingContext = null; + this._currentBufferPointers = []; + this._renderingCanvas = null; + this._currentProgram = null; + this._bindedRenderFunction = null; + this.onResizeObservable.clear(); + this.onCanvasBlurObservable.clear(); + this.onCanvasFocusObservable.clear(); + this.onCanvasPointerOutObservable.clear(); + this.onBeginFrameObservable.clear(); + this.onEndFrameObservable.clear(); + _Materials_effect__WEBPACK_IMPORTED_MODULE_8__["Effect"].ResetCache(); + // Abort active requests + for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) { + var request = _a[_i]; + request.abort(); + } + }; + // Loading screen + /** + * Display the loading screen + * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen + */ + Engine.prototype.displayLoadingUI = function () { + if (!_Misc_domManagement__WEBPACK_IMPORTED_MODULE_12__["DomManagement"].IsWindowObjectExist()) { + return; + } + var loadingScreen = this.loadingScreen; + if (loadingScreen) { + loadingScreen.displayLoadingUI(); + } + }; + /** + * Hide the loading screen + * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen + */ + Engine.prototype.hideLoadingUI = function () { + if (!_Misc_domManagement__WEBPACK_IMPORTED_MODULE_12__["DomManagement"].IsWindowObjectExist()) { + return; + } + var loadingScreen = this._loadingScreen; + if (loadingScreen) { + loadingScreen.hideLoadingUI(); + } + }; + Object.defineProperty(Engine.prototype, "loadingScreen", { + /** + * Gets the current loading screen object + * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen + */ + get: function () { + if (!this._loadingScreen && this._renderingCanvas) { + this._loadingScreen = Engine.DefaultLoadingScreenFactory(this._renderingCanvas); + } + return this._loadingScreen; + }, + /** + * Sets the current loading screen object + * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen + */ + set: function (loadingScreen) { + this._loadingScreen = loadingScreen; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Engine.prototype, "loadingUIText", { + /** + * Sets the current loading screen text + * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen + */ + set: function (text) { + this.loadingScreen.loadingUIText = text; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", { + /** + * Sets the current loading screen background color + * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen + */ + set: function (color) { + this.loadingScreen.loadingUIBackgroundColor = color; + }, + enumerable: true, + configurable: true + }); + /** + * Attach a new callback raised when context lost event is fired + * @param callback defines the callback to call + */ + Engine.prototype.attachContextLostEvent = function (callback) { + if (this._renderingCanvas) { + this._renderingCanvas.addEventListener("webglcontextlost", callback, false); + } + }; + /** + * Attach a new callback raised when context restored event is fired + * @param callback defines the callback to call + */ + Engine.prototype.attachContextRestoredEvent = function (callback) { + if (this._renderingCanvas) { + this._renderingCanvas.addEventListener("webglcontextrestored", callback, false); + } + }; + /** + * Gets the source code of the vertex shader associated with a specific webGL program + * @param program defines the program to use + * @returns a string containing the source code of the vertex shader associated with the program + */ + Engine.prototype.getVertexShaderSource = function (program) { + var shaders = this._gl.getAttachedShaders(program); + if (!shaders) { + return null; + } + return this._gl.getShaderSource(shaders[0]); + }; + /** + * Gets the source code of the fragment shader associated with a specific webGL program + * @param program defines the program to use + * @returns a string containing the source code of the fragment shader associated with the program + */ + Engine.prototype.getFragmentShaderSource = function (program) { + var shaders = this._gl.getAttachedShaders(program); + if (!shaders) { + return null; + } + return this._gl.getShaderSource(shaders[1]); + }; + /** + * Get the current error code of the webGL context + * @returns the error code + * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError + */ + Engine.prototype.getError = function () { + return this._gl.getError(); + }; + // FPS + /** + * Gets the current framerate + * @returns a number representing the framerate + */ + Engine.prototype.getFps = function () { + return this._fps; + }; + /** + * Gets the time spent between current and previous frame + * @returns a number representing the delta time in ms + */ + Engine.prototype.getDeltaTime = function () { + return this._deltaTime; + }; + Engine.prototype._measureFps = function () { + this._performanceMonitor.sampleFrame(); + this._fps = this._performanceMonitor.averageFPS; + this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0; + }; + /** @hidden */ + Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level, buffer) { + if (faceIndex === void 0) { faceIndex = -1; } + if (level === void 0) { level = 0; } + if (buffer === void 0) { buffer = null; } + var gl = this._gl; + if (!this._dummyFramebuffer) { + var dummy = gl.createFramebuffer(); + if (!dummy) { + throw new Error("Unable to create dummy framebuffer"); + } + this._dummyFramebuffer = dummy; + } + gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer); + if (faceIndex > -1) { + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level); + } + else { + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level); + } + var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE; + switch (readType) { + case gl.UNSIGNED_BYTE: + if (!buffer) { + buffer = new Uint8Array(4 * width * height); + } + readType = gl.UNSIGNED_BYTE; + break; + default: + if (!buffer) { + buffer = new Float32Array(4 * width * height); + } + readType = gl.FLOAT; + break; + } + gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer); + return buffer; + }; + Engine.prototype._canRenderToFloatFramebuffer = function () { + if (this._webGLVersion > 1) { + return this._caps.colorBufferFloat; + } + return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT); + }; + Engine.prototype._canRenderToHalfFloatFramebuffer = function () { + if (this._webGLVersion > 1) { + return this._caps.colorBufferFloat; + } + return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT); + }; + // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture + Engine.prototype._canRenderToFramebuffer = function (type) { + var gl = this._gl; + //clear existing errors + while (gl.getError() !== gl.NO_ERROR) { } + var successful = true; + var texture = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, texture); + gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); + var fb = gl.createFramebuffer(); + gl.bindFramebuffer(gl.FRAMEBUFFER, fb); + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0); + var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER); + successful = successful && (status === gl.FRAMEBUFFER_COMPLETE); + successful = successful && (gl.getError() === gl.NO_ERROR); + //try render by clearing frame buffer's color buffer + if (successful) { + gl.clear(gl.COLOR_BUFFER_BIT); + successful = successful && (gl.getError() === gl.NO_ERROR); + } + //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported) + if (successful) { + //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + var readFormat = gl.RGBA; + var readType = gl.UNSIGNED_BYTE; + var buffer = new Uint8Array(4); + gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer); + successful = successful && (gl.getError() === gl.NO_ERROR); + } + //clean up + gl.deleteTexture(texture); + gl.deleteFramebuffer(fb); + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + //clear accumulated errors + while (!successful && (gl.getError() !== gl.NO_ERROR)) { } + return successful; + }; + /** @hidden */ + Engine.prototype._getWebGLTextureType = function (type) { + if (this._webGLVersion === 1) { + switch (type) { + case Engine.TEXTURETYPE_FLOAT: + return this._gl.FLOAT; + case Engine.TEXTURETYPE_HALF_FLOAT: + return this._gl.HALF_FLOAT_OES; + case Engine.TEXTURETYPE_UNSIGNED_BYTE: + return this._gl.UNSIGNED_BYTE; + } + return this._gl.UNSIGNED_BYTE; + } + switch (type) { + case Engine.TEXTURETYPE_BYTE: + return this._gl.BYTE; + case Engine.TEXTURETYPE_UNSIGNED_BYTE: + return this._gl.UNSIGNED_BYTE; + case Engine.TEXTURETYPE_SHORT: + return this._gl.SHORT; + case Engine.TEXTURETYPE_UNSIGNED_SHORT: + return this._gl.UNSIGNED_SHORT; + case Engine.TEXTURETYPE_INT: + return this._gl.INT; + case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT + return this._gl.UNSIGNED_INT; + case Engine.TEXTURETYPE_FLOAT: + return this._gl.FLOAT; + case Engine.TEXTURETYPE_HALF_FLOAT: + return this._gl.HALF_FLOAT; + case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4: + return this._gl.UNSIGNED_SHORT_4_4_4_4; + case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1: + return this._gl.UNSIGNED_SHORT_5_5_5_1; + case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5: + return this._gl.UNSIGNED_SHORT_5_6_5; + case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV: + return this._gl.UNSIGNED_INT_2_10_10_10_REV; + case Engine.TEXTURETYPE_UNSIGNED_INT_24_8: + return this._gl.UNSIGNED_INT_24_8; + case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV: + return this._gl.UNSIGNED_INT_10F_11F_11F_REV; + case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV: + return this._gl.UNSIGNED_INT_5_9_9_9_REV; + case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV: + return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV; + } + return this._gl.UNSIGNED_BYTE; + }; + /** @hidden */ + Engine.prototype._getInternalFormat = function (format) { + var internalFormat = this._gl.RGBA; + switch (format) { + case Engine.TEXTUREFORMAT_ALPHA: + internalFormat = this._gl.ALPHA; + break; + case Engine.TEXTUREFORMAT_LUMINANCE: + internalFormat = this._gl.LUMINANCE; + break; + case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA: + internalFormat = this._gl.LUMINANCE_ALPHA; + break; + case Engine.TEXTUREFORMAT_RED: + internalFormat = this._gl.RED; + break; + case Engine.TEXTUREFORMAT_RG: + internalFormat = this._gl.RG; + break; + case Engine.TEXTUREFORMAT_RGB: + internalFormat = this._gl.RGB; + break; + case Engine.TEXTUREFORMAT_RGBA: + internalFormat = this._gl.RGBA; + break; + } + if (this._webGLVersion > 1) { + switch (format) { + case Engine.TEXTUREFORMAT_RED_INTEGER: + internalFormat = this._gl.RED_INTEGER; + break; + case Engine.TEXTUREFORMAT_RG_INTEGER: + internalFormat = this._gl.RG_INTEGER; + break; + case Engine.TEXTUREFORMAT_RGB_INTEGER: + internalFormat = this._gl.RGB_INTEGER; + break; + case Engine.TEXTUREFORMAT_RGBA_INTEGER: + internalFormat = this._gl.RGBA_INTEGER; + break; + } + } + return internalFormat; + }; + /** @hidden */ + Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) { + if (this._webGLVersion === 1) { + if (format !== undefined) { + switch (format) { + case Engine.TEXTUREFORMAT_ALPHA: + return this._gl.ALPHA; + case Engine.TEXTUREFORMAT_LUMINANCE: + return this._gl.LUMINANCE; + case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA: + return this._gl.LUMINANCE_ALPHA; + } + } + return this._gl.RGBA; + } + switch (type) { + case Engine.TEXTURETYPE_BYTE: + switch (format) { + case Engine.TEXTUREFORMAT_RED: + return this._gl.R8_SNORM; + case Engine.TEXTUREFORMAT_RG: + return this._gl.RG8_SNORM; + case Engine.TEXTUREFORMAT_RGB: + return this._gl.RGB8_SNORM; + case Engine.TEXTUREFORMAT_RED_INTEGER: + return this._gl.R8I; + case Engine.TEXTUREFORMAT_RG_INTEGER: + return this._gl.RG8I; + case Engine.TEXTUREFORMAT_RGB_INTEGER: + return this._gl.RGB8I; + case Engine.TEXTUREFORMAT_RGBA_INTEGER: + return this._gl.RGBA8I; + default: + return this._gl.RGBA8_SNORM; + } + case Engine.TEXTURETYPE_UNSIGNED_BYTE: + switch (format) { + case Engine.TEXTUREFORMAT_RED: + return this._gl.R8; + case Engine.TEXTUREFORMAT_RG: + return this._gl.RG8; + case Engine.TEXTUREFORMAT_RGB: + return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8. + case Engine.TEXTUREFORMAT_RGBA: + return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8. + case Engine.TEXTUREFORMAT_RED_INTEGER: + return this._gl.R8UI; + case Engine.TEXTUREFORMAT_RG_INTEGER: + return this._gl.RG8UI; + case Engine.TEXTUREFORMAT_RGB_INTEGER: + return this._gl.RGB8UI; + case Engine.TEXTUREFORMAT_RGBA_INTEGER: + return this._gl.RGBA8UI; + case Engine.TEXTUREFORMAT_ALPHA: + return this._gl.ALPHA; + case Engine.TEXTUREFORMAT_LUMINANCE: + return this._gl.LUMINANCE; + case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA: + return this._gl.LUMINANCE_ALPHA; + default: + return this._gl.RGBA8; + } + case Engine.TEXTURETYPE_SHORT: + switch (format) { + case Engine.TEXTUREFORMAT_RED_INTEGER: + return this._gl.R16I; + case Engine.TEXTUREFORMAT_RG_INTEGER: + return this._gl.RG16I; + case Engine.TEXTUREFORMAT_RGB_INTEGER: + return this._gl.RGB16I; + case Engine.TEXTUREFORMAT_RGBA_INTEGER: + return this._gl.RGBA16I; + default: + return this._gl.RGBA16I; + } + case Engine.TEXTURETYPE_UNSIGNED_SHORT: + switch (format) { + case Engine.TEXTUREFORMAT_RED_INTEGER: + return this._gl.R16UI; + case Engine.TEXTUREFORMAT_RG_INTEGER: + return this._gl.RG16UI; + case Engine.TEXTUREFORMAT_RGB_INTEGER: + return this._gl.RGB16UI; + case Engine.TEXTUREFORMAT_RGBA_INTEGER: + return this._gl.RGBA16UI; + default: + return this._gl.RGBA16UI; + } + case Engine.TEXTURETYPE_INT: + switch (format) { + case Engine.TEXTUREFORMAT_RED_INTEGER: + return this._gl.R32I; + case Engine.TEXTUREFORMAT_RG_INTEGER: + return this._gl.RG32I; + case Engine.TEXTUREFORMAT_RGB_INTEGER: + return this._gl.RGB32I; + case Engine.TEXTUREFORMAT_RGBA_INTEGER: + return this._gl.RGBA32I; + default: + return this._gl.RGBA32I; + } + case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT + switch (format) { + case Engine.TEXTUREFORMAT_RED_INTEGER: + return this._gl.R32UI; + case Engine.TEXTUREFORMAT_RG_INTEGER: + return this._gl.RG32UI; + case Engine.TEXTUREFORMAT_RGB_INTEGER: + return this._gl.RGB32UI; + case Engine.TEXTUREFORMAT_RGBA_INTEGER: + return this._gl.RGBA32UI; + default: + return this._gl.RGBA32UI; + } + case Engine.TEXTURETYPE_FLOAT: + switch (format) { + case Engine.TEXTUREFORMAT_RED: + return this._gl.R32F; // By default. Other possibility is R16F. + case Engine.TEXTUREFORMAT_RG: + return this._gl.RG32F; // By default. Other possibility is RG16F. + case Engine.TEXTUREFORMAT_RGB: + return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5. + case Engine.TEXTUREFORMAT_RGBA: + return this._gl.RGBA32F; // By default. Other possibility is RGBA16F. + default: + return this._gl.RGBA32F; + } + case Engine.TEXTURETYPE_HALF_FLOAT: + switch (format) { + case Engine.TEXTUREFORMAT_RED: + return this._gl.R16F; + case Engine.TEXTUREFORMAT_RG: + return this._gl.RG16F; + case Engine.TEXTUREFORMAT_RGB: + return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5. + case Engine.TEXTUREFORMAT_RGBA: + return this._gl.RGBA16F; + default: + return this._gl.RGBA16F; + } + case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5: + return this._gl.RGB565; + case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV: + return this._gl.R11F_G11F_B10F; + case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV: + return this._gl.RGB9_E5; + case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4: + return this._gl.RGBA4; + case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1: + return this._gl.RGB5_A1; + case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV: + switch (format) { + case Engine.TEXTUREFORMAT_RGBA: + return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1. + case Engine.TEXTUREFORMAT_RGBA_INTEGER: + return this._gl.RGB10_A2UI; + default: + return this._gl.RGB10_A2; + } + } + return this._gl.RGBA8; + }; + /** @hidden */ + Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) { + if (type === Engine.TEXTURETYPE_FLOAT) { + return this._gl.RGBA32F; + } + else if (type === Engine.TEXTURETYPE_HALF_FLOAT) { + return this._gl.RGBA16F; + } + return this._gl.RGBA8; + }; + /** @hidden */ + Engine.prototype._loadFile = function (url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError) { + var _this = this; + var request = _Misc_tools__WEBPACK_IMPORTED_MODULE_5__["Tools"].LoadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError); + this._activeRequests.push(request); + request.onCompleteObservable.add(function (request) { + _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1); + }); + return request; + }; + /** @hidden */ + Engine.prototype._loadFileAsync = function (url, offlineProvider, useArrayBuffer) { + var _this = this; + return new Promise(function (resolve, reject) { + _this._loadFile(url, function (data) { + resolve(data); + }, undefined, offlineProvider, useArrayBuffer, function (request, exception) { + reject(exception); + }); + }); + }; + // Statics + /** + * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found) + * @returns true if the engine can be created + * @ignorenaming + */ + Engine.isSupported = function () { + try { + var tempcanvas = document.createElement("canvas"); + var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl"); + return gl != null && !!window.WebGLRenderingContext; + } + catch (e) { + return false; + } + }; + /** Use this array to turn off some WebGL2 features on known buggy browsers version */ + Engine.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"] } + ]; + /** @hidden */ + Engine._TextureLoaders = []; + // Const statics + /** Defines that alpha blending is disabled */ + Engine.ALPHA_DISABLE = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].ALPHA_DISABLE; + /** Defines that alpha blending to SRC ALPHA * SRC + DEST */ + Engine.ALPHA_ADD = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].ALPHA_ADD; + /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */ + Engine.ALPHA_COMBINE = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].ALPHA_COMBINE; + /** Defines that alpha blending to DEST - SRC * DEST */ + Engine.ALPHA_SUBTRACT = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].ALPHA_SUBTRACT; + /** Defines that alpha blending to SRC * DEST */ + Engine.ALPHA_MULTIPLY = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].ALPHA_MULTIPLY; + /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */ + Engine.ALPHA_MAXIMIZED = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].ALPHA_MAXIMIZED; + /** Defines that alpha blending to SRC + DEST */ + Engine.ALPHA_ONEONE = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].ALPHA_ONEONE; + /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */ + Engine.ALPHA_PREMULTIPLIED = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].ALPHA_PREMULTIPLIED; + /** + * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST + * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA + */ + Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].ALPHA_PREMULTIPLIED_PORTERDUFF; + /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */ + Engine.ALPHA_INTERPOLATE = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].ALPHA_INTERPOLATE; + /** + * Defines that alpha blending to SRC + (1 - SRC) * DEST + * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA + */ + Engine.ALPHA_SCREENMODE = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].ALPHA_SCREENMODE; + /** Defines that the ressource is not delayed*/ + Engine.DELAYLOADSTATE_NONE = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].DELAYLOADSTATE_NONE; + /** Defines that the ressource was successfully delay loaded */ + Engine.DELAYLOADSTATE_LOADED = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].DELAYLOADSTATE_LOADED; + /** Defines that the ressource is currently delay loading */ + Engine.DELAYLOADSTATE_LOADING = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].DELAYLOADSTATE_LOADING; + /** Defines that the ressource is delayed and has not started loading */ + Engine.DELAYLOADSTATE_NOTLOADED = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].DELAYLOADSTATE_NOTLOADED; + // Depht or Stencil test Constants. + /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */ + Engine.NEVER = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].NEVER; + /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn */ + Engine.ALWAYS = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].ALWAYS; + /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */ + Engine.LESS = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].LESS; + /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */ + Engine.EQUAL = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].EQUAL; + /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value */ + Engine.LEQUAL = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].LEQUAL; + /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */ + Engine.GREATER = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].GREATER; + /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value */ + Engine.GEQUAL = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].GEQUAL; + /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value */ + Engine.NOTEQUAL = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].NOTEQUAL; + // Stencil Actions Constants. + /** Passed to stencilOperation to specify that stencil value must be kept */ + Engine.KEEP = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].KEEP; + /** Passed to stencilOperation to specify that stencil value must be replaced */ + Engine.REPLACE = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].REPLACE; + /** Passed to stencilOperation to specify that stencil value must be incremented */ + Engine.INCR = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].INCR; + /** Passed to stencilOperation to specify that stencil value must be decremented */ + Engine.DECR = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].DECR; + /** Passed to stencilOperation to specify that stencil value must be inverted */ + Engine.INVERT = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].INVERT; + /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */ + Engine.INCR_WRAP = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].INCR_WRAP; + /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */ + Engine.DECR_WRAP = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].DECR_WRAP; + /** Texture is not repeating outside of 0..1 UVs */ + Engine.TEXTURE_CLAMP_ADDRESSMODE = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURE_CLAMP_ADDRESSMODE; + /** Texture is repeating outside of 0..1 UVs */ + Engine.TEXTURE_WRAP_ADDRESSMODE = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURE_WRAP_ADDRESSMODE; + /** Texture is repeating and mirrored */ + Engine.TEXTURE_MIRROR_ADDRESSMODE = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURE_MIRROR_ADDRESSMODE; + /** ALPHA */ + Engine.TEXTUREFORMAT_ALPHA = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTUREFORMAT_ALPHA; + /** LUMINANCE */ + Engine.TEXTUREFORMAT_LUMINANCE = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTUREFORMAT_LUMINANCE; + /** LUMINANCE_ALPHA */ + Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTUREFORMAT_LUMINANCE_ALPHA; + /** RGB */ + Engine.TEXTUREFORMAT_RGB = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTUREFORMAT_RGB; + /** RGBA */ + Engine.TEXTUREFORMAT_RGBA = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTUREFORMAT_RGBA; + /** RED */ + Engine.TEXTUREFORMAT_RED = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTUREFORMAT_RED; + /** RED (2nd reference) */ + Engine.TEXTUREFORMAT_R = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTUREFORMAT_R; + /** RG */ + Engine.TEXTUREFORMAT_RG = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTUREFORMAT_RG; + /** RED_INTEGER */ + Engine.TEXTUREFORMAT_RED_INTEGER = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTUREFORMAT_RED_INTEGER; + /** RED_INTEGER (2nd reference) */ + Engine.TEXTUREFORMAT_R_INTEGER = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTUREFORMAT_R_INTEGER; + /** RG_INTEGER */ + Engine.TEXTUREFORMAT_RG_INTEGER = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTUREFORMAT_RG_INTEGER; + /** RGB_INTEGER */ + Engine.TEXTUREFORMAT_RGB_INTEGER = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTUREFORMAT_RGB_INTEGER; + /** RGBA_INTEGER */ + Engine.TEXTUREFORMAT_RGBA_INTEGER = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTUREFORMAT_RGBA_INTEGER; + /** UNSIGNED_BYTE */ + Engine.TEXTURETYPE_UNSIGNED_BYTE = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURETYPE_UNSIGNED_BYTE; + /** UNSIGNED_BYTE (2nd reference) */ + Engine.TEXTURETYPE_UNSIGNED_INT = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURETYPE_UNSIGNED_INT; + /** FLOAT */ + Engine.TEXTURETYPE_FLOAT = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURETYPE_FLOAT; + /** HALF_FLOAT */ + Engine.TEXTURETYPE_HALF_FLOAT = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURETYPE_HALF_FLOAT; + /** BYTE */ + Engine.TEXTURETYPE_BYTE = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURETYPE_BYTE; + /** SHORT */ + Engine.TEXTURETYPE_SHORT = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURETYPE_SHORT; + /** UNSIGNED_SHORT */ + Engine.TEXTURETYPE_UNSIGNED_SHORT = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURETYPE_UNSIGNED_SHORT; + /** INT */ + Engine.TEXTURETYPE_INT = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURETYPE_INT; + /** UNSIGNED_INT */ + Engine.TEXTURETYPE_UNSIGNED_INTEGER = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURETYPE_UNSIGNED_INTEGER; + /** UNSIGNED_SHORT_4_4_4_4 */ + Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4; + /** UNSIGNED_SHORT_5_5_5_1 */ + Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1; + /** UNSIGNED_SHORT_5_6_5 */ + Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURETYPE_UNSIGNED_SHORT_5_6_5; + /** UNSIGNED_INT_2_10_10_10_REV */ + Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV; + /** UNSIGNED_INT_24_8 */ + Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURETYPE_UNSIGNED_INT_24_8; + /** UNSIGNED_INT_10F_11F_11F_REV */ + Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV; + /** UNSIGNED_INT_5_9_9_9_REV */ + Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV; + /** FLOAT_32_UNSIGNED_INT_24_8_REV */ + Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV; + /** nearest is mag = nearest and min = nearest and mip = linear */ + Engine.TEXTURE_NEAREST_SAMPLINGMODE = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURE_NEAREST_SAMPLINGMODE; + /** Bilinear is mag = linear and min = linear and mip = nearest */ + Engine.TEXTURE_BILINEAR_SAMPLINGMODE = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURE_BILINEAR_SAMPLINGMODE; + /** Trilinear is mag = linear and min = linear and mip = linear */ + Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURE_TRILINEAR_SAMPLINGMODE; + /** nearest is mag = nearest and min = nearest and mip = linear */ + Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURE_NEAREST_NEAREST_MIPLINEAR; + /** Bilinear is mag = linear and min = linear and mip = nearest */ + Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURE_LINEAR_LINEAR_MIPNEAREST; + /** Trilinear is mag = linear and min = linear and mip = linear */ + Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURE_LINEAR_LINEAR_MIPLINEAR; + /** mag = nearest and min = nearest and mip = nearest */ + Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURE_NEAREST_NEAREST_MIPNEAREST; + /** mag = nearest and min = linear and mip = nearest */ + Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURE_NEAREST_LINEAR_MIPNEAREST; + /** mag = nearest and min = linear and mip = linear */ + Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURE_NEAREST_LINEAR_MIPLINEAR; + /** mag = nearest and min = linear and mip = none */ + Engine.TEXTURE_NEAREST_LINEAR = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURE_NEAREST_LINEAR; + /** mag = nearest and min = nearest and mip = none */ + Engine.TEXTURE_NEAREST_NEAREST = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURE_NEAREST_NEAREST; + /** mag = linear and min = nearest and mip = nearest */ + Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURE_LINEAR_NEAREST_MIPNEAREST; + /** mag = linear and min = nearest and mip = linear */ + Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURE_LINEAR_NEAREST_MIPLINEAR; + /** mag = linear and min = linear and mip = none */ + Engine.TEXTURE_LINEAR_LINEAR = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURE_LINEAR_LINEAR; + /** mag = linear and min = nearest and mip = none */ + Engine.TEXTURE_LINEAR_NEAREST = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURE_LINEAR_NEAREST; + /** Explicit coordinates mode */ + Engine.TEXTURE_EXPLICIT_MODE = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURE_EXPLICIT_MODE; + /** Spherical coordinates mode */ + Engine.TEXTURE_SPHERICAL_MODE = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURE_SPHERICAL_MODE; + /** Planar coordinates mode */ + Engine.TEXTURE_PLANAR_MODE = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURE_PLANAR_MODE; + /** Cubic coordinates mode */ + Engine.TEXTURE_CUBIC_MODE = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURE_CUBIC_MODE; + /** Projection coordinates mode */ + Engine.TEXTURE_PROJECTION_MODE = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURE_PROJECTION_MODE; + /** Skybox coordinates mode */ + Engine.TEXTURE_SKYBOX_MODE = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURE_SKYBOX_MODE; + /** Inverse Cubic coordinates mode */ + Engine.TEXTURE_INVCUBIC_MODE = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURE_INVCUBIC_MODE; + /** Equirectangular coordinates mode */ + Engine.TEXTURE_EQUIRECTANGULAR_MODE = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURE_EQUIRECTANGULAR_MODE; + /** Equirectangular Fixed coordinates mode */ + Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURE_FIXED_EQUIRECTANGULAR_MODE; + /** Equirectangular Fixed Mirrored coordinates mode */ + Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE; + // Texture rescaling mode + /** Defines that texture rescaling will use a floor to find the closer power of 2 size */ + Engine.SCALEMODE_FLOOR = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].SCALEMODE_FLOOR; + /** Defines that texture rescaling will look for the nearest power of 2 size */ + Engine.SCALEMODE_NEAREST = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].SCALEMODE_NEAREST; + /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */ + Engine.SCALEMODE_CEILING = _constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].SCALEMODE_CEILING; + // Updatable statics so stick with vars here + /** + * Gets or sets the epsilon value used by collision engine + */ + Engine.CollisionsEpsilon = 0.001; + /** + * Method called to create the default rescale post process on each engine. + */ + Engine._RescalePostProcessFactory = null; + return Engine; +}()); + + + +/***/ }), + +/***/ "./Engines/engineStore.ts": +/*!********************************!*\ + !*** ./Engines/engineStore.ts ***! + \********************************/ +/*! exports provided: EngineStore */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EngineStore", function() { return EngineStore; }); +/** + * The engine store class is responsible to hold all the instances of Engine and Scene created + * during the life time of the application. + */ +var EngineStore = /** @class */ (function () { + function EngineStore() { + } + Object.defineProperty(EngineStore, "LastCreatedEngine", { + /** + * Gets the latest created engine + */ + get: function () { + if (this.Instances.length === 0) { + return null; + } + return this.Instances[this.Instances.length - 1]; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(EngineStore, "LastCreatedScene", { + /** + * Gets the latest created scene + */ + get: function () { + return this._LastCreatedScene; + }, + enumerable: true, + configurable: true + }); + /** Gets the list of created engines */ + EngineStore.Instances = new Array(); + /** @hidden */ + EngineStore._LastCreatedScene = null; + return EngineStore; +}()); + + + +/***/ }), + +/***/ "./Engines/index.ts": +/*!**************************!*\ + !*** ./Engines/index.ts ***! + \**************************/ +/*! exports provided: Constants, InstancingAttributeInfo, DepthTextureCreationOptions, EngineCapabilities, Engine, EngineStore, NullEngineOptions, NullEngine, WebGLPipelineContext, WebGL2ShaderProcessor, NativeEngineOptions, NativeEngine, _OcclusionDataStorage, _forceTransformFeedbackToBundle */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./constants */ "./Engines/constants.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Constants", function() { return _constants__WEBPACK_IMPORTED_MODULE_0__["Constants"]; }); + +/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./engine */ "./Engines/engine.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InstancingAttributeInfo", function() { return _engine__WEBPACK_IMPORTED_MODULE_1__["InstancingAttributeInfo"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DepthTextureCreationOptions", function() { return _engine__WEBPACK_IMPORTED_MODULE_1__["DepthTextureCreationOptions"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EngineCapabilities", function() { return _engine__WEBPACK_IMPORTED_MODULE_1__["EngineCapabilities"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Engine", function() { return _engine__WEBPACK_IMPORTED_MODULE_1__["Engine"]; }); + +/* harmony import */ var _engineStore__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./engineStore */ "./Engines/engineStore.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EngineStore", function() { return _engineStore__WEBPACK_IMPORTED_MODULE_2__["EngineStore"]; }); + +/* harmony import */ var _nullEngine__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./nullEngine */ "./Engines/nullEngine.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NullEngineOptions", function() { return _nullEngine__WEBPACK_IMPORTED_MODULE_3__["NullEngineOptions"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NullEngine", function() { return _nullEngine__WEBPACK_IMPORTED_MODULE_3__["NullEngine"]; }); + +/* harmony import */ var _Extensions_index__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Extensions/index */ "./Engines/Extensions/index.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_OcclusionDataStorage", function() { return _Extensions_index__WEBPACK_IMPORTED_MODULE_4__["_OcclusionDataStorage"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_forceTransformFeedbackToBundle", function() { return _Extensions_index__WEBPACK_IMPORTED_MODULE_4__["_forceTransformFeedbackToBundle"]; }); + +/* harmony import */ var _WebGL_webGLPipelineContext__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./WebGL/webGLPipelineContext */ "./Engines/WebGL/webGLPipelineContext.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebGLPipelineContext", function() { return _WebGL_webGLPipelineContext__WEBPACK_IMPORTED_MODULE_5__["WebGLPipelineContext"]; }); + +/* harmony import */ var _WebGL_webGL2ShaderProcessors__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./WebGL/webGL2ShaderProcessors */ "./Engines/WebGL/webGL2ShaderProcessors.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebGL2ShaderProcessor", function() { return _WebGL_webGL2ShaderProcessors__WEBPACK_IMPORTED_MODULE_6__["WebGL2ShaderProcessor"]; }); + +/* harmony import */ var _nativeEngine__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./nativeEngine */ "./Engines/nativeEngine.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NativeEngineOptions", function() { return _nativeEngine__WEBPACK_IMPORTED_MODULE_7__["NativeEngineOptions"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NativeEngine", function() { return _nativeEngine__WEBPACK_IMPORTED_MODULE_7__["NativeEngine"]; }); + + + + + + + + + + + +/***/ }), + +/***/ "./Engines/nativeEngine.ts": +/*!*********************************!*\ + !*** ./Engines/nativeEngine.ts ***! + \*********************************/ +/*! exports provided: NativeEngineOptions, NativeEngine */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NativeEngineOptions", function() { return NativeEngineOptions; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NativeEngine", function() { return NativeEngine; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Engines/engine */ "./Engines/engine.ts"); +/* harmony import */ var _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Materials/Textures/internalTexture */ "./Materials/Textures/internalTexture.ts"); +/* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Materials/Textures/texture */ "./Materials/Textures/texture.ts"); +/* harmony import */ var _Materials_effect__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Materials/effect */ "./Materials/effect.ts"); +/* harmony import */ var _Meshes_dataBuffer__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Meshes/dataBuffer */ "./Meshes/dataBuffer.ts"); +/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Misc/tools */ "./Misc/tools.ts"); +/* harmony import */ var _Misc_environmentTextureTools__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Misc/environmentTextureTools */ "./Misc/environmentTextureTools.ts"); +/* harmony import */ var _Materials_Textures_renderTargetCreationOptions__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Materials/Textures/renderTargetCreationOptions */ "./Materials/Textures/renderTargetCreationOptions.ts"); +/* harmony import */ var _Native_nativeShaderProcessor__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./Native/nativeShaderProcessor */ "./Engines/Native/nativeShaderProcessor.ts"); + + + + + + + + + + +var NativePipelineContext = /** @class */ (function () { + function NativePipelineContext() { + // TODO: async should be true? + this.isAsync = false; + this.isReady = false; + } + // TODO: what should this do? + NativePipelineContext.prototype._handlesSpectorRebuildCallback = function (onCompiled) { + throw new Error("Not implemented"); + }; + return NativePipelineContext; +}()); +var NativeDataBuffer = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](NativeDataBuffer, _super); + function NativeDataBuffer(id, data) { + var _this = _super.call(this) || this; + _this.id = id; + _this.data = data; + return _this; + } + return NativeDataBuffer; +}(_Meshes_dataBuffer__WEBPACK_IMPORTED_MODULE_5__["DataBuffer"])); +// Must match Filter enum in SpectreEngine.h. +var NativeFilter = /** @class */ (function () { + function NativeFilter() { + } + NativeFilter.POINT = 0; + NativeFilter.MINPOINT_MAGPOINT_MIPPOINT = NativeFilter.POINT; + NativeFilter.BILINEAR = 1; + NativeFilter.MINLINEAR_MAGLINEAR_MIPPOINT = NativeFilter.BILINEAR; + NativeFilter.TRILINEAR = 2; + NativeFilter.MINLINEAR_MAGLINEAR_MIPLINEAR = NativeFilter.TRILINEAR; + NativeFilter.ANISOTROPIC = 3; + NativeFilter.POINT_COMPARE = 4; + NativeFilter.TRILINEAR_COMPARE = 5; + NativeFilter.MINBILINEAR_MAGPOINT = 6; + NativeFilter.MINLINEAR_MAGPOINT_MIPLINEAR = NativeFilter.MINBILINEAR_MAGPOINT; + NativeFilter.MINPOINT_MAGPOINT_MIPLINEAR = 7; + NativeFilter.MINPOINT_MAGLINEAR_MIPPOINT = 8; + NativeFilter.MINPOINT_MAGLINEAR_MIPLINEAR = 9; + NativeFilter.MINLINEAR_MAGPOINT_MIPPOINT = 10; + return NativeFilter; +}()); +// Must match AddressMode enum in SpectreEngine.h. +var NativeAddressMode = /** @class */ (function () { + function NativeAddressMode() { + } + NativeAddressMode.WRAP = 0; + NativeAddressMode.MIRROR = 1; + NativeAddressMode.CLAMP = 2; + NativeAddressMode.BORDER = 3; + NativeAddressMode.MIRROR_ONCE = 4; + return NativeAddressMode; +}()); +// Must match BlendMode in SpectreEngine.h. +var NativeBlendMode = /** @class */ (function () { + function NativeBlendMode() { + } + NativeBlendMode.REPLACE = 0; + NativeBlendMode.OVER = 1; + NativeBlendMode.UNDER = 2; + NativeBlendMode.INSIDE = 3; + NativeBlendMode.ERASE = 4; + NativeBlendMode.NULL = 5; + NativeBlendMode.CLEAR = 6; + NativeBlendMode.STRAIGHT_REPLACE = 7; + NativeBlendMode.STRAIGHT_OVER = 8; + NativeBlendMode.STRAIGHT_ADD = 9; + NativeBlendMode.ADD = 10; + NativeBlendMode.SCREEN = 11; + NativeBlendMode.MULTIPLY = 12; + NativeBlendMode.MULTIPLY2X = 13; + NativeBlendMode.INTERPOLATE = 14; + NativeBlendMode.MINIMUM = 15; + NativeBlendMode.MAXIMUM = 16; + NativeBlendMode.MAXIMUM_ALPHA = 17; + NativeBlendMode.ADD_ALPHA = 18; + NativeBlendMode.BLACK_REPLACE = 19; + NativeBlendMode.BLACK_OVER = 20; + NativeBlendMode.BLACK_UNDER = 21; + NativeBlendMode.BLACK_INSIDE = 22; + NativeBlendMode.ALPHA_COVERAGE_MASK = 23; + NativeBlendMode.DUAL_COLOR_MULTIPLY_ADD = 24; + NativeBlendMode.COMBINE = 25; + NativeBlendMode.BLEND_OPAQUE = NativeBlendMode.REPLACE; + NativeBlendMode.BLEND_ALPHA_PREMULTIPLIED = NativeBlendMode.OVER; + NativeBlendMode.BLEND_ALPHA_STRAIGHT = NativeBlendMode.STRAIGHT_OVER; + return NativeBlendMode; +}()); +/** @hidden */ +var NativeEngineOptions = /** @class */ (function () { + function NativeEngineOptions() { + this.textureSize = 512; + this.deterministicLockstep = false; + this.lockstepMaxSteps = 4; + } + return NativeEngineOptions; +}()); + +/** @hidden */ +var NativeEngine = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](NativeEngine, _super); + function NativeEngine(options) { + if (options === void 0) { options = new NativeEngineOptions(); } + var _this = _super.call(this, null) || this; + _this._native = nativeEngine; + _this._nextBufferId = 0; + if (options.deterministicLockstep === undefined) { + options.deterministicLockstep = false; + } + if (options.lockstepMaxSteps === undefined) { + options.lockstepMaxSteps = 4; + } + _this._options = options; + _this._webGLVersion = 2; + _this.disableUniformBuffers = true; + // TODO: Initialize this more correctly based on the hardware capabilities. + // Init caps + _this._caps = new _Engines_engine__WEBPACK_IMPORTED_MODULE_1__["EngineCapabilities"](); + _this._caps.maxTexturesImageUnits = 16; + _this._caps.maxVertexTextureImageUnits = 16; + _this._caps.maxTextureSize = 512; + _this._caps.maxCubemapTextureSize = 512; + _this._caps.maxRenderTextureSize = 512; + _this._caps.maxVertexAttribs = 16; + _this._caps.maxVaryingVectors = 16; + _this._caps.maxFragmentUniformVectors = 16; + _this._caps.maxVertexUniformVectors = 16; + // Extensions + _this._caps.standardDerivatives = true; + _this._caps.astc = null; + _this._caps.s3tc = null; + _this._caps.pvrtc = null; + _this._caps.etc1 = null; + _this._caps.etc2 = null; + _this._caps.maxAnisotropy = 16; // TODO: Retrieve this smartly. Currently set to D3D11 maximum allowable value. + _this._caps.uintIndices = false; + _this._caps.fragmentDepthSupported = false; + _this._caps.highPrecisionShaderSupported = true; + _this._caps.colorBufferFloat = false; + _this._caps.textureFloat = false; + _this._caps.textureFloatLinearFiltering = false; + _this._caps.textureFloatRender = false; + _this._caps.textureHalfFloat = false; + _this._caps.textureHalfFloatLinearFiltering = false; + _this._caps.textureHalfFloatRender = false; + _this._caps.textureLOD = true; + _this._caps.drawBuffersExtension = false; + _this._caps.depthTextureExtension = false; + _this._caps.vertexArrayObject = true; + _this._caps.instancedArrays = false; + _Misc_tools__WEBPACK_IMPORTED_MODULE_6__["Tools"].Log("Babylon Native (v" + _Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].Version + ") launched"); + // Wrappers + if (typeof URL === "undefined") { + window.URL = { + createObjectURL: function () { }, + revokeObjectURL: function () { } + }; + } + if (typeof Blob === "undefined") { + window.Blob = function () { }; + } + // Shader processor + _this._shaderProcessor = new _Native_nativeShaderProcessor__WEBPACK_IMPORTED_MODULE_9__["NativeShaderProcessor"](); + return _this; + } + NativeEngine.prototype.isDeterministicLockStep = function () { + return this._options.deterministicLockstep; + }; + NativeEngine.prototype.getLockstepMaxSteps = function () { + return this._options.lockstepMaxSteps; + }; + NativeEngine.prototype.getHardwareScalingLevel = function () { + return 1.0; + }; + /** + * Can be used to override the current requestAnimationFrame requester. + * @hidden + */ + NativeEngine.prototype._queueNewFrame = function (bindedRenderFunction, requester) { + this._native.requestAnimationFrame(bindedRenderFunction); + return 0; + }; + NativeEngine.prototype.clear = function (color, backBuffer, depth, stencil) { + if (stencil === void 0) { stencil = false; } + this._native.clear(color.r, color.g, color.b, color.a, backBuffer, depth, stencil); + }; + NativeEngine.prototype.createIndexBuffer = function (indices) { + var data = this._normalizeIndexData(indices); + var buffer = new NativeDataBuffer(this._nextBufferId++, data); + buffer.references = 1; + buffer.is32Bits = (data.BYTES_PER_ELEMENT === 4); + return buffer; + }; + NativeEngine.prototype.createVertexBuffer = function (data) { + var buffer = new NativeDataBuffer(this._nextBufferId++, data); + buffer.references = 1; + return buffer; + }; + NativeEngine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) { + var vertexArray = this._native.createVertexArray(); + // Index + if (indexBuffer) { + if (!indexBuffer.nativeIndexBuffer) { + indexBuffer.nativeIndexBuffer = this._native.createIndexBuffer(indexBuffer.data); + } + this._native.recordIndexBuffer(vertexArray, indexBuffer.nativeIndexBuffer); + } + // Vertex + // Map the vertex buffers that point to the same underlying buffer. + var map = {}; + var attributes = effect.getAttributesNames(); + for (var index = 0; index < attributes.length; index++) { + var location_1 = effect.getAttributeLocation(index); + if (location_1 >= 0) { + var kind = attributes[index]; + var vertexBuffer = vertexBuffers[kind]; + if (vertexBuffer) { + var buffer = vertexBuffer.getBuffer(); + if (buffer) { + var entry = map[buffer.id]; + if (!entry) { + entry = { buffer: buffer, byteStride: vertexBuffer.byteStride, infos: [] }; + map[buffer.id] = entry; + } + // TODO: check if byteStride matches for all vertex buffers?? + entry.infos.push({ + location: location_1, + numElements: vertexBuffer.getSize(), + type: vertexBuffer.type, + normalized: vertexBuffer.normalized, + byteOffset: vertexBuffer.byteOffset + }); + } + } + } + } + // Record vertex buffer for each unique buffer. + for (var id in map) { + var entry = map[id]; + var buffer = entry.buffer; + if (!buffer.nativeVertexBuffer) { + // TODO: handle non-normalized non-float data (shader always expects float data) + var data = ArrayBuffer.isView(buffer.data) ? buffer.data : new Float32Array(buffer.data); + buffer.nativeVertexBuffer = this._native.createVertexBuffer(data, entry.byteStride, entry.infos); + } + this._native.recordVertexBuffer(vertexArray, buffer.nativeVertexBuffer); + } + return vertexArray; + }; + NativeEngine.prototype.bindVertexArrayObject = function (vertexArray) { + this._native.bindVertexArray(vertexArray); + }; + NativeEngine.prototype.releaseVertexArrayObject = function (vertexArray) { + this._native.deleteVertexArray(vertexArray); + }; + NativeEngine.prototype.getAttributes = function (pipelineContext, attributesNames) { + var nativePipelineContext = pipelineContext; + return this._native.getAttributes(nativePipelineContext.nativeProgram, attributesNames); + }; + /** + * Draw a list of indexed primitives + * @param fillMode defines the primitive to use + * @param indexStart defines the starting index + * @param indexCount defines the number of index to draw + * @param instancesCount defines the number of instances to draw (if instanciation is enabled) + */ + NativeEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) { + // Apply states + this._drawCalls.addCount(1, false); + // TODO: Make this implementation more robust like core Engine version. + // Render + //var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT; + //var mult = this._uintIndicesCurrentlySet ? 4 : 2; + // if (instancesCount) { + // this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount); + // } else { + this._native.drawIndexed(fillMode, indexStart, indexCount); + // } + }; + /** + * Draw a list of unindexed primitives + * @param fillMode defines the primitive to use + * @param verticesStart defines the index of first vertex to draw + * @param verticesCount defines the count of vertices to draw + * @param instancesCount defines the number of instances to draw (if instanciation is enabled) + */ + NativeEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) { + // Apply states + this._drawCalls.addCount(1, false); + // TODO: Make this implementation more robust like core Engine version. + // if (instancesCount) { + // this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount); + // } else { + this._native.draw(fillMode, verticesStart, verticesCount); + // } + }; + /** + * Create a new effect (used to store vertex/fragment shaders) + * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx) + * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object + * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use + * @param samplers defines an array of string used to represent textures + * @param defines defines the string containing the defines to use to compile the shaders + * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails + * @param onCompiled defines a function to call when the effect creation is successful + * @param onError defines a function to call when the effect creation has failed + * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights) + * @returns the new Effect + */ + NativeEngine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) { + var vertex = baseName.vertexElement || baseName.vertex || baseName; + var fragment = baseName.fragmentElement || baseName.fragment || baseName; + var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines); + if (this._compiledEffects[name]) { + var compiledEffect = this._compiledEffects[name]; + if (onCompiled && compiledEffect.isReady()) { + onCompiled(compiledEffect); + } + return compiledEffect; + } + var effect = new _Materials_effect__WEBPACK_IMPORTED_MODULE_4__["Effect"](baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters, false); + effect._key = name; + this._compiledEffects[name] = effect; + return effect; + }; + NativeEngine.prototype.createPipelineContext = function () { + return new NativePipelineContext(); + }; + NativeEngine.prototype._preparePipelineContext = function (pipelineContext, vertexSourceCode, fragmentSourceCode, createAsRaw, rebuildRebind, defines, transformFeedbackVaryings) { + var nativePipelineContext = pipelineContext; + if (createAsRaw) { + nativePipelineContext.nativeProgram = this.createRawShaderProgram(pipelineContext, vertexSourceCode, fragmentSourceCode, undefined, transformFeedbackVaryings); + } + else { + nativePipelineContext.nativeProgram = this.createShaderProgram(pipelineContext, vertexSourceCode, fragmentSourceCode, defines, undefined, transformFeedbackVaryings); + } + }; + /** @hidden */ + NativeEngine.prototype._isRenderingStateCompiled = function (pipelineContext) { + // TODO: support async shader compilcation + return true; + }; + /** @hidden */ + NativeEngine.prototype._executeWhenRenderingStateIsCompiled = function (pipelineContext, action) { + // TODO: support async shader compilcation + action(); + }; + NativeEngine.prototype.createRawShaderProgram = function (pipelineContext, vertexCode, fragmentCode, context, transformFeedbackVaryings) { + if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; } + throw new Error("Not Supported"); + }; + NativeEngine.prototype.createShaderProgram = function (pipelineContext, vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) { + if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; } + this.onBeforeShaderCompilationObservable.notifyObservers(this); + var program = this._native.createProgram(vertexCode, fragmentCode); + this.onAfterShaderCompilationObservable.notifyObservers(this); + return program; + }; + NativeEngine.prototype._setProgram = function (program) { + if (this._currentProgram !== program) { + this._native.setProgram(program); + this._currentProgram = program; + } + }; + NativeEngine.prototype._releaseEffect = function (effect) { + // TODO + }; + NativeEngine.prototype._deletePipelineContext = function (pipelineContext) { + // TODO + }; + NativeEngine.prototype.getUniforms = function (pipelineContext, uniformsNames) { + var nativePipelineContext = pipelineContext; + return this._native.getUniforms(nativePipelineContext.nativeProgram, uniformsNames); + }; + NativeEngine.prototype.bindUniformBlock = function (pipelineContext, blockName, index) { + // TODO + throw new Error("Not Implemented"); + }; + NativeEngine.prototype.bindSamplers = function (effect) { + var nativePipelineContext = effect.getPipelineContext(); + this._setProgram(nativePipelineContext.nativeProgram); + // TODO: share this with engine? + var samplers = effect.getSamplers(); + for (var index = 0; index < samplers.length; index++) { + var uniform = effect.getUniform(samplers[index]); + if (uniform) { + this._boundUniforms[index] = uniform; + } + } + this._currentEffect = null; + }; + NativeEngine.prototype.setMatrix = function (uniform, matrix) { + if (!uniform) { + return; + } + this._native.setMatrix(uniform, matrix.toArray()); + }; + NativeEngine.prototype.getRenderWidth = function (useScreen) { + if (useScreen === void 0) { useScreen = false; } + if (!useScreen && this._currentRenderTarget) { + return this._currentRenderTarget.width; + } + return this._native.getRenderWidth(); + }; + NativeEngine.prototype.getRenderHeight = function (useScreen) { + if (useScreen === void 0) { useScreen = false; } + if (!useScreen && this._currentRenderTarget) { + return this._currentRenderTarget.height; + } + return this._native.getRenderHeight(); + }; + NativeEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) { + // TODO: Implement. + this._cachedViewport = viewport; + }; + NativeEngine.prototype.setState = function (culling, zOffset, force, reverseSide) { + if (zOffset === void 0) { zOffset = 0; } + if (reverseSide === void 0) { reverseSide = false; } + this._native.setState(culling, zOffset, reverseSide); + }; + /** + * Set the z offset to apply to current rendering + * @param value defines the offset to apply + */ + NativeEngine.prototype.setZOffset = function (value) { + this._native.setZOffset(value); + }; + /** + * Gets the current value of the zOffset + * @returns the current zOffset state + */ + NativeEngine.prototype.getZOffset = function () { + return this._native.getZOffset(); + }; + /** + * Enable or disable depth buffering + * @param enable defines the state to set + */ + NativeEngine.prototype.setDepthBuffer = function (enable) { + this._native.setDepthTest(enable); + }; + /** + * Gets a boolean indicating if depth writing is enabled + * @returns the current depth writing state + */ + NativeEngine.prototype.getDepthWrite = function () { + return this._native.getDepthWrite(); + }; + /** + * Enable or disable depth writing + * @param enable defines the state to set + */ + NativeEngine.prototype.setDepthWrite = function (enable) { + this._native.setDepthWrite(enable); + }; + /** + * Enable or disable color writing + * @param enable defines the state to set + */ + NativeEngine.prototype.setColorWrite = function (enable) { + this._native.setColorWrite(enable); + this._colorWrite = enable; + }; + /** + * Gets a boolean indicating if color writing is enabled + * @returns the current color writing state + */ + NativeEngine.prototype.getColorWrite = function () { + return this._colorWrite; + }; + /** + * Sets alpha constants used by some alpha blending modes + * @param r defines the red component + * @param g defines the green component + * @param b defines the blue component + * @param a defines the alpha component + */ + NativeEngine.prototype.setAlphaConstants = function (r, g, b, a) { + throw new Error("Setting alpha blend constant color not yet implemented."); + }; + /** + * Sets the current alpha mode + * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX) + * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default) + * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered + */ + NativeEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) { + if (noDepthWriteChange === void 0) { noDepthWriteChange = false; } + if (this._alphaMode === mode) { + return; + } + this._native.setBlendMode(this._getBlendMode(mode)); + if (!noDepthWriteChange) { + this.setDepthWrite(mode === _Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].ALPHA_DISABLE); + } + this._alphaMode = mode; + }; + // Returns a NativeBlendMode.XXXX value. + // Note: Many blend modes intentionally not implemented. If more are needed, they should be added. + NativeEngine.prototype._getBlendMode = function (mode) { + switch (mode) { + case _Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].ALPHA_DISABLE: + return NativeBlendMode.REPLACE; + case _Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].ALPHA_PREMULTIPLIED_PORTERDUFF: + return NativeBlendMode.OVER; + case _Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].ALPHA_COMBINE: + return NativeBlendMode.COMBINE; + case _Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].ALPHA_SCREENMODE: + return NativeBlendMode.SCREEN; + default: + throw new Error("Unexpected alpha mode: " + mode + "."); + } + }; + /** + * Gets the current alpha mode + * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered + * @returns the current alpha mode + */ + NativeEngine.prototype.getAlphaMode = function () { + return this._alphaMode; + }; + NativeEngine.prototype.setIntArray = function (uniform, array) { + if (!uniform) { + return; + } + this._native.setIntArray(uniform, array); + }; + NativeEngine.prototype.setIntArray2 = function (uniform, array) { + if (!uniform) { + return; + } + this._native.setIntArray2(uniform, array); + }; + NativeEngine.prototype.setIntArray3 = function (uniform, array) { + if (!uniform) { + return; + } + this._native.setIntArray3(uniform, array); + }; + NativeEngine.prototype.setIntArray4 = function (uniform, array) { + if (!uniform) { + return; + } + this._native.setIntArray4(uniform, array); + }; + NativeEngine.prototype.setFloatArray = function (uniform, array) { + if (!uniform) { + return; + } + this._native.setFloatArray(uniform, array); + }; + NativeEngine.prototype.setFloatArray2 = function (uniform, array) { + if (!uniform) { + return; + } + this._native.setFloatArray2(uniform, array); + }; + NativeEngine.prototype.setFloatArray3 = function (uniform, array) { + if (!uniform) { + return; + } + this._native.setFloatArray3(uniform, array); + }; + NativeEngine.prototype.setFloatArray4 = function (uniform, array) { + if (!uniform) { + return; + } + this._native.setFloatArray4(uniform, array); + }; + NativeEngine.prototype.setArray = function (uniform, array) { + if (!uniform) { + return; + } + this._native.setFloatArray(uniform, array); + }; + NativeEngine.prototype.setArray2 = function (uniform, array) { + if (!uniform) { + return; + } + this._native.setFloatArray2(uniform, array); + }; + NativeEngine.prototype.setArray3 = function (uniform, array) { + if (!uniform) { + return; + } + this._native.setFloatArray3(uniform, array); + }; + NativeEngine.prototype.setArray4 = function (uniform, array) { + if (!uniform) { + return; + } + this._native.setFloatArray4(uniform, array); + }; + NativeEngine.prototype.setMatrices = function (uniform, matrices) { + if (!uniform) { + return; + } + this._native.setMatrices(uniform, matrices); + }; + NativeEngine.prototype.setMatrix3x3 = function (uniform, matrix) { + if (!uniform) { + return; + } + this._native.setMatrix3x3(uniform, matrix); + }; + NativeEngine.prototype.setMatrix2x2 = function (uniform, matrix) { + if (!uniform) { + return; + } + this._native.setMatrix2x2(uniform, matrix); + }; + NativeEngine.prototype.setFloat = function (uniform, value) { + if (!uniform) { + return; + } + this._native.setFloat(uniform, value); + }; + NativeEngine.prototype.setFloat2 = function (uniform, x, y) { + if (!uniform) { + return; + } + this._native.setFloat2(uniform, x, y); + }; + NativeEngine.prototype.setFloat3 = function (uniform, x, y, z) { + if (!uniform) { + return; + } + this._native.setFloat3(uniform, x, y, z); + }; + NativeEngine.prototype.setBool = function (uniform, bool) { + if (!uniform) { + return; + } + this._native.setBool(uniform, bool); + }; + NativeEngine.prototype.setFloat4 = function (uniform, x, y, z, w) { + if (!uniform) { + return; + } + this._native.setFloat4(uniform, x, y, z, w); + }; + NativeEngine.prototype.setColor3 = function (uniform, color3) { + if (!uniform) { + return; + } + this._native.setFloat3(uniform, color3.r, color3.g, color3.b); + }; + NativeEngine.prototype.setColor4 = function (uniform, color3, alpha) { + if (!uniform) { + return; + } + this._native.setFloat4(uniform, color3.r, color3.g, color3.b, alpha); + }; + NativeEngine.prototype.wipeCaches = function (bruteForce) { + if (this.preventCacheWipeBetweenFrames) { + return; + } + this.resetTextureCache(); + this._currentEffect = null; + if (bruteForce) { + this._currentProgram = null; + this._stencilState.reset(); + this._depthCullingState.reset(); + this._alphaState.reset(); + } + this._cachedVertexBuffers = null; + this._cachedIndexBuffer = null; + this._cachedEffectForVertexBuffers = null; + }; + NativeEngine.prototype._createTexture = function () { + return this._native.createTexture(); + }; + NativeEngine.prototype._deleteTexture = function (texture) { + this._native.deleteTexture(texture); + }; + // TODO: Refactor to share more logic with babylon.engine.ts version. + /** + * Usually called from BABYLON.Texture.ts. + * Passed information to create a WebGLTexture + * @param urlArg defines a value which contains one of the following: + * * A conventional http URL, e.g. 'http://...' or 'file://...' + * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...' + * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg' + * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file + * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file + * @param scene needed for loading to the correct scene + * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE) + * @param onLoad optional callback to be called upon successful completion + * @param onError optional callback to be called upon failure + * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), or a Blob + * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities + * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures + * @param forcedExtension defines the extension to use to pick the right loader + * @returns a InternalTexture for assignment back into BABYLON.Texture + */ + NativeEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) { + var _this = this; + if (samplingMode === void 0) { samplingMode = _Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].TEXTURE_TRILINEAR_SAMPLINGMODE; } + if (onLoad === void 0) { onLoad = null; } + if (onError === void 0) { onError = null; } + if (buffer === void 0) { buffer = null; } + if (fallback === void 0) { fallback = null; } + if (format === void 0) { format = null; } + if (forcedExtension === void 0) { forcedExtension = null; } + var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback + var fromData = url.substr(0, 5) === "data:"; + var fromBlob = url.substr(0, 5) === "blob:"; + var isBase64 = fromData && url.indexOf("base64") !== -1; + var texture = fallback ? fallback : new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_2__["InternalTexture"](this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_2__["InternalTexture"].DATASOURCE_URL); + // establish the file extension, if possible + var lastDot = url.lastIndexOf('.'); + var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : ""); + // TODO: Add support for compressed texture formats. + var textureFormatInUse = null; + var loader = null; + for (var _i = 0, _a = _Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"]._TextureLoaders; _i < _a.length; _i++) { + var availableLoader = _a[_i]; + if (availableLoader.canLoad(extension, textureFormatInUse, fallback, isBase64, buffer ? true : false)) { + loader = availableLoader; + break; + } + } + if (loader) { + url = loader.transformUrl(url, textureFormatInUse); + } + if (scene) { + scene._addPendingData(texture); + } + texture.url = url; + texture.generateMipMaps = !noMipmap; + texture.samplingMode = samplingMode; + texture.invertY = invertY; + if (!this.doNotHandleContextLost) { + // Keep a link to the buffer only if we plan to handle context lost + texture._buffer = buffer; + } + var onLoadObserver = null; + if (onLoad && !fallback) { + onLoadObserver = texture.onLoadedObservable.add(onLoad); + } + if (!fallback) { + this._internalTexturesCache.push(texture); + } + var onInternalError = function (message, exception) { + if (scene) { + scene._removePendingData(texture); + } + var customFallback = false; + if (loader) { + var fallbackUrl = loader.getFallbackTextureUrl(url, textureFormatInUse); + if (fallbackUrl) { + // Add Back + customFallback = true; + _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture); + } + } + if (!customFallback) { + if (onLoadObserver) { + texture.onLoadedObservable.remove(onLoadObserver); + } + if (_Misc_tools__WEBPACK_IMPORTED_MODULE_6__["Tools"].UseFallbackTexture) { + _this.createTexture(_Misc_tools__WEBPACK_IMPORTED_MODULE_6__["Tools"].fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture); + } + } + if (onError) { + onError(message || "Unknown error", exception); + } + }; + // processing for non-image formats + if (loader) { + throw new Error("Loading textures from IInternalTextureLoader not yet implemented."); + // var callback = (data: string | ArrayBuffer) => { + // loader!.loadData(data as ArrayBuffer, texture, (width: number, height: number, loadMipmap: boolean, isCompressed: boolean, done: () => void) => { + // this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, () => { + // done(); + // return false; + // }, + // samplingMode); + // }); + // } + // if (!buffer) { + // this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, (request?: XMLHttpRequest, exception?: any) => { + // onInternalError("Unable to load " + (request ? request.responseURL : url, exception)); + // }); + // } else { + // callback(buffer as ArrayBuffer); + // } + } + else { + var onload = function (data, responseURL) { + if (typeof (data) === "string") { + throw new Error("Loading textures from string data not yet implemented."); + } + if (fromBlob && !_this.doNotHandleContextLost) { + // We need to store the image if we need to rebuild the texture + // in case of a webgl context lost + texture._buffer = data; + } + var webGLTexture = texture._webGLTexture; + if (!webGLTexture) { + // this.resetTextureCache(); + if (scene) { + scene._removePendingData(texture); + } + return; + } + _this._native.loadTexture(webGLTexture, data, !noMipmap); + if (invertY) { + throw new Error("Support for textures with inverted Y coordinates not yet implemented."); + } + //this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false)); + texture.baseWidth = _this._native.getTextureWidth(webGLTexture); + texture.baseHeight = _this._native.getTextureHeight(webGLTexture); + texture.width = texture.baseWidth; + texture.height = texture.baseHeight; + texture.isReady = true; + var filter = _this._getSamplingFilter(samplingMode); + _this._native.setTextureSampling(webGLTexture, filter); + // this.resetTextureCache(); + if (scene) { + scene._removePendingData(texture); + } + texture.onLoadedObservable.notifyObservers(texture); + texture.onLoadedObservable.clear(); + }; + if (buffer instanceof ArrayBuffer) { + onload(buffer); + } + else if (buffer instanceof Blob) { + throw new Error("Loading texture from Blob not yet implemented."); + } + else if (!fromData) { + var onLoadFileError = function (request, exception) { + onInternalError("Failed to retrieve " + url + ".", exception); + }; + _Misc_tools__WEBPACK_IMPORTED_MODULE_6__["Tools"].LoadFile(url, onload, undefined, undefined, /*useArrayBuffer*/ true, onLoadFileError); + } + else { + onload(_Misc_tools__WEBPACK_IMPORTED_MODULE_6__["Tools"].DecodeBase64(buffer)); + } + } + return texture; + }; + /** + * Creates a cube texture + * @param rootUrl defines the url where the files to load is located + * @param scene defines the current scene + * @param files defines the list of files to load (1 per face) + * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default) + * @param onLoad defines an optional callback raised when the texture is loaded + * @param onError defines an optional callback raised if there is an issue to load the texture + * @param format defines the format of the data + * @param forcedExtension defines the extension to use to pick the right loader + * @param createPolynomials if a polynomial sphere should be created for the cube texture + * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness + * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness + * @param fallback defines texture to use while falling back when (compressed) texture file not found. + * @returns the cube texture as an InternalTexture + */ + NativeEngine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) { + var _this = this; + if (onLoad === void 0) { onLoad = null; } + if (onError === void 0) { onError = null; } + if (forcedExtension === void 0) { forcedExtension = null; } + if (createPolynomials === void 0) { createPolynomials = false; } + if (lodScale === void 0) { lodScale = 0; } + if (lodOffset === void 0) { lodOffset = 0; } + if (fallback === void 0) { fallback = null; } + var texture = fallback ? fallback : new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_2__["InternalTexture"](this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_2__["InternalTexture"].DATASOURCE_CUBE); + texture.isCube = true; + texture.url = rootUrl; + texture.generateMipMaps = !noMipmap; + texture._lodGenerationScale = lodScale; + texture._lodGenerationOffset = lodOffset; + if (!this._doNotHandleContextLost) { + texture._extension = forcedExtension; + texture._files = files; + } + var lastDot = rootUrl.lastIndexOf('.'); + var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : ""); + if (extension === ".env") { + var onloaddata = function (data) { + data = data; + var info = _Misc_environmentTextureTools__WEBPACK_IMPORTED_MODULE_7__["EnvironmentTextureTools"].GetEnvInfo(data); + texture.width = info.width; + texture.height = info.width; + _Misc_environmentTextureTools__WEBPACK_IMPORTED_MODULE_7__["EnvironmentTextureTools"].UploadEnvSpherical(texture, info); + if (info.version !== 1) { + throw new Error("Unsupported babylon environment map version \"" + info.version + "\""); + } + var specularInfo = info.specular; + if (!specularInfo) { + throw new Error("Nothing else parsed so far"); + } + texture._lodGenerationScale = specularInfo.lodGenerationScale; + var imageData = _Misc_environmentTextureTools__WEBPACK_IMPORTED_MODULE_7__["EnvironmentTextureTools"].CreateImageDataArrayBufferViews(data, info); + texture.format = _Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].TEXTUREFORMAT_RGBA; + texture.type = _Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].TEXTURETYPE_UNSIGNED_INT; + texture.generateMipMaps = true; + texture.getEngine().updateTextureSamplingMode(_Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_3__["Texture"].TRILINEAR_SAMPLINGMODE, texture); + texture._isRGBD = true; + texture.invertY = true; + _this._native.loadCubeTexture(texture._webGLTexture, imageData, true); + texture.isReady = true; + if (onLoad) { + onLoad(); + } + }; + if (files && files.length === 6) { + throw new Error("Multi-file loading not yet supported."); + } + else { + var onInternalError = function (request, exception) { + if (onError && request) { + onError(request.status + " " + request.statusText, exception); + } + }; + this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError); + } + } + else { + throw new Error("Cannot load cubemap: non-ENV format not supported."); + } + this._internalTexturesCache.push(texture); + return texture; + }; + // Returns a NativeFilter.XXXX value. + NativeEngine.prototype._getSamplingFilter = function (samplingMode) { + switch (samplingMode) { + case _Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].TEXTURE_BILINEAR_SAMPLINGMODE: + return NativeFilter.MINLINEAR_MAGLINEAR_MIPPOINT; + case _Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].TEXTURE_TRILINEAR_SAMPLINGMODE: + return NativeFilter.MINLINEAR_MAGLINEAR_MIPLINEAR; + case _Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].TEXTURE_NEAREST_SAMPLINGMODE: + return NativeFilter.MINPOINT_MAGPOINT_MIPLINEAR; + case _Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].TEXTURE_NEAREST_NEAREST_MIPNEAREST: + return NativeFilter.MINPOINT_MAGPOINT_MIPPOINT; + case _Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].TEXTURE_NEAREST_LINEAR_MIPNEAREST: + return NativeFilter.MINLINEAR_MAGPOINT_MIPPOINT; + case _Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].TEXTURE_NEAREST_LINEAR_MIPLINEAR: + return NativeFilter.MINLINEAR_MAGPOINT_MIPLINEAR; + case _Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].TEXTURE_NEAREST_LINEAR: + return NativeFilter.MINLINEAR_MAGPOINT_MIPLINEAR; + case _Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].TEXTURE_NEAREST_NEAREST: + return NativeFilter.MINPOINT_MAGPOINT_MIPPOINT; + case _Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].TEXTURE_LINEAR_NEAREST_MIPNEAREST: + return NativeFilter.MINPOINT_MAGLINEAR_MIPPOINT; + case _Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].TEXTURE_LINEAR_NEAREST_MIPLINEAR: + return NativeFilter.MINPOINT_MAGLINEAR_MIPLINEAR; + case _Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].TEXTURE_LINEAR_LINEAR: + return NativeFilter.MINLINEAR_MAGLINEAR_MIPLINEAR; + case _Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].TEXTURE_LINEAR_NEAREST: + return NativeFilter.MINPOINT_MAGLINEAR_MIPLINEAR; + default: + throw new Error("Unexpected sampling mode: " + samplingMode + "."); + } + }; + NativeEngine.prototype.createRenderTargetTexture = function (size, options) { + var fullOptions = new _Materials_Textures_renderTargetCreationOptions__WEBPACK_IMPORTED_MODULE_8__["RenderTargetCreationOptions"](); + if (options !== undefined && typeof options === "object") { + fullOptions.generateMipMaps = options.generateMipMaps; + fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer; + fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer; + fullOptions.type = options.type === undefined ? _Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].TEXTURETYPE_UNSIGNED_INT : options.type; + fullOptions.samplingMode = options.samplingMode === undefined ? _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_3__["Texture"].TRILINEAR_SAMPLINGMODE : options.samplingMode; + } + else { + fullOptions.generateMipMaps = options; + fullOptions.generateDepthBuffer = true; + fullOptions.generateStencilBuffer = false; + fullOptions.type = _Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].TEXTURETYPE_UNSIGNED_INT; + fullOptions.samplingMode = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_3__["Texture"].TRILINEAR_SAMPLINGMODE; + } + var texture = new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_2__["InternalTexture"](this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_2__["InternalTexture"].DATASOURCE_RENDERTARGET); + var width = size.width || size; + var height = size.height || size; + texture._depthStencilBuffer = {}; + texture._framebuffer = {}; + texture.baseWidth = width; + texture.baseHeight = height; + texture.width = width; + texture.height = height; + texture.isReady = true; + texture.samples = 1; + texture.generateMipMaps = fullOptions.generateMipMaps ? true : false; + texture.samplingMode = fullOptions.samplingMode; + texture.type = fullOptions.type; + texture._generateDepthBuffer = fullOptions.generateDepthBuffer; + texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false; + this._internalTexturesCache.push(texture); + return texture; + }; + NativeEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) { + if (texture._webGLTexture) { + var filter = this._getSamplingFilter(samplingMode); + this._native.setTextureSampling(texture._webGLTexture, filter); + } + texture.samplingMode = samplingMode; + }; + NativeEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) { + throw new Error("bindFramebuffer not yet implemented."); + }; + NativeEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) { + if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; } + throw new Error("unBindFramebuffer not yet implemented."); + }; + NativeEngine.prototype.createDynamicVertexBuffer = function (data) { + throw new Error("createDynamicVertexBuffer not yet implemented."); + }; + NativeEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) { + if (offset === void 0) { offset = 0; } + throw new Error("updateDynamicIndexBuffer not yet implemented."); + }; + /** + * Updates a dynamic vertex buffer. + * @param vertexBuffer the vertex buffer to update + * @param data the data used to update the vertex buffer + * @param byteOffset the byte offset of the data (optional) + * @param byteLength the byte length of the data (optional) + */ + NativeEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) { + throw new Error("updateDynamicVertexBuffer not yet implemented."); + }; + // TODO: Refactor to share more logic with base Engine implementation. + NativeEngine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) { + if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; } + if (depthStencilTexture === void 0) { depthStencilTexture = false; } + var uniform = this._boundUniforms[channel]; + if (!uniform) { + return false; + } + // Not ready? + if (!texture) { + if (this._boundTexturesCache[channel] != null) { + this._activeChannel = channel; + this._native.setTexture(uniform, null); + } + return false; + } + // Video + if (texture.video) { + this._activeChannel = channel; + texture.update(); + } + else if (texture.delayLoadState === _Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].DELAYLOADSTATE_NOTLOADED) { // Delay loading + texture.delayLoad(); + return false; + } + var internalTexture; + if (depthStencilTexture) { + internalTexture = texture.depthStencilTexture; + } + else if (texture.isReady()) { + internalTexture = texture.getInternalTexture(); + } + else if (texture.isCube) { + internalTexture = this.emptyCubeTexture; + } + else if (texture.is3D) { + internalTexture = this.emptyTexture3D; + } + else { + internalTexture = this.emptyTexture; + } + this._activeChannel = channel; + if (!internalTexture || + !internalTexture._webGLTexture) { + return false; + } + this._native.setTextureWrapMode(internalTexture._webGLTexture, this._getAddressMode(texture.wrapU), this._getAddressMode(texture.wrapV), this._getAddressMode(texture.wrapR)); + this._updateAnisotropicLevel(texture); + this._native.setTexture(uniform, internalTexture._webGLTexture); + return true; + }; + // TODO: Share more of this logic with the base implementation. + // TODO: Rename to match naming in base implementation once refactoring allows different parameters. + NativeEngine.prototype._updateAnisotropicLevel = function (texture) { + var internalTexture = texture.getInternalTexture(); + var value = texture.anisotropicFilteringLevel; + if (!internalTexture || !internalTexture._webGLTexture) { + return; + } + if (internalTexture._cachedAnisotropicFilteringLevel !== value) { + this._native.setTextureAnisotropicLevel(internalTexture._webGLTexture, value); + internalTexture._cachedAnisotropicFilteringLevel = value; + } + }; + // Returns a NativeAddressMode.XXX value. + NativeEngine.prototype._getAddressMode = function (wrapMode) { + switch (wrapMode) { + case _Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].TEXTURE_WRAP_ADDRESSMODE: + return NativeAddressMode.WRAP; + case _Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].TEXTURE_CLAMP_ADDRESSMODE: + return NativeAddressMode.CLAMP; + case _Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].TEXTURE_MIRROR_ADDRESSMODE: + return NativeAddressMode.MIRROR; + default: + throw new Error("Unexpected wrap mode: " + wrapMode + "."); + } + }; + /** @hidden */ + NativeEngine.prototype._bindTexture = function (channel, texture) { + throw new Error("_bindTexture not implemented."); + }; + NativeEngine.prototype._deleteBuffer = function (buffer) { + if (buffer.nativeIndexBuffer) { + this._native.deleteIndexBuffer(buffer.nativeIndexBuffer); + delete buffer.nativeIndexBuffer; + } + if (buffer.nativeVertexBuffer) { + this._native.deleteVertexBuffer(buffer.nativeVertexBuffer); + delete buffer.nativeVertexBuffer; + } + }; + NativeEngine.prototype.releaseEffects = function () { + // TODO + }; + /** @hidden */ + NativeEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) { + if (faceIndex === void 0) { faceIndex = 0; } + if (lod === void 0) { lod = 0; } + throw new Error("_uploadCompressedDataToTextureDirectly not implemented."); + }; + /** @hidden */ + NativeEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) { + if (faceIndex === void 0) { faceIndex = 0; } + if (lod === void 0) { lod = 0; } + throw new Error("_uploadDataToTextureDirectly not implemented."); + }; + /** @hidden */ + NativeEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) { + if (faceIndex === void 0) { faceIndex = 0; } + if (lod === void 0) { lod = 0; } + throw new Error("_uploadArrayBufferViewToTexture not implemented."); + }; + /** @hidden */ + NativeEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) { + if (faceIndex === void 0) { faceIndex = 0; } + if (lod === void 0) { lod = 0; } + throw new Error("_uploadArrayBufferViewToTexture not implemented."); + }; + return NativeEngine; +}(_Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"])); + + + +/***/ }), + +/***/ "./Engines/nullEngine.ts": +/*!*******************************!*\ + !*** ./Engines/nullEngine.ts ***! + \*******************************/ +/*! exports provided: NullEngineOptions, NullEngine */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* WEBPACK VAR INJECTION */(function(global) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NullEngineOptions", function() { return NullEngineOptions; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NullEngine", function() { return NullEngine; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts"); +/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Engines/engine */ "./Engines/engine.ts"); +/* harmony import */ var _Materials_Textures_renderTargetCreationOptions__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Materials/Textures/renderTargetCreationOptions */ "./Materials/Textures/renderTargetCreationOptions.ts"); +/* harmony import */ var _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Materials/Textures/internalTexture */ "./Materials/Textures/internalTexture.ts"); +/* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./constants */ "./Engines/constants.ts"); +/* harmony import */ var _Meshes_dataBuffer__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Meshes/dataBuffer */ "./Meshes/dataBuffer.ts"); + + + + + + + +/** + * Options to create the null engine + */ +var NullEngineOptions = /** @class */ (function () { + function NullEngineOptions() { + /** + * Render width (Default: 512) + */ + this.renderWidth = 512; + /** + * Render height (Default: 256) + */ + this.renderHeight = 256; + /** + * Texture size (Default: 512) + */ + this.textureSize = 512; + /** + * If delta time between frames should be constant + * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep + */ + this.deterministicLockstep = false; + /** + * Maximum about of steps between frames (Default: 4) + * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep + */ + this.lockstepMaxSteps = 4; + } + return NullEngineOptions; +}()); + +/** + * The null engine class provides support for headless version of babylon.js. + * This can be used in server side scenario or for testing purposes + */ +var NullEngine = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](NullEngine, _super); + function NullEngine(options) { + if (options === void 0) { options = new NullEngineOptions(); } + var _this = _super.call(this, null) || this; + if (options.deterministicLockstep === undefined) { + options.deterministicLockstep = false; + } + if (options.lockstepMaxSteps === undefined) { + options.lockstepMaxSteps = 4; + } + _this._options = options; + // Init caps + // We consider we are on a webgl1 capable device + _this._caps = new _Engines_engine__WEBPACK_IMPORTED_MODULE_2__["EngineCapabilities"](); + _this._caps.maxTexturesImageUnits = 16; + _this._caps.maxVertexTextureImageUnits = 16; + _this._caps.maxTextureSize = 512; + _this._caps.maxCubemapTextureSize = 512; + _this._caps.maxRenderTextureSize = 512; + _this._caps.maxVertexAttribs = 16; + _this._caps.maxVaryingVectors = 16; + _this._caps.maxFragmentUniformVectors = 16; + _this._caps.maxVertexUniformVectors = 16; + // Extensions + _this._caps.standardDerivatives = false; + _this._caps.astc = null; + _this._caps.s3tc = null; + _this._caps.pvrtc = null; + _this._caps.etc1 = null; + _this._caps.etc2 = null; + _this._caps.textureAnisotropicFilterExtension = null; + _this._caps.maxAnisotropy = 0; + _this._caps.uintIndices = false; + _this._caps.fragmentDepthSupported = false; + _this._caps.highPrecisionShaderSupported = true; + _this._caps.colorBufferFloat = false; + _this._caps.textureFloat = false; + _this._caps.textureFloatLinearFiltering = false; + _this._caps.textureFloatRender = false; + _this._caps.textureHalfFloat = false; + _this._caps.textureHalfFloatLinearFiltering = false; + _this._caps.textureHalfFloatRender = false; + _this._caps.textureLOD = false; + _this._caps.drawBuffersExtension = false; + _this._caps.depthTextureExtension = false; + _this._caps.vertexArrayObject = false; + _this._caps.instancedArrays = false; + _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Log("Babylon.js v" + _Engines_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].Version + " - Null engine"); + // Wrappers + var theCurrentGlobal = (typeof self !== "undefined" ? self : typeof global !== "undefined" ? global : window); + if (typeof URL === "undefined") { + theCurrentGlobal.URL = { + createObjectURL: function () { }, + revokeObjectURL: function () { } + }; + } + if (typeof Blob === "undefined") { + theCurrentGlobal.Blob = function () { }; + } + return _this; + } + /** + * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep + */ + NullEngine.prototype.isDeterministicLockStep = function () { + return this._options.deterministicLockstep; + }; + /** @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep */ + NullEngine.prototype.getLockstepMaxSteps = function () { + return this._options.lockstepMaxSteps; + }; + /** + * Sets hardware scaling, used to save performance if needed + * @see https://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer + */ + NullEngine.prototype.getHardwareScalingLevel = function () { + return 1.0; + }; + NullEngine.prototype.createVertexBuffer = function (vertices) { + var buffer = new _Meshes_dataBuffer__WEBPACK_IMPORTED_MODULE_6__["DataBuffer"](); + buffer.references = 1; + return buffer; + }; + NullEngine.prototype.createIndexBuffer = function (indices) { + var buffer = new _Meshes_dataBuffer__WEBPACK_IMPORTED_MODULE_6__["DataBuffer"](); + buffer.references = 1; + return buffer; + }; + NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) { + if (stencil === void 0) { stencil = false; } + }; + NullEngine.prototype.getRenderWidth = function (useScreen) { + if (useScreen === void 0) { useScreen = false; } + if (!useScreen && this._currentRenderTarget) { + return this._currentRenderTarget.width; + } + return this._options.renderWidth; + }; + NullEngine.prototype.getRenderHeight = function (useScreen) { + if (useScreen === void 0) { useScreen = false; } + if (!useScreen && this._currentRenderTarget) { + return this._currentRenderTarget.height; + } + return this._options.renderHeight; + }; + NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) { + this._cachedViewport = viewport; + }; + NullEngine.prototype.createShaderProgram = function (pipelineContext, vertexCode, fragmentCode, defines, context) { + return { + __SPECTOR_rebuildProgram: null, + }; + }; + NullEngine.prototype.getUniforms = function (pipelineContext, uniformsNames) { + return []; + }; + NullEngine.prototype.getAttributes = function (pipelineContext, attributesNames) { + return []; + }; + NullEngine.prototype.bindSamplers = function (effect) { + this._currentEffect = null; + }; + NullEngine.prototype.enableEffect = function (effect) { + this._currentEffect = effect; + if (effect.onBind) { + effect.onBind(effect); + } + if (effect._onBindObservable) { + effect._onBindObservable.notifyObservers(effect); + } + }; + NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) { + if (zOffset === void 0) { zOffset = 0; } + if (reverseSide === void 0) { reverseSide = false; } + }; + NullEngine.prototype.setIntArray = function (uniform, array) { + }; + NullEngine.prototype.setIntArray2 = function (uniform, array) { + }; + NullEngine.prototype.setIntArray3 = function (uniform, array) { + }; + NullEngine.prototype.setIntArray4 = function (uniform, array) { + }; + NullEngine.prototype.setFloatArray = function (uniform, array) { + }; + NullEngine.prototype.setFloatArray2 = function (uniform, array) { + }; + NullEngine.prototype.setFloatArray3 = function (uniform, array) { + }; + NullEngine.prototype.setFloatArray4 = function (uniform, array) { + }; + NullEngine.prototype.setArray = function (uniform, array) { + }; + NullEngine.prototype.setArray2 = function (uniform, array) { + }; + NullEngine.prototype.setArray3 = function (uniform, array) { + }; + NullEngine.prototype.setArray4 = function (uniform, array) { + }; + NullEngine.prototype.setMatrices = function (uniform, matrices) { + }; + NullEngine.prototype.setMatrix = function (uniform, matrix) { + }; + NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) { + }; + NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) { + }; + NullEngine.prototype.setFloat = function (uniform, value) { + }; + NullEngine.prototype.setFloat2 = function (uniform, x, y) { + }; + NullEngine.prototype.setFloat3 = function (uniform, x, y, z) { + }; + NullEngine.prototype.setBool = function (uniform, bool) { + }; + NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) { + }; + NullEngine.prototype.setColor3 = function (uniform, color3) { + }; + NullEngine.prototype.setColor4 = function (uniform, color3, alpha) { + }; + NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) { + if (noDepthWriteChange === void 0) { noDepthWriteChange = false; } + if (this._alphaMode === mode) { + return; + } + this._alphaState.alphaBlend = (mode !== _constants__WEBPACK_IMPORTED_MODULE_5__["Constants"].ALPHA_DISABLE); + if (!noDepthWriteChange) { + this.setDepthWrite(mode === _constants__WEBPACK_IMPORTED_MODULE_5__["Constants"].ALPHA_DISABLE); + } + this._alphaMode = mode; + }; + NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) { + }; + NullEngine.prototype.wipeCaches = function (bruteForce) { + if (this.preventCacheWipeBetweenFrames) { + return; + } + this.resetTextureCache(); + this._currentEffect = null; + if (bruteForce) { + this._currentProgram = null; + this._stencilState.reset(); + this._depthCullingState.reset(); + this._alphaState.reset(); + } + this._cachedVertexBuffers = null; + this._cachedIndexBuffer = null; + this._cachedEffectForVertexBuffers = null; + }; + NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) { + }; + NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) { + }; + NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) { + }; + /** @hidden */ + NullEngine.prototype._createTexture = function () { + return {}; + }; + /** @hidden */ + NullEngine.prototype._releaseTexture = function (texture) { + }; + NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) { + if (samplingMode === void 0) { samplingMode = _constants__WEBPACK_IMPORTED_MODULE_5__["Constants"].TEXTURE_TRILINEAR_SAMPLINGMODE; } + if (onLoad === void 0) { onLoad = null; } + if (onError === void 0) { onError = null; } + if (buffer === void 0) { buffer = null; } + var texture = new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_4__["InternalTexture"](this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_4__["InternalTexture"].DATASOURCE_URL); + var url = String(urlArg); + texture.url = url; + texture.generateMipMaps = !noMipmap; + texture.samplingMode = samplingMode; + texture.invertY = invertY; + texture.baseWidth = this._options.textureSize; + texture.baseHeight = this._options.textureSize; + texture.width = this._options.textureSize; + texture.height = this._options.textureSize; + if (format) { + texture.format = format; + } + texture.isReady = true; + if (onLoad) { + onLoad(); + } + this._internalTexturesCache.push(texture); + return texture; + }; + NullEngine.prototype.createRenderTargetTexture = function (size, options) { + var fullOptions = new _Materials_Textures_renderTargetCreationOptions__WEBPACK_IMPORTED_MODULE_3__["RenderTargetCreationOptions"](); + if (options !== undefined && typeof options === "object") { + fullOptions.generateMipMaps = options.generateMipMaps; + fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer; + fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer; + fullOptions.type = options.type === undefined ? _constants__WEBPACK_IMPORTED_MODULE_5__["Constants"].TEXTURETYPE_UNSIGNED_INT : options.type; + fullOptions.samplingMode = options.samplingMode === undefined ? _constants__WEBPACK_IMPORTED_MODULE_5__["Constants"].TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode; + } + else { + fullOptions.generateMipMaps = options; + fullOptions.generateDepthBuffer = true; + fullOptions.generateStencilBuffer = false; + fullOptions.type = _constants__WEBPACK_IMPORTED_MODULE_5__["Constants"].TEXTURETYPE_UNSIGNED_INT; + fullOptions.samplingMode = _constants__WEBPACK_IMPORTED_MODULE_5__["Constants"].TEXTURE_TRILINEAR_SAMPLINGMODE; + } + var texture = new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_4__["InternalTexture"](this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_4__["InternalTexture"].DATASOURCE_RENDERTARGET); + var width = size.width || size; + var height = size.height || size; + texture._depthStencilBuffer = {}; + texture._framebuffer = {}; + texture.baseWidth = width; + texture.baseHeight = height; + texture.width = width; + texture.height = height; + texture.isReady = true; + texture.samples = 1; + texture.generateMipMaps = fullOptions.generateMipMaps ? true : false; + texture.samplingMode = fullOptions.samplingMode; + texture.type = fullOptions.type; + texture._generateDepthBuffer = fullOptions.generateDepthBuffer; + texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false; + this._internalTexturesCache.push(texture); + return texture; + }; + NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) { + texture.samplingMode = samplingMode; + }; + NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) { + if (this._currentRenderTarget) { + this.unBindFramebuffer(this._currentRenderTarget); + } + this._currentRenderTarget = texture; + this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer; + if (this._cachedViewport && !forceFullscreenViewport) { + this.setViewport(this._cachedViewport, requiredWidth, requiredHeight); + } + }; + NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) { + if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; } + this._currentRenderTarget = null; + if (onBeforeUnbind) { + if (texture._MSAAFramebuffer) { + this._currentFramebuffer = texture._framebuffer; + } + onBeforeUnbind(); + } + this._currentFramebuffer = null; + }; + NullEngine.prototype.createDynamicVertexBuffer = function (vertices) { + var buffer = new _Meshes_dataBuffer__WEBPACK_IMPORTED_MODULE_6__["DataBuffer"](); + buffer.references = 1; + buffer.capacity = 1; + return buffer; + }; + NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) { + if (premulAlpha === void 0) { premulAlpha = false; } + }; + NullEngine.prototype.areAllEffectsReady = function () { + return true; + }; + /** + * @hidden + * Get the current error code of the webGL context + * @returns the error code + * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError + */ + NullEngine.prototype.getError = function () { + return 0; + }; + /** @hidden */ + NullEngine.prototype._getUnpackAlignement = function () { + return 1; + }; + /** @hidden */ + NullEngine.prototype._unpackFlipY = function (value) { + }; + NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) { + if (offset === void 0) { offset = 0; } + }; + /** + * Updates a dynamic vertex buffer. + * @param vertexBuffer the vertex buffer to update + * @param data the data used to update the vertex buffer + * @param byteOffset the byte offset of the data (optional) + * @param byteLength the byte length of the data (optional) + */ + NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) { + }; + NullEngine.prototype._bindTextureDirectly = function (target, texture) { + if (this._boundTexturesCache[this._activeChannel] !== texture) { + this._boundTexturesCache[this._activeChannel] = texture; + return true; + } + return false; + }; + /** @hidden */ + NullEngine.prototype._bindTexture = function (channel, texture) { + if (channel < 0) { + return; + } + this._bindTextureDirectly(0, texture); + }; + NullEngine.prototype._deleteBuffer = function (buffer) { + }; + NullEngine.prototype.releaseEffects = function () { + }; + NullEngine.prototype.displayLoadingUI = function () { + }; + NullEngine.prototype.hideLoadingUI = function () { + }; + /** @hidden */ + NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) { + if (faceIndex === void 0) { faceIndex = 0; } + if (lod === void 0) { lod = 0; } + }; + /** @hidden */ + NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) { + if (faceIndex === void 0) { faceIndex = 0; } + if (lod === void 0) { lod = 0; } + }; + /** @hidden */ + NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) { + if (faceIndex === void 0) { faceIndex = 0; } + if (lod === void 0) { lod = 0; } + }; + /** @hidden */ + NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) { + if (faceIndex === void 0) { faceIndex = 0; } + if (lod === void 0) { lod = 0; } + }; + return NullEngine; +}(_Engines_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"])); + + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../node_modules/webpack/buildin/global.js */ "../node_modules/webpack/buildin/global.js"))) + +/***/ }), + +/***/ "./Events/clipboardEvents.ts": +/*!***********************************!*\ + !*** ./Events/clipboardEvents.ts ***! + \***********************************/ +/*! exports provided: ClipboardEventTypes, ClipboardInfo */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ClipboardEventTypes", function() { return ClipboardEventTypes; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ClipboardInfo", function() { return ClipboardInfo; }); +/** + * Gather the list of clipboard event types as constants. + */ +var ClipboardEventTypes = /** @class */ (function () { + function ClipboardEventTypes() { + } + /** + * The clipboard event is fired when a copy command is active (pressed). + */ + ClipboardEventTypes.COPY = 0x01; // + /** + * The clipboard event is fired when a cut command is active (pressed). + */ + ClipboardEventTypes.CUT = 0x02; + /** + * The clipboard event is fired when a paste command is active (pressed). + */ + ClipboardEventTypes.PASTE = 0x03; + return ClipboardEventTypes; +}()); + +/** + * This class is used to store clipboard related info for the onClipboardObservable event. + */ +var ClipboardInfo = /** @class */ (function () { + /** + *Creates an instance of ClipboardInfo. + * @param type Defines the type of event (BABYLON.ClipboardEventTypes) + * @param event Defines the related dom event + */ + function ClipboardInfo( + /** + * Defines the type of event (BABYLON.ClipboardEventTypes) + */ + type, + /** + * Defines the related dom event + */ + event) { + this.type = type; + this.event = event; + } + /** + * Get the clipboard event's type from the keycode. + * @param keyCode Defines the keyCode for the current keyboard event. + * @return {number} + */ + ClipboardInfo.GetTypeFromCharacter = function (keyCode) { + var charCode = keyCode; + //TODO: add codes for extended ASCII + switch (charCode) { + case 67: return ClipboardEventTypes.COPY; + case 86: return ClipboardEventTypes.PASTE; + case 88: return ClipboardEventTypes.CUT; + default: return -1; + } + }; + return ClipboardInfo; +}()); + + + +/***/ }), + +/***/ "./Events/index.ts": +/*!*************************!*\ + !*** ./Events/index.ts ***! + \*************************/ +/*! exports provided: KeyboardEventTypes, KeyboardInfo, KeyboardInfoPre, PointerEventTypes, PointerInfoBase, PointerInfoPre, PointerInfo, ClipboardEventTypes, ClipboardInfo */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _keyboardEvents__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./keyboardEvents */ "./Events/keyboardEvents.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KeyboardEventTypes", function() { return _keyboardEvents__WEBPACK_IMPORTED_MODULE_0__["KeyboardEventTypes"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KeyboardInfo", function() { return _keyboardEvents__WEBPACK_IMPORTED_MODULE_0__["KeyboardInfo"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KeyboardInfoPre", function() { return _keyboardEvents__WEBPACK_IMPORTED_MODULE_0__["KeyboardInfoPre"]; }); + +/* harmony import */ var _pointerEvents__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./pointerEvents */ "./Events/pointerEvents.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointerEventTypes", function() { return _pointerEvents__WEBPACK_IMPORTED_MODULE_1__["PointerEventTypes"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointerInfoBase", function() { return _pointerEvents__WEBPACK_IMPORTED_MODULE_1__["PointerInfoBase"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointerInfoPre", function() { return _pointerEvents__WEBPACK_IMPORTED_MODULE_1__["PointerInfoPre"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointerInfo", function() { return _pointerEvents__WEBPACK_IMPORTED_MODULE_1__["PointerInfo"]; }); + +/* harmony import */ var _clipboardEvents__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./clipboardEvents */ "./Events/clipboardEvents.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ClipboardEventTypes", function() { return _clipboardEvents__WEBPACK_IMPORTED_MODULE_2__["ClipboardEventTypes"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ClipboardInfo", function() { return _clipboardEvents__WEBPACK_IMPORTED_MODULE_2__["ClipboardInfo"]; }); + + + + + + +/***/ }), + +/***/ "./Events/keyboardEvents.ts": +/*!**********************************!*\ + !*** ./Events/keyboardEvents.ts ***! + \**********************************/ +/*! exports provided: KeyboardEventTypes, KeyboardInfo, KeyboardInfoPre */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KeyboardEventTypes", function() { return KeyboardEventTypes; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KeyboardInfo", function() { return KeyboardInfo; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KeyboardInfoPre", function() { return KeyboardInfoPre; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); + +/** + * Gather the list of keyboard event types as constants. + */ +var KeyboardEventTypes = /** @class */ (function () { + function KeyboardEventTypes() { + } + /** + * The keydown event is fired when a key becomes active (pressed). + */ + KeyboardEventTypes.KEYDOWN = 0x01; + /** + * The keyup event is fired when a key has been released. + */ + KeyboardEventTypes.KEYUP = 0x02; + return KeyboardEventTypes; +}()); + +/** + * This class is used to store keyboard related info for the onKeyboardObservable event. + */ +var KeyboardInfo = /** @class */ (function () { + /** + * Instantiates a new keyboard info. + * This class is used to store keyboard related info for the onKeyboardObservable event. + * @param type Defines the type of event (KeyboardEventTypes) + * @param event Defines the related dom event + */ + function KeyboardInfo( + /** + * Defines the type of event (KeyboardEventTypes) + */ + type, + /** + * Defines the related dom event + */ + event) { + this.type = type; + this.event = event; + } + return KeyboardInfo; +}()); + +/** + * This class is used to store keyboard related info for the onPreKeyboardObservable event. + * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable + */ +var KeyboardInfoPre = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](KeyboardInfoPre, _super); + /** + * Instantiates a new keyboard pre info. + * This class is used to store keyboard related info for the onPreKeyboardObservable event. + * @param type Defines the type of event (KeyboardEventTypes) + * @param event Defines the related dom event + */ + function KeyboardInfoPre( + /** + * Defines the type of event (KeyboardEventTypes) + */ + type, + /** + * Defines the related dom event + */ + event) { + var _this = _super.call(this, type, event) || this; + _this.type = type; + _this.event = event; + _this.skipOnPointerObservable = false; + return _this; + } + return KeyboardInfoPre; +}(KeyboardInfo)); + + + +/***/ }), + +/***/ "./Events/pointerEvents.ts": +/*!*********************************!*\ + !*** ./Events/pointerEvents.ts ***! + \*********************************/ +/*! exports provided: PointerEventTypes, PointerInfoBase, PointerInfoPre, PointerInfo */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PointerEventTypes", function() { return PointerEventTypes; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PointerInfoBase", function() { return PointerInfoBase; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PointerInfoPre", function() { return PointerInfoPre; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PointerInfo", function() { return PointerInfo; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); + + +/** + * Gather the list of pointer event types as constants. + */ +var PointerEventTypes = /** @class */ (function () { + function PointerEventTypes() { + } + /** + * The pointerdown event is fired when a pointer becomes active. For mouse, it is fired when the device transitions from no buttons depressed to at least one button depressed. For touch, it is fired when physical contact is made with the digitizer. For pen, it is fired when the stylus makes physical contact with the digitizer. + */ + PointerEventTypes.POINTERDOWN = 0x01; + /** + * The pointerup event is fired when a pointer is no longer active. + */ + PointerEventTypes.POINTERUP = 0x02; + /** + * The pointermove event is fired when a pointer changes coordinates. + */ + PointerEventTypes.POINTERMOVE = 0x04; + /** + * The pointerwheel event is fired when a mouse wheel has been rotated. + */ + PointerEventTypes.POINTERWHEEL = 0x08; + /** + * The pointerpick event is fired when a mesh or sprite has been picked by the pointer. + */ + PointerEventTypes.POINTERPICK = 0x10; + /** + * The pointertap event is fired when a the object has been touched and released without drag. + */ + PointerEventTypes.POINTERTAP = 0x20; + /** + * The pointerdoubletap event is fired when a the object has been touched and released twice without drag. + */ + PointerEventTypes.POINTERDOUBLETAP = 0x40; + return PointerEventTypes; +}()); + +/** + * Base class of pointer info types. + */ +var PointerInfoBase = /** @class */ (function () { + /** + * Instantiates the base class of pointers info. + * @param type Defines the type of event (PointerEventTypes) + * @param event Defines the related dom event + */ + function PointerInfoBase( + /** + * Defines the type of event (PointerEventTypes) + */ + type, + /** + * Defines the related dom event + */ + event) { + this.type = type; + this.event = event; + } + return PointerInfoBase; +}()); + +/** + * This class is used to store pointer related info for the onPrePointerObservable event. + * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable + */ +var PointerInfoPre = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PointerInfoPre, _super); + /** + * Instantiates a PointerInfoPre to store pointer related info to the onPrePointerObservable event. + * @param type Defines the type of event (PointerEventTypes) + * @param event Defines the related dom event + * @param localX Defines the local x coordinates of the pointer when the event occured + * @param localY Defines the local y coordinates of the pointer when the event occured + */ + function PointerInfoPre(type, event, localX, localY) { + var _this = _super.call(this, type, event) || this; + /** + * Ray from a pointer if availible (eg. 6dof controller) + */ + _this.ray = null; + _this.skipOnPointerObservable = false; + _this.localPosition = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector2"](localX, localY); + return _this; + } + return PointerInfoPre; +}(PointerInfoBase)); + +/** + * This type contains all the data related to a pointer event in Babylon.js. + * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class. + */ +var PointerInfo = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PointerInfo, _super); + /** + * Instantiates a PointerInfo to store pointer related info to the onPointerObservable event. + * @param type Defines the type of event (PointerEventTypes) + * @param event Defines the related dom event + * @param pickInfo Defines the picking info associated to the info (if any)\ + */ + function PointerInfo(type, event, + /** + * Defines the picking info associated to the info (if any)\ + */ + pickInfo) { + var _this = _super.call(this, type, event) || this; + _this.pickInfo = pickInfo; + return _this; + } + return PointerInfo; +}(PointerInfoBase)); + + + +/***/ }), + +/***/ "./Gamepads/Controllers/daydreamController.ts": +/*!****************************************************!*\ + !*** ./Gamepads/Controllers/daydreamController.ts ***! + \****************************************************/ +/*! exports provided: DaydreamController */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DaydreamController", function() { return DaydreamController; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/logger */ "./Misc/logger.ts"); +/* harmony import */ var _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Loading/sceneLoader */ "./Loading/sceneLoader.ts"); +/* harmony import */ var _webVRController__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./webVRController */ "./Gamepads/Controllers/webVRController.ts"); +/* harmony import */ var _poseEnabledController__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./poseEnabledController */ "./Gamepads/Controllers/poseEnabledController.ts"); + + + + + +/** + * Google Daydream controller + */ +var DaydreamController = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](DaydreamController, _super); + /** + * Creates a new DaydreamController from a gamepad + * @param vrGamepad the gamepad that the controller should be created from + */ + function DaydreamController(vrGamepad) { + var _this = _super.call(this, vrGamepad) || this; + _this.controllerType = _poseEnabledController__WEBPACK_IMPORTED_MODULE_4__["PoseEnabledControllerType"].DAYDREAM; + return _this; + } + /** + * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful. + * @param scene scene in which to add meshes + * @param meshLoaded optional callback function that will be called if the mesh loads successfully. + */ + DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) { + var _this = this; + _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_2__["SceneLoader"].ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) { + _this._defaultModel = newMeshes[1]; + _this.attachToMesh(_this._defaultModel); + if (meshLoaded) { + meshLoaded(_this._defaultModel); + } + }); + }; + /** + * Called once for each button that changed state since the last frame + * @param buttonIdx Which button index changed + * @param state New state of the button + * @param changes Which properties on the state changed since last frame + */ + DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) { + // Daydream controller only has 1 GamepadButton (on the trackpad). + if (buttonIdx === 0) { + var observable = this.onTriggerStateChangedObservable; + if (observable) { + observable.notifyObservers(state); + } + } + else { + // If the app or home buttons are ever made available + _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn("Unrecognized Daydream button index: " + buttonIdx); + } + }; + /** + * Base Url for the controller model. + */ + DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/'; + /** + * File name for the controller model. + */ + DaydreamController.MODEL_FILENAME = 'generic.babylon'; + /** + * Gamepad Id prefix used to identify Daydream Controller. + */ + DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller' + return DaydreamController; +}(_webVRController__WEBPACK_IMPORTED_MODULE_3__["WebVRController"])); + +_poseEnabledController__WEBPACK_IMPORTED_MODULE_4__["PoseEnabledControllerHelper"]._ControllerFactories.push({ + canCreate: function (gamepadInfo) { + return gamepadInfo.id.indexOf(DaydreamController.GAMEPAD_ID_PREFIX) === 0; + }, + create: function (gamepadInfo) { + return new DaydreamController(gamepadInfo); + } +}); + + +/***/ }), + +/***/ "./Gamepads/Controllers/gearVRController.ts": +/*!**************************************************!*\ + !*** ./Gamepads/Controllers/gearVRController.ts ***! + \**************************************************/ +/*! exports provided: GearVRController */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GearVRController", function() { return GearVRController; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Meshes_mesh__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Meshes/mesh */ "./Meshes/mesh.ts"); +/* harmony import */ var _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Loading/sceneLoader */ "./Loading/sceneLoader.ts"); +/* harmony import */ var _webVRController__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./webVRController */ "./Gamepads/Controllers/webVRController.ts"); +/* harmony import */ var _poseEnabledController__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./poseEnabledController */ "./Gamepads/Controllers/poseEnabledController.ts"); + + + + + + +/** + * Gear VR Controller + */ +var GearVRController = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](GearVRController, _super); + /** + * Creates a new GearVRController from a gamepad + * @param vrGamepad the gamepad that the controller should be created from + */ + function GearVRController(vrGamepad) { + var _this = _super.call(this, vrGamepad) || this; + _this._buttonIndexToObservableNameMap = [ + 'onPadStateChangedObservable', + 'onTriggerStateChangedObservable' // Trigger + ]; + _this.controllerType = _poseEnabledController__WEBPACK_IMPORTED_MODULE_5__["PoseEnabledControllerType"].GEAR_VR; + // Initial starting position defaults to where hand would be (incase of only 3dof controller) + _this._calculatedPosition = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"](_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25); + _this._disableTrackPosition(_this._calculatedPosition); + return _this; + } + /** + * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful. + * @param scene scene in which to add meshes + * @param meshLoaded optional callback function that will be called if the mesh loads successfully. + */ + GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) { + var _this = this; + _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_3__["SceneLoader"].ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) { + // Offset the controller so it will rotate around the users wrist + var mesh = new _Meshes_mesh__WEBPACK_IMPORTED_MODULE_2__["Mesh"]("", scene); + newMeshes[1].parent = mesh; + newMeshes[1].position.z = -0.15; + _this._defaultModel = mesh; + _this.attachToMesh(_this._defaultModel); + if (meshLoaded) { + meshLoaded(_this._defaultModel); + } + }); + }; + /** + * Called once for each button that changed state since the last frame + * @param buttonIdx Which button index changed + * @param state New state of the button + * @param changes Which properties on the state changed since last frame + */ + GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) { + if (buttonIdx < this._buttonIndexToObservableNameMap.length) { + var observableName = this._buttonIndexToObservableNameMap[buttonIdx]; + // Only emit events for buttons that we know how to map from index to observable + var observable = this[observableName]; + if (observable) { + observable.notifyObservers(state); + } + } + }; + /** + * Base Url for the controller model. + */ + GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/'; + /** + * File name for the controller model. + */ + GearVRController.MODEL_FILENAME = 'generic.babylon'; + /** + * Gamepad Id prefix used to identify this controller. + */ + GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller' + return GearVRController; +}(_webVRController__WEBPACK_IMPORTED_MODULE_4__["WebVRController"])); + +_poseEnabledController__WEBPACK_IMPORTED_MODULE_5__["PoseEnabledControllerHelper"]._ControllerFactories.push({ + canCreate: function (gamepadInfo) { + return gamepadInfo.id.indexOf(GearVRController.GAMEPAD_ID_PREFIX) === 0 || + gamepadInfo.id.indexOf('Oculus Go') !== -1 || + gamepadInfo.id.indexOf('Vive Focus') !== -1; + }, + create: function (gamepadInfo) { + return new GearVRController(gamepadInfo); + } +}); + + +/***/ }), + +/***/ "./Gamepads/Controllers/genericController.ts": +/*!***************************************************!*\ + !*** ./Gamepads/Controllers/genericController.ts ***! + \***************************************************/ +/*! exports provided: GenericController */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GenericController", function() { return GenericController; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Loading/sceneLoader */ "./Loading/sceneLoader.ts"); +/* harmony import */ var _webVRController__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./webVRController */ "./Gamepads/Controllers/webVRController.ts"); +/* harmony import */ var _poseEnabledController__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./poseEnabledController */ "./Gamepads/Controllers/poseEnabledController.ts"); + + + + +/** + * Generic Controller + */ +var GenericController = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](GenericController, _super); + /** + * Creates a new GenericController from a gamepad + * @param vrGamepad the gamepad that the controller should be created from + */ + function GenericController(vrGamepad) { + return _super.call(this, vrGamepad) || this; + } + /** + * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful. + * @param scene scene in which to add meshes + * @param meshLoaded optional callback function that will be called if the mesh loads successfully. + */ + GenericController.prototype.initControllerMesh = function (scene, meshLoaded) { + var _this = this; + _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_1__["SceneLoader"].ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) { + _this._defaultModel = newMeshes[1]; + _this.attachToMesh(_this._defaultModel); + if (meshLoaded) { + meshLoaded(_this._defaultModel); + } + }); + }; + /** + * Called once for each button that changed state since the last frame + * @param buttonIdx Which button index changed + * @param state New state of the button + * @param changes Which properties on the state changed since last frame + */ + GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) { + console.log("Button id: " + buttonIdx + "state: "); + console.dir(state); + }; + /** + * Base Url for the controller model. + */ + GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/'; + /** + * File name for the controller model. + */ + GenericController.MODEL_FILENAME = 'generic.babylon'; + return GenericController; +}(_webVRController__WEBPACK_IMPORTED_MODULE_2__["WebVRController"])); + +_poseEnabledController__WEBPACK_IMPORTED_MODULE_3__["PoseEnabledControllerHelper"]._DefaultControllerFactory = function (gamepadInfo) { return new GenericController(gamepadInfo); }; + + +/***/ }), + +/***/ "./Gamepads/Controllers/index.ts": +/*!***************************************!*\ + !*** ./Gamepads/Controllers/index.ts ***! + \***************************************/ +/*! exports provided: DaydreamController, GearVRController, GenericController, OculusTouchController, PoseEnabledControllerType, PoseEnabledControllerHelper, PoseEnabledController, ViveController, WebVRController, WindowsMotionController */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _daydreamController__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./daydreamController */ "./Gamepads/Controllers/daydreamController.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DaydreamController", function() { return _daydreamController__WEBPACK_IMPORTED_MODULE_0__["DaydreamController"]; }); + +/* harmony import */ var _gearVRController__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./gearVRController */ "./Gamepads/Controllers/gearVRController.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GearVRController", function() { return _gearVRController__WEBPACK_IMPORTED_MODULE_1__["GearVRController"]; }); + +/* harmony import */ var _genericController__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./genericController */ "./Gamepads/Controllers/genericController.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GenericController", function() { return _genericController__WEBPACK_IMPORTED_MODULE_2__["GenericController"]; }); + +/* harmony import */ var _oculusTouchController__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./oculusTouchController */ "./Gamepads/Controllers/oculusTouchController.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OculusTouchController", function() { return _oculusTouchController__WEBPACK_IMPORTED_MODULE_3__["OculusTouchController"]; }); + +/* harmony import */ var _poseEnabledController__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./poseEnabledController */ "./Gamepads/Controllers/poseEnabledController.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PoseEnabledControllerType", function() { return _poseEnabledController__WEBPACK_IMPORTED_MODULE_4__["PoseEnabledControllerType"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PoseEnabledControllerHelper", function() { return _poseEnabledController__WEBPACK_IMPORTED_MODULE_4__["PoseEnabledControllerHelper"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PoseEnabledController", function() { return _poseEnabledController__WEBPACK_IMPORTED_MODULE_4__["PoseEnabledController"]; }); + +/* harmony import */ var _viveController__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./viveController */ "./Gamepads/Controllers/viveController.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ViveController", function() { return _viveController__WEBPACK_IMPORTED_MODULE_5__["ViveController"]; }); + +/* harmony import */ var _webVRController__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./webVRController */ "./Gamepads/Controllers/webVRController.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebVRController", function() { return _webVRController__WEBPACK_IMPORTED_MODULE_6__["WebVRController"]; }); + +/* harmony import */ var _windowsMotionController__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./windowsMotionController */ "./Gamepads/Controllers/windowsMotionController.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WindowsMotionController", function() { return _windowsMotionController__WEBPACK_IMPORTED_MODULE_7__["WindowsMotionController"]; }); + + + + + + + + + + + +/***/ }), + +/***/ "./Gamepads/Controllers/oculusTouchController.ts": +/*!*******************************************************!*\ + !*** ./Gamepads/Controllers/oculusTouchController.ts ***! + \*******************************************************/ +/*! exports provided: OculusTouchController */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OculusTouchController", function() { return OculusTouchController; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Loading/sceneLoader */ "./Loading/sceneLoader.ts"); +/* harmony import */ var _webVRController__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./webVRController */ "./Gamepads/Controllers/webVRController.ts"); +/* harmony import */ var _poseEnabledController__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./poseEnabledController */ "./Gamepads/Controllers/poseEnabledController.ts"); + + + + + +/** + * Oculus Touch Controller + */ +var OculusTouchController = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](OculusTouchController, _super); + /** + * Creates a new OculusTouchController from a gamepad + * @param vrGamepad the gamepad that the controller should be created from + */ + function OculusTouchController(vrGamepad) { + var _this = _super.call(this, vrGamepad) || this; + /** + * Fired when the secondary trigger on this controller is modified + */ + _this.onSecondaryTriggerStateChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + /** + * Fired when the thumb rest on this controller is modified + */ + _this.onThumbRestChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + _this.controllerType = _poseEnabledController__WEBPACK_IMPORTED_MODULE_4__["PoseEnabledControllerType"].OCULUS; + return _this; + } + /** + * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful. + * @param scene scene in which to add meshes + * @param meshLoaded optional callback function that will be called if the mesh loads successfully. + */ + OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) { + var _this = this; + var meshName; + // Hand + if (this.hand === 'left') { + meshName = OculusTouchController.MODEL_LEFT_FILENAME; + } + else { // Right is the default if no hand is specified + meshName = OculusTouchController.MODEL_RIGHT_FILENAME; + } + _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_2__["SceneLoader"].ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) { + /* + Parent Mesh name: oculus_touch_left + - body + - trigger + - thumbstick + - grip + - button_y + - button_x + - button_enter + */ + _this._defaultModel = newMeshes[1]; + _this.attachToMesh(_this._defaultModel); + if (meshLoaded) { + meshLoaded(_this._defaultModel); + } + }); + }; + Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", { + /** + * Fired when the A button on this controller is modified + */ + get: function () { + if (this.hand === 'right') { + return this.onMainButtonStateChangedObservable; + } + else { + throw new Error('No A button on left hand'); + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", { + /** + * Fired when the B button on this controller is modified + */ + get: function () { + if (this.hand === 'right') { + return this.onSecondaryButtonStateChangedObservable; + } + else { + throw new Error('No B button on left hand'); + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", { + /** + * Fired when the X button on this controller is modified + */ + get: function () { + if (this.hand === 'left') { + return this.onMainButtonStateChangedObservable; + } + else { + throw new Error('No X button on right hand'); + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", { + /** + * Fired when the Y button on this controller is modified + */ + get: function () { + if (this.hand === 'left') { + return this.onSecondaryButtonStateChangedObservable; + } + else { + throw new Error('No Y button on right hand'); + } + }, + enumerable: true, + configurable: true + }); + /** + * Called once for each button that changed state since the last frame + * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick + * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1) + * 2) secondary trigger (same) + * 3) A (right) X (left), touch, pressed = value + * 4) B / Y + * 5) thumb rest + * @param buttonIdx Which button index changed + * @param state New state of the button + * @param changes Which properties on the state changed since last frame + */ + OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) { + var notifyObject = state; //{ state: state, changes: changes }; + var triggerDirection = this.hand === 'right' ? -1 : 1; + switch (buttonIdx) { + case 0: + this.onPadStateChangedObservable.notifyObservers(notifyObject); + return; + case 1: // index trigger + if (this._defaultModel) { + (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20; + (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005; + (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005; + } + this.onTriggerStateChangedObservable.notifyObservers(notifyObject); + return; + case 2: // secondary trigger + if (this._defaultModel) { + (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035; + } + this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject); + return; + case 3: + if (this._defaultModel) { + if (notifyObject.pressed) { + (this._defaultModel.getChildren()[1]).position.y = -0.001; + } + else { + (this._defaultModel.getChildren()[1]).position.y = 0; + } + } + this.onMainButtonStateChangedObservable.notifyObservers(notifyObject); + return; + case 4: + if (this._defaultModel) { + if (notifyObject.pressed) { + (this._defaultModel.getChildren()[2]).position.y = -0.001; + } + else { + (this._defaultModel.getChildren()[2]).position.y = 0; + } + } + this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject); + return; + case 5: + this.onThumbRestChangedObservable.notifyObservers(notifyObject); + return; + } + }; + /** + * Base Url for the controller model. + */ + OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/'; + /** + * File name for the left controller model. + */ + OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon'; + /** + * File name for the right controller model. + */ + OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon'; + return OculusTouchController; +}(_webVRController__WEBPACK_IMPORTED_MODULE_3__["WebVRController"])); + +_poseEnabledController__WEBPACK_IMPORTED_MODULE_4__["PoseEnabledControllerHelper"]._ControllerFactories.push({ + canCreate: function (gamepadInfo) { + return gamepadInfo.id.indexOf('Oculus Touch') !== -1; + }, + create: function (gamepadInfo) { + return new OculusTouchController(gamepadInfo); + } +}); + + +/***/ }), + +/***/ "./Gamepads/Controllers/poseEnabledController.ts": +/*!*******************************************************!*\ + !*** ./Gamepads/Controllers/poseEnabledController.ts ***! + \*******************************************************/ +/*! exports provided: PoseEnabledControllerType, PoseEnabledControllerHelper, PoseEnabledController */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PoseEnabledControllerType", function() { return PoseEnabledControllerType; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PoseEnabledControllerHelper", function() { return PoseEnabledControllerHelper; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PoseEnabledController", function() { return PoseEnabledController; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Culling_ray__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Culling/ray */ "./Culling/ray.ts"); +/* harmony import */ var _Engines_engineStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Engines/engineStore */ "./Engines/engineStore.ts"); +/* harmony import */ var _Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Gamepads/gamepad */ "./Gamepads/gamepad.ts"); + + + + + + +/** +* Defines the types of pose enabled controllers that are supported +*/ +var PoseEnabledControllerType; +(function (PoseEnabledControllerType) { + /** + * HTC Vive + */ + PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE"; + /** + * Oculus Rift + */ + PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS"; + /** + * Windows mixed reality + */ + PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS"; + /** + * Samsung gear VR + */ + PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR"; + /** + * Google Daydream + */ + PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM"; + /** + * Generic + */ + PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC"; +})(PoseEnabledControllerType || (PoseEnabledControllerType = {})); +/** + * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller) + */ +var PoseEnabledControllerHelper = /** @class */ (function () { + function PoseEnabledControllerHelper() { + } + /** + * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller) + * @param vrGamepad the gamepad to initialized + * @returns a vr controller of the type the gamepad identified as + */ + PoseEnabledControllerHelper.InitiateController = function (vrGamepad) { + for (var _i = 0, _a = this._ControllerFactories; _i < _a.length; _i++) { + var factory = _a[_i]; + if (factory.canCreate(vrGamepad)) { + return factory.create(vrGamepad); + } + } + if (this._DefaultControllerFactory) { + return this._DefaultControllerFactory(vrGamepad); + } + throw "The type of gamepad you are trying to load needs to be imported first or is not supported."; + }; + /** @hidden */ + PoseEnabledControllerHelper._ControllerFactories = []; + /** @hidden */ + PoseEnabledControllerHelper._DefaultControllerFactory = null; + return PoseEnabledControllerHelper; +}()); + +/** + * Defines the PoseEnabledController object that contains state of a vr capable controller + */ +var PoseEnabledController = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PoseEnabledController, _super); + /** + * Creates a new PoseEnabledController from a gamepad + * @param browserGamepad the gamepad that the PoseEnabledController should be created from + */ + function PoseEnabledController(browserGamepad) { + var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this; + // Represents device position and rotation in room space. Should only be used to help calculate babylon space values + _this._deviceRoomPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); + _this._deviceRoomRotationQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Quaternion"](); + /** + * The device position in babylon space + */ + _this.devicePosition = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); + /** + * The device rotation in babylon space + */ + _this.deviceRotationQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Quaternion"](); + /** + * The scale factor of the device in babylon space + */ + _this.deviceScaleFactor = 1; + // Used to convert 6dof controllers to 3dof + _this._trackPosition = true; + _this._maxRotationDistFromHeadset = Math.PI / 5; + _this._draggedRoomRotation = 0; + _this._leftHandSystemQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Quaternion"](); + /** + * Internal, matrix used to convert room space to babylon space + * @hidden + */ + _this._deviceToWorld = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"].Identity(); + /** + * Node to be used when casting a ray from the controller + * @hidden + */ + _this._pointingPoseNode = null; + _this._workingMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"].Identity(); + /** + * @hidden + */ + _this._meshAttachedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + _this.type = _Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_5__["Gamepad"].POSE_ENABLED; + _this.controllerType = PoseEnabledControllerType.GENERIC; + _this.position = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); + _this.rotationQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Quaternion"](); + _this._calculatedPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); + _this._calculatedRotation = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Quaternion"](); + _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Quaternion"].RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion); + return _this; + } + /** + * @hidden + */ + PoseEnabledController.prototype._disableTrackPosition = function (fixedPosition) { + if (this._trackPosition) { + this._calculatedPosition.copyFrom(fixedPosition); + this._trackPosition = false; + } + }; + /** + * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller + */ + PoseEnabledController.prototype.update = function () { + _super.prototype.update.call(this); + this._updatePoseAndMesh(); + }; + /** + * Updates only the pose device and mesh without doing any button event checking + */ + PoseEnabledController.prototype._updatePoseAndMesh = function () { + var pose = this.browserGamepad.pose; + this.updateFromDevice(pose); + if (!this._trackPosition && _Engines_engineStore__WEBPACK_IMPORTED_MODULE_4__["EngineStore"].LastCreatedScene && _Engines_engineStore__WEBPACK_IMPORTED_MODULE_4__["EngineStore"].LastCreatedScene.activeCamera && _Engines_engineStore__WEBPACK_IMPORTED_MODULE_4__["EngineStore"].LastCreatedScene.activeCamera.devicePosition) { + var camera = _Engines_engineStore__WEBPACK_IMPORTED_MODULE_4__["EngineStore"].LastCreatedScene.activeCamera; + camera._computeDevicePosition(); + this._deviceToWorld.setTranslation(camera.devicePosition); + if (camera.deviceRotationQuaternion) { + var camera = camera; + camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(_Maths_math__WEBPACK_IMPORTED_MODULE_2__["Tmp"].Vector3[0]); + // Find the radian distance away that the headset is from the controllers rotation + var distanceAway = Math.atan2(Math.sin(_Maths_math__WEBPACK_IMPORTED_MODULE_2__["Tmp"].Vector3[0].y - this._draggedRoomRotation), Math.cos(_Maths_math__WEBPACK_IMPORTED_MODULE_2__["Tmp"].Vector3[0].y - this._draggedRoomRotation)); + if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) { + // Only rotate enouph to be within the _maxRotationDistFromHeadset + var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset); + this._draggedRoomRotation += rotationAmount; + // Rotate controller around headset + var sin = Math.sin(-rotationAmount); + var cos = Math.cos(-rotationAmount); + this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin; + this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos; + } + } + } + _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition); + this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix); + _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Quaternion"].FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion); + this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation); + if (this._mesh) { + this._mesh.position.copyFrom(this.devicePosition); + if (this._mesh.rotationQuaternion) { + this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion); + } + } + }; + /** + * Updates the state of the pose enbaled controller based on the raw pose data from the device + * @param poseData raw pose fromthe device + */ + PoseEnabledController.prototype.updateFromDevice = function (poseData) { + if (poseData) { + this.rawPose = poseData; + if (poseData.position) { + this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]); + if (this._mesh && this._mesh.getScene().useRightHandedSystem) { + this._deviceRoomPosition.z *= -1; + } + if (this._trackPosition) { + this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition); + } + this._calculatedPosition.addInPlace(this.position); + } + var pose = this.rawPose; + if (poseData.orientation && pose.orientation) { + this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]); + if (this._mesh) { + if (this._mesh.getScene().useRightHandedSystem) { + this._deviceRoomRotationQuaternion.z *= -1; + this._deviceRoomRotationQuaternion.w *= -1; + } + else { + this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion); + } + } + // if the camera is set, rotate to the camera's rotation + this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation); + } + } + }; + /** + * Attaches a mesh to the controller + * @param mesh the mesh to be attached + */ + PoseEnabledController.prototype.attachToMesh = function (mesh) { + if (this._mesh) { + this._mesh.parent = null; + } + this._mesh = mesh; + if (this._poseControlledCamera) { + this._mesh.parent = this._poseControlledCamera; + } + if (!this._mesh.rotationQuaternion) { + this._mesh.rotationQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Quaternion"](); + } + // Sync controller mesh and pointing pose node's state with controller, this is done to avoid a frame where position is 0,0,0 when attaching mesh + this._updatePoseAndMesh(); + if (this._pointingPoseNode) { + var parents = []; + var obj = this._pointingPoseNode; + while (obj.parent) { + parents.push(obj.parent); + obj = obj.parent; + } + parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); }); + } + this._meshAttachedObservable.notifyObservers(mesh); + }; + /** + * Attaches the controllers mesh to a camera + * @param camera the camera the mesh should be attached to + */ + PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) { + this._poseControlledCamera = camera; + if (this._mesh) { + this._mesh.parent = this._poseControlledCamera; + } + }; + /** + * Disposes of the controller + */ + PoseEnabledController.prototype.dispose = function () { + if (this._mesh) { + this._mesh.dispose(); + } + this._mesh = null; + _super.prototype.dispose.call(this); + }; + Object.defineProperty(PoseEnabledController.prototype, "mesh", { + /** + * The mesh that is attached to the controller + */ + get: function () { + return this._mesh; + }, + enumerable: true, + configurable: true + }); + /** + * Gets the ray of the controller in the direction the controller is pointing + * @param length the length the resulting ray should be + * @returns a ray in the direction the controller is pointing + */ + PoseEnabledController.prototype.getForwardRay = function (length) { + if (length === void 0) { length = 100; } + if (!this.mesh) { + return new _Culling_ray__WEBPACK_IMPORTED_MODULE_3__["Ray"](_Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(), new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](0, 0, 1), length); + } + var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix(); + var origin = m.getTranslation(); + var forward = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](0, 0, -1); + var forwardWorld = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].TransformNormal(forward, m); + var direction = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Normalize(forwardWorld); + return new _Culling_ray__WEBPACK_IMPORTED_MODULE_3__["Ray"](origin, direction, length); + }; + /** + * Name of the child mesh that can be used to cast a ray from the controller + */ + PoseEnabledController.POINTING_POSE = "POINTING_POSE"; + return PoseEnabledController; +}(_Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_5__["Gamepad"])); + + + +/***/ }), + +/***/ "./Gamepads/Controllers/viveController.ts": +/*!************************************************!*\ + !*** ./Gamepads/Controllers/viveController.ts ***! + \************************************************/ +/*! exports provided: ViveController */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ViveController", function() { return ViveController; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Loading/sceneLoader */ "./Loading/sceneLoader.ts"); +/* harmony import */ var _webVRController__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./webVRController */ "./Gamepads/Controllers/webVRController.ts"); +/* harmony import */ var _poseEnabledController__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./poseEnabledController */ "./Gamepads/Controllers/poseEnabledController.ts"); + + + + +/** + * Vive Controller + */ +var ViveController = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ViveController, _super); + /** + * Creates a new ViveController from a gamepad + * @param vrGamepad the gamepad that the controller should be created from + */ + function ViveController(vrGamepad) { + var _this = _super.call(this, vrGamepad) || this; + _this.controllerType = _poseEnabledController__WEBPACK_IMPORTED_MODULE_3__["PoseEnabledControllerType"].VIVE; + _this._invertLeftStickY = true; + return _this; + } + /** + * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful. + * @param scene scene in which to add meshes + * @param meshLoaded optional callback function that will be called if the mesh loads successfully. + */ + ViveController.prototype.initControllerMesh = function (scene, meshLoaded) { + var _this = this; + _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_1__["SceneLoader"].ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) { + /* + Parent Mesh name: ViveWand + - body + - r_gripper + - l_gripper + - menu_button + - system_button + - trackpad + - trigger + - LED + */ + _this._defaultModel = newMeshes[1]; + _this.attachToMesh(_this._defaultModel); + if (meshLoaded) { + meshLoaded(_this._defaultModel); + } + }); + }; + Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", { + /** + * Fired when the left button on this controller is modified + */ + get: function () { + return this.onMainButtonStateChangedObservable; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", { + /** + * Fired when the right button on this controller is modified + */ + get: function () { + return this.onMainButtonStateChangedObservable; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", { + /** + * Fired when the menu button on this controller is modified + */ + get: function () { + return this.onSecondaryButtonStateChangedObservable; + }, + enumerable: true, + configurable: true + }); + /** + * Called once for each button that changed state since the last frame + * Vive mapping: + * 0: touchpad + * 1: trigger + * 2: left AND right buttons + * 3: menu button + * @param buttonIdx Which button index changed + * @param state New state of the button + * @param changes Which properties on the state changed since last frame + */ + ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) { + var notifyObject = state; //{ state: state, changes: changes }; + switch (buttonIdx) { + case 0: + this.onPadStateChangedObservable.notifyObservers(notifyObject); + return; + case 1: // index trigger + if (this._defaultModel) { + (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15; + } + this.onTriggerStateChangedObservable.notifyObservers(notifyObject); + return; + case 2: // left AND right button + this.onMainButtonStateChangedObservable.notifyObservers(notifyObject); + return; + case 3: + if (this._defaultModel) { + if (notifyObject.pressed) { + (this._defaultModel.getChildren()[2]).position.y = -0.001; + } + else { + (this._defaultModel.getChildren()[2]).position.y = 0; + } + } + this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject); + return; + } + }; + /** + * Base Url for the controller model. + */ + ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/'; + /** + * File name for the controller model. + */ + ViveController.MODEL_FILENAME = 'wand.babylon'; + return ViveController; +}(_webVRController__WEBPACK_IMPORTED_MODULE_2__["WebVRController"])); + +_poseEnabledController__WEBPACK_IMPORTED_MODULE_3__["PoseEnabledControllerHelper"]._ControllerFactories.push({ + canCreate: function (gamepadInfo) { + return gamepadInfo.id.toLowerCase().indexOf('openvr') !== -1; + }, + create: function (gamepadInfo) { + return new ViveController(gamepadInfo); + } +}); + + +/***/ }), + +/***/ "./Gamepads/Controllers/webVRController.ts": +/*!*************************************************!*\ + !*** ./Gamepads/Controllers/webVRController.ts ***! + \*************************************************/ +/*! exports provided: WebVRController */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WebVRController", function() { return WebVRController; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _poseEnabledController__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./poseEnabledController */ "./Gamepads/Controllers/poseEnabledController.ts"); + + + +/** + * Defines the WebVRController object that represents controllers tracked in 3D space + */ +var WebVRController = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](WebVRController, _super); + /** + * Creates a new WebVRController from a gamepad + * @param vrGamepad the gamepad that the WebVRController should be created from + */ + function WebVRController(vrGamepad) { + var _this = _super.call(this, vrGamepad) || this; + // Observables + /** + * Fired when the trigger state has changed + */ + _this.onTriggerStateChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + /** + * Fired when the main button state has changed + */ + _this.onMainButtonStateChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + /** + * Fired when the secondary button state has changed + */ + _this.onSecondaryButtonStateChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + /** + * Fired when the pad state has changed + */ + _this.onPadStateChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + /** + * Fired when controllers stick values have changed + */ + _this.onPadValuesChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + /** + * X and Y axis corrisponding to the controllers joystick + */ + _this.pad = { x: 0, y: 0 }; + // avoid GC, store state in a tmp object + _this._changes = { + pressChanged: false, + touchChanged: false, + valueChanged: false, + changed: false + }; + _this._buttons = new Array(vrGamepad.buttons.length); + _this.hand = vrGamepad.hand; + return _this; + } + /** + * Fired when a controller button's state has changed + * @param callback the callback containing the button that was modified + */ + WebVRController.prototype.onButtonStateChange = function (callback) { + this._onButtonStateChange = callback; + }; + Object.defineProperty(WebVRController.prototype, "defaultModel", { + /** + * The default controller model for the controller + */ + get: function () { + return this._defaultModel; + }, + enumerable: true, + configurable: true + }); + /** + * Updates the state of the controller and mesh based on the current position and rotation of the controller + */ + WebVRController.prototype.update = function () { + _super.prototype.update.call(this); + for (var index = 0; index < this._buttons.length; index++) { + this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index); + } + if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) { + this.pad.x = this.leftStick.x; + this.pad.y = this.leftStick.y; + this.onPadValuesChangedObservable.notifyObservers(this.pad); + } + }; + WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) { + if (!newState) { + newState = { + pressed: false, + touched: false, + value: 0 + }; + } + if (!currentState) { + this._buttons[buttonIndex] = { + pressed: newState.pressed, + touched: newState.touched, + value: newState.value + }; + return; + } + this._checkChanges(newState, currentState); + if (this._changes.changed) { + this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState); + this._handleButtonChange(buttonIndex, newState, this._changes); + } + this._buttons[buttonIndex].pressed = newState.pressed; + this._buttons[buttonIndex].touched = newState.touched; + // oculus triggers are never 0, thou not touched. + this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value; + }; + WebVRController.prototype._checkChanges = function (newState, currentState) { + this._changes.pressChanged = newState.pressed !== currentState.pressed; + this._changes.touchChanged = newState.touched !== currentState.touched; + this._changes.valueChanged = newState.value !== currentState.value; + this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged; + return this._changes; + }; + /** + * Disposes of th webVRCOntroller + */ + WebVRController.prototype.dispose = function () { + _super.prototype.dispose.call(this); + this.onTriggerStateChangedObservable.clear(); + this.onMainButtonStateChangedObservable.clear(); + this.onSecondaryButtonStateChangedObservable.clear(); + this.onPadStateChangedObservable.clear(); + this.onPadValuesChangedObservable.clear(); + }; + return WebVRController; +}(_poseEnabledController__WEBPACK_IMPORTED_MODULE_2__["PoseEnabledController"])); + + + +/***/ }), + +/***/ "./Gamepads/Controllers/windowsMotionController.ts": +/*!*********************************************************!*\ + !*** ./Gamepads/Controllers/windowsMotionController.ts ***! + \*********************************************************/ +/*! exports provided: WindowsMotionController */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WindowsMotionController", function() { return WindowsMotionController; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/logger */ "./Misc/logger.ts"); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Meshes_mesh__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Meshes/mesh */ "./Meshes/mesh.ts"); +/* harmony import */ var _Culling_ray__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Culling/ray */ "./Culling/ray.ts"); +/* harmony import */ var _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../Loading/sceneLoader */ "./Loading/sceneLoader.ts"); +/* harmony import */ var _webVRController__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./webVRController */ "./Gamepads/Controllers/webVRController.ts"); +/* harmony import */ var _genericController__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./genericController */ "./Gamepads/Controllers/genericController.ts"); +/* harmony import */ var _poseEnabledController__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./poseEnabledController */ "./Gamepads/Controllers/poseEnabledController.ts"); + + + + + + + + + + +/** + * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh + */ +var LoadedMeshInfo = /** @class */ (function () { + function LoadedMeshInfo() { + /** + * Map of the button meshes contained in the controller + */ + this.buttonMeshes = {}; + /** + * Map of the axis meshes contained in the controller + */ + this.axisMeshes = {}; + } + return LoadedMeshInfo; +}()); +/** + * Defines the WindowsMotionController object that the state of the windows motion controller + */ +var WindowsMotionController = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](WindowsMotionController, _super); + /** + * Creates a new WindowsMotionController from a gamepad + * @param vrGamepad the gamepad that the controller should be created from + */ + function WindowsMotionController(vrGamepad) { + var _this = _super.call(this, vrGamepad) || this; + _this._mapping = { + // Semantic button names + buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'], + // A mapping of the button name to glTF model node name + // that should be transformed by button value. + buttonMeshNames: { + 'trigger': 'SELECT', + 'menu': 'MENU', + 'grip': 'GRASP', + 'thumbstick': 'THUMBSTICK_PRESS', + 'trackpad': 'TOUCHPAD_PRESS' + }, + // This mapping is used to translate from the Motion Controller to Babylon semantics + buttonObservableNames: { + 'trigger': 'onTriggerStateChangedObservable', + 'menu': 'onSecondaryButtonStateChangedObservable', + 'grip': 'onMainButtonStateChangedObservable', + 'thumbstick': 'onPadStateChangedObservable', + 'trackpad': 'onTrackpadChangedObservable' + }, + // A mapping of the axis name to glTF model node name + // that should be transformed by axis value. + // This array mirrors the browserGamepad.axes array, such that + // the mesh corresponding to axis 0 is in this array index 0. + axisMeshNames: [ + 'THUMBSTICK_X', + 'THUMBSTICK_Y', + 'TOUCHPAD_TOUCH_X', + 'TOUCHPAD_TOUCH_Y' + ], + pointingPoseMeshName: _poseEnabledController__WEBPACK_IMPORTED_MODULE_9__["PoseEnabledController"].POINTING_POSE + }; + /** + * Fired when the trackpad on this controller is clicked + */ + _this.onTrackpadChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); + /** + * Fired when the trackpad on this controller is modified + */ + _this.onTrackpadValuesChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); + /** + * The current x and y values of this controller's trackpad + */ + _this.trackpad = { x: 0, y: 0 }; + _this.controllerType = _poseEnabledController__WEBPACK_IMPORTED_MODULE_9__["PoseEnabledControllerType"].WINDOWS; + _this._loadedMeshInfo = null; + return _this; + } + Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", { + /** + * Fired when the trigger on this controller is modified + */ + get: function () { + return this.onTriggerStateChangedObservable; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", { + /** + * Fired when the menu button on this controller is modified + */ + get: function () { + return this.onSecondaryButtonStateChangedObservable; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", { + /** + * Fired when the grip button on this controller is modified + */ + get: function () { + return this.onMainButtonStateChangedObservable; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", { + /** + * Fired when the thumbstick button on this controller is modified + */ + get: function () { + return this.onPadStateChangedObservable; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", { + /** + * Fired when the touchpad button on this controller is modified + */ + get: function () { + return this.onTrackpadChangedObservable; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", { + /** + * Fired when the touchpad values on this controller are modified + */ + get: function () { + return this.onTrackpadValuesChangedObservable; + }, + enumerable: true, + configurable: true + }); + WindowsMotionController.prototype._updateTrackpad = function () { + if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) { + this.trackpad.x = this.browserGamepad["axes"][2]; + this.trackpad.y = this.browserGamepad["axes"][3]; + this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad); + } + }; + /** + * Called once per frame by the engine. + */ + WindowsMotionController.prototype.update = function () { + _super.prototype.update.call(this); + if (this.browserGamepad.axes) { + this._updateTrackpad(); + // Only need to animate axes if there is a loaded mesh + if (this._loadedMeshInfo) { + for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) { + this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]); + } + } + } + }; + /** + * Called once for each button that changed state since the last frame + * @param buttonIdx Which button index changed + * @param state New state of the button + * @param changes Which properties on the state changed since last frame + */ + WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) { + var buttonName = this._mapping.buttons[buttonIdx]; + if (!buttonName) { + return; + } + // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames + this._updateTrackpad(); + // Only emit events for buttons that we know how to map from index to name + var observable = this[(this._mapping.buttonObservableNames)[buttonName]]; + if (observable) { + observable.notifyObservers(state); + } + this._lerpButtonTransform(buttonName, state.value); + }; + /** + * Moves the buttons on the controller mesh based on their current state + * @param buttonName the name of the button to move + * @param buttonValue the value of the button which determines the buttons new position + */ + WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) { + // If there is no loaded mesh, there is nothing to transform. + if (!this._loadedMeshInfo) { + return; + } + var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName]; + if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) { + return; + } + _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion); + _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position); + }; + /** + * Moves the axis on the controller mesh based on its current state + * @param axis the index of the axis + * @param axisValue the value of the axis which determines the meshes new position + * @hidden + */ + WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) { + if (!this._loadedMeshInfo) { + return; + } + var meshInfo = this._loadedMeshInfo.axisMeshes[axis]; + if (!meshInfo) { + return; + } + if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) { + return; + } + // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1) + var lerpValue = axisValue * 0.5 + 0.5; + _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion); + _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position); + }; + /** + * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful. + * @param scene scene in which to add meshes + * @param meshLoaded optional callback function that will be called if the mesh loads successfully. + */ + WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) { + var _this = this; + if (forceDefault === void 0) { forceDefault = false; } + var path; + var filename; + // Checking if GLB loader is present + if (_Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_6__["SceneLoader"].IsPluginForExtensionAvailable(".glb")) { + // Determine the device specific folder based on the ID suffix + var device = 'default'; + if (this.id && !forceDefault) { + var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN); + device = ((match && match[0]) || device); + } + // Hand + if (this.hand === 'left') { + filename = WindowsMotionController.MODEL_LEFT_FILENAME; + } + else { // Right is the default if no hand is specified + filename = WindowsMotionController.MODEL_RIGHT_FILENAME; + } + path = WindowsMotionController.MODEL_BASE_URL + device + '/'; + } + else { + _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models"); + path = _genericController__WEBPACK_IMPORTED_MODULE_8__["GenericController"].MODEL_BASE_URL; + filename = _genericController__WEBPACK_IMPORTED_MODULE_8__["GenericController"].MODEL_FILENAME; + } + _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_6__["SceneLoader"].ImportMesh("", path, filename, scene, function (meshes) { + // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format. + _this._loadedMeshInfo = _this.processModel(scene, meshes); + if (!_this._loadedMeshInfo) { + return; + } + _this._defaultModel = _this._loadedMeshInfo.rootNode; + _this.attachToMesh(_this._defaultModel); + if (meshLoaded) { + meshLoaded(_this._defaultModel); + } + }, null, function (scene, message) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Log(message); + _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn('Failed to retrieve controller model from the remote server: ' + path + filename); + if (!forceDefault) { + _this.initControllerMesh(scene, meshLoaded, true); + } + }); + }; + /** + * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that + * can be transformed by button presses and axes values, based on this._mapping. + * + * @param scene scene in which the meshes exist + * @param meshes list of meshes that make up the controller model to process + * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed. + */ + WindowsMotionController.prototype.processModel = function (scene, meshes) { + var loadedMeshInfo = null; + // Create a new mesh to contain the glTF hierarchy + var parentMesh = new _Meshes_mesh__WEBPACK_IMPORTED_MODULE_4__["Mesh"](this.id + " " + this.hand, scene); + // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh' + var childMesh = null; + for (var i = 0; i < meshes.length; i++) { + var mesh = meshes[i]; + if (!mesh.parent) { + // Exclude controller meshes from picking results + mesh.isPickable = false; + // Handle root node, attach to the new parentMesh + childMesh = mesh; + break; + } + } + if (childMesh) { + childMesh.setParent(parentMesh); + // Create our mesh info. Note that this method will always return non-null. + loadedMeshInfo = this.createMeshInfo(parentMesh); + } + else { + _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn('Could not find root node in model file.'); + } + return loadedMeshInfo; + }; + WindowsMotionController.prototype.createMeshInfo = function (rootNode) { + var loadedMeshInfo = new LoadedMeshInfo(); + var i; + loadedMeshInfo.rootNode = rootNode; + // Reset the caches + loadedMeshInfo.buttonMeshes = {}; + loadedMeshInfo.axisMeshes = {}; + // Button Meshes + for (i = 0; i < this._mapping.buttons.length; i++) { + var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]]; + if (!buttonMeshName) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]); + continue; + } + var buttonMesh = getChildByName(rootNode, buttonMeshName); + if (!buttonMesh) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn('Missing button mesh with name: ' + buttonMeshName); + continue; + } + var buttonMeshInfo = { + index: i, + value: getImmediateChildByName(buttonMesh, 'VALUE'), + pressed: getImmediateChildByName(buttonMesh, 'PRESSED'), + unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED') + }; + if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) { + loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo; + } + else { + // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes. + _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn('Missing button submesh under mesh with name: ' + buttonMeshName + + '(VALUE: ' + !!buttonMeshInfo.value + + ', PRESSED: ' + !!buttonMeshInfo.pressed + + ', UNPRESSED:' + !!buttonMeshInfo.unpressed + + ')'); + } + } + // Axis Meshes + for (i = 0; i < this._mapping.axisMeshNames.length; i++) { + var axisMeshName = this._mapping.axisMeshNames[i]; + if (!axisMeshName) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Log('Skipping unknown axis at index: ' + i); + continue; + } + var axisMesh = getChildByName(rootNode, axisMeshName); + if (!axisMesh) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn('Missing axis mesh with name: ' + axisMeshName); + continue; + } + var axisMeshInfo = { + index: i, + value: getImmediateChildByName(axisMesh, 'VALUE'), + min: getImmediateChildByName(axisMesh, 'MIN'), + max: getImmediateChildByName(axisMesh, 'MAX') + }; + if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) { + loadedMeshInfo.axisMeshes[i] = axisMeshInfo; + } + else { + // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change. + _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn('Missing axis submesh under mesh with name: ' + axisMeshName + + '(VALUE: ' + !!axisMeshInfo.value + + ', MIN: ' + !!axisMeshInfo.min + + ', MAX:' + !!axisMeshInfo.max + + ')'); + } + } + // Pointing Ray + loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName); + if (!loadedMeshInfo.pointingPoseNode) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName); + } + else { + this._pointingPoseNode = loadedMeshInfo.pointingPoseNode; + } + return loadedMeshInfo; + // Look through all children recursively. This will return null if no mesh exists with the given name. + function getChildByName(node, name) { + return node.getChildren(function (n) { return n.name === name; }, false)[0]; + } + // Look through only immediate children. This will return null if no mesh exists with the given name. + function getImmediateChildByName(node, name) { + return node.getChildren(function (n) { return n.name == name; }, true)[0]; + } + }; + /** + * Gets the ray of the controller in the direction the controller is pointing + * @param length the length the resulting ray should be + * @returns a ray in the direction the controller is pointing + */ + WindowsMotionController.prototype.getForwardRay = function (length) { + if (length === void 0) { length = 100; } + if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) { + return _super.prototype.getForwardRay.call(this, length); + } + var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix(); + var origin = m.getTranslation(); + var forward = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, -1); + var forwardWorld = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformNormal(forward, m); + var direction = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Normalize(forwardWorld); + return new _Culling_ray__WEBPACK_IMPORTED_MODULE_5__["Ray"](origin, direction, length); + }; + /** + * Disposes of the controller + */ + WindowsMotionController.prototype.dispose = function () { + _super.prototype.dispose.call(this); + this.onTrackpadChangedObservable.clear(); + }; + /** + * The base url used to load the left and right controller models + */ + WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/'; + /** + * The name of the left controller model file + */ + WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb'; + /** + * The name of the right controller model file + */ + WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb'; + /** + * The controller name prefix for this controller type + */ + WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) '; + /** + * The controller id pattern for this controller type + */ + WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/; + return WindowsMotionController; +}(_webVRController__WEBPACK_IMPORTED_MODULE_7__["WebVRController"])); + +_poseEnabledController__WEBPACK_IMPORTED_MODULE_9__["PoseEnabledControllerHelper"]._ControllerFactories.push({ + canCreate: function (gamepadInfo) { + return gamepadInfo.id.indexOf(WindowsMotionController.GAMEPAD_ID_PREFIX) === 0; + }, + create: function (gamepadInfo) { + return new WindowsMotionController(gamepadInfo); + } +}); + + +/***/ }), + +/***/ "./Gamepads/gamepad.ts": +/*!*****************************!*\ + !*** ./Gamepads/gamepad.ts ***! + \*****************************/ +/*! exports provided: StickValues, Gamepad, GenericPad */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StickValues", function() { return StickValues; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Gamepad", function() { return Gamepad; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GenericPad", function() { return GenericPad; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); + + +/** + * Represents a gamepad control stick position + */ +var StickValues = /** @class */ (function () { + /** + * Initializes the gamepad x and y control stick values + * @param x The x component of the gamepad control stick value + * @param y The y component of the gamepad control stick value + */ + function StickValues( + /** + * The x component of the control stick + */ + x, + /** + * The y component of the control stick + */ + y) { + this.x = x; + this.y = y; + } + return StickValues; +}()); + +/** + * Represents a gamepad + */ +var Gamepad = /** @class */ (function () { + /** + * Initializes the gamepad + * @param id The id of the gamepad + * @param index The index of the gamepad + * @param browserGamepad The browser gamepad + * @param leftStickX The x component of the left joystick + * @param leftStickY The y component of the left joystick + * @param rightStickX The x component of the right joystick + * @param rightStickY The y component of the right joystick + */ + function Gamepad( + /** + * The id of the gamepad + */ + id, + /** + * The index of the gamepad + */ + index, + /** + * The browser gamepad + */ + browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) { + if (leftStickX === void 0) { leftStickX = 0; } + if (leftStickY === void 0) { leftStickY = 1; } + if (rightStickX === void 0) { rightStickX = 2; } + if (rightStickY === void 0) { rightStickY = 3; } + this.id = id; + this.index = index; + this.browserGamepad = browserGamepad; + this._leftStick = { x: 0, y: 0 }; + this._rightStick = { x: 0, y: 0 }; + /** @hidden */ + this._isConnected = true; + /** + * Specifies whether the left control stick should be Y-inverted + */ + this._invertLeftStickY = false; + this.type = Gamepad.GAMEPAD; + this._leftStickAxisX = leftStickX; + this._leftStickAxisY = leftStickY; + this._rightStickAxisX = rightStickX; + this._rightStickAxisY = rightStickY; + if (this.browserGamepad.axes.length >= 2) { + this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] }; + } + if (this.browserGamepad.axes.length >= 4) { + this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] }; + } + } + Object.defineProperty(Gamepad.prototype, "isConnected", { + /** + * Specifies if the gamepad has been connected + */ + get: function () { + return this._isConnected; + }, + enumerable: true, + configurable: true + }); + /** + * Callback triggered when the left joystick has changed + * @param callback + */ + Gamepad.prototype.onleftstickchanged = function (callback) { + this._onleftstickchanged = callback; + }; + /** + * Callback triggered when the right joystick has changed + * @param callback + */ + Gamepad.prototype.onrightstickchanged = function (callback) { + this._onrightstickchanged = callback; + }; + Object.defineProperty(Gamepad.prototype, "leftStick", { + /** + * Gets the left joystick + */ + get: function () { + return this._leftStick; + }, + /** + * Sets the left joystick values + */ + set: function (newValues) { + if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) { + this._onleftstickchanged(newValues); + } + this._leftStick = newValues; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Gamepad.prototype, "rightStick", { + /** + * Gets the right joystick + */ + get: function () { + return this._rightStick; + }, + /** + * Sets the right joystick value + */ + set: function (newValues) { + if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) { + this._onrightstickchanged(newValues); + } + this._rightStick = newValues; + }, + enumerable: true, + configurable: true + }); + /** + * Updates the gamepad joystick positions + */ + Gamepad.prototype.update = function () { + if (this._leftStick) { + this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] }; + if (this._invertLeftStickY) { + this.leftStick.y *= -1; + } + } + if (this._rightStick) { + this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] }; + } + }; + /** + * Disposes the gamepad + */ + Gamepad.prototype.dispose = function () { + }; + /** + * Represents a gamepad controller + */ + Gamepad.GAMEPAD = 0; + /** + * Represents a generic controller + */ + Gamepad.GENERIC = 1; + /** + * Represents an XBox controller + */ + Gamepad.XBOX = 2; + /** + * Represents a pose-enabled controller + */ + Gamepad.POSE_ENABLED = 3; + return Gamepad; +}()); + +/** + * Represents a generic gamepad + */ +var GenericPad = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](GenericPad, _super); + /** + * Initializes the generic gamepad + * @param id The id of the generic gamepad + * @param index The index of the generic gamepad + * @param browserGamepad The browser gamepad + */ + function GenericPad(id, index, browserGamepad) { + var _this = _super.call(this, id, index, browserGamepad) || this; + /** + * Observable triggered when a button has been pressed + */ + _this.onButtonDownObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + /** + * Observable triggered when a button has been released + */ + _this.onButtonUpObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + _this.type = Gamepad.GENERIC; + _this._buttons = new Array(browserGamepad.buttons.length); + return _this; + } + /** + * Callback triggered when a button has been pressed + * @param callback Called when a button has been pressed + */ + GenericPad.prototype.onbuttondown = function (callback) { + this._onbuttondown = callback; + }; + /** + * Callback triggered when a button has been released + * @param callback Called when a button has been released + */ + GenericPad.prototype.onbuttonup = function (callback) { + this._onbuttonup = callback; + }; + GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) { + if (newValue !== currentValue) { + if (newValue === 1) { + if (this._onbuttondown) { + this._onbuttondown(buttonIndex); + } + this.onButtonDownObservable.notifyObservers(buttonIndex); + } + if (newValue === 0) { + if (this._onbuttonup) { + this._onbuttonup(buttonIndex); + } + this.onButtonUpObservable.notifyObservers(buttonIndex); + } + } + return newValue; + }; + /** + * Updates the generic gamepad + */ + GenericPad.prototype.update = function () { + _super.prototype.update.call(this); + for (var index = 0; index < this._buttons.length; index++) { + this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index); + } + }; + /** + * Disposes the generic gamepad + */ + GenericPad.prototype.dispose = function () { + _super.prototype.dispose.call(this); + this.onButtonDownObservable.clear(); + this.onButtonUpObservable.clear(); + }; + return GenericPad; +}(Gamepad)); + + + +/***/ }), + +/***/ "./Gamepads/gamepadManager.ts": +/*!************************************!*\ + !*** ./Gamepads/gamepadManager.ts ***! + \************************************/ +/*! exports provided: GamepadManager */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GamepadManager", function() { return GamepadManager; }); +/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/tools */ "./Misc/tools.ts"); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _Misc_domManagement__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/domManagement */ "./Misc/domManagement.ts"); +/* harmony import */ var _Gamepads_Controllers_poseEnabledController__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Gamepads/Controllers/poseEnabledController */ "./Gamepads/Controllers/poseEnabledController.ts"); +/* harmony import */ var _xboxGamepad__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./xboxGamepad */ "./Gamepads/xboxGamepad.ts"); +/* harmony import */ var _gamepad__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./gamepad */ "./Gamepads/gamepad.ts"); + + + + + + +/** + * Manager for handling gamepads + */ +var GamepadManager = /** @class */ (function () { + /** + * Initializes the gamepad manager + * @param _scene BabylonJS scene + */ + function GamepadManager(_scene) { + var _this = this; + this._scene = _scene; + this._babylonGamepads = []; + this._oneGamepadConnected = false; + /** @hidden */ + this._isMonitoring = false; + /** + * observable to be triggered when the gamepad controller has been disconnected + */ + this.onGamepadDisconnectedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + if (!_Misc_domManagement__WEBPACK_IMPORTED_MODULE_2__["DomManagement"].IsWindowObjectExist()) { + this._gamepadEventSupported = false; + } + else { + this._gamepadEventSupported = 'GamepadEvent' in window; + this._gamepadSupport = (navigator.getGamepads || + navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads); + } + this.onGamepadConnectedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](function (observer) { + // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected + for (var i in _this._babylonGamepads) { + var gamepad = _this._babylonGamepads[i]; + if (gamepad && gamepad._isConnected) { + _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad); + } + } + }); + this._onGamepadConnectedEvent = function (evt) { + var gamepad = evt.gamepad; + if (gamepad.index in _this._babylonGamepads) { + if (_this._babylonGamepads[gamepad.index].isConnected) { + return; + } + } + var newGamepad; + if (_this._babylonGamepads[gamepad.index]) { + newGamepad = _this._babylonGamepads[gamepad.index]; + newGamepad.browserGamepad = gamepad; + newGamepad._isConnected = true; + } + else { + newGamepad = _this._addNewGamepad(gamepad); + } + _this.onGamepadConnectedObservable.notifyObservers(newGamepad); + _this._startMonitoringGamepads(); + }; + this._onGamepadDisconnectedEvent = function (evt) { + var gamepad = evt.gamepad; + // Remove the gamepad from the list of gamepads to monitor. + for (var i in _this._babylonGamepads) { + if (_this._babylonGamepads[i].index === gamepad.index) { + var disconnectedGamepad = _this._babylonGamepads[i]; + disconnectedGamepad._isConnected = false; + _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad); + break; + } + } + }; + if (this._gamepadSupport) { + //first add already-connected gamepads + this._updateGamepadObjects(); + if (this._babylonGamepads.length) { + this._startMonitoringGamepads(); + } + // Checking if the gamepad connected event is supported (like in Firefox) + if (this._gamepadEventSupported) { + window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false); + window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false); + } + else { + this._startMonitoringGamepads(); + } + } + } + Object.defineProperty(GamepadManager.prototype, "gamepads", { + /** + * The gamepads in the game pad manager + */ + get: function () { + return this._babylonGamepads; + }, + enumerable: true, + configurable: true + }); + /** + * Get the gamepad controllers based on type + * @param type The type of gamepad controller + * @returns Nullable gamepad + */ + GamepadManager.prototype.getGamepadByType = function (type) { + if (type === void 0) { type = _gamepad__WEBPACK_IMPORTED_MODULE_5__["Gamepad"].XBOX; } + for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) { + var gamepad = _a[_i]; + if (gamepad && gamepad.type === type) { + return gamepad; + } + } + return null; + }; + /** + * Disposes the gamepad manager + */ + GamepadManager.prototype.dispose = function () { + if (this._gamepadEventSupported) { + if (this._onGamepadConnectedEvent) { + window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent); + } + if (this._onGamepadDisconnectedEvent) { + window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent); + } + this._onGamepadConnectedEvent = null; + this._onGamepadDisconnectedEvent = null; + } + this._babylonGamepads.forEach(function (gamepad) { + gamepad.dispose(); + }); + this.onGamepadConnectedObservable.clear(); + this.onGamepadDisconnectedObservable.clear(); + this._oneGamepadConnected = false; + this._stopMonitoringGamepads(); + this._babylonGamepads = []; + }; + GamepadManager.prototype._addNewGamepad = function (gamepad) { + if (!this._oneGamepadConnected) { + this._oneGamepadConnected = true; + } + var newGamepad; + var dualShock = (gamepad.id.search("054c") !== -1); + var xboxOne = (gamepad.id.search("Xbox One") !== -1); + if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) { + newGamepad = new _xboxGamepad__WEBPACK_IMPORTED_MODULE_4__["Xbox360Pad"](gamepad.id, gamepad.index, gamepad, xboxOne); + } + // if pose is supported, use the (WebVR) pose enabled controller, ignore DualShock (ps4) as they have a pose but should not be used for webVR + else if (gamepad.pose && !dualShock) { + newGamepad = _Gamepads_Controllers_poseEnabledController__WEBPACK_IMPORTED_MODULE_3__["PoseEnabledControllerHelper"].InitiateController(gamepad); + } + else { + newGamepad = new _gamepad__WEBPACK_IMPORTED_MODULE_5__["GenericPad"](gamepad.id, gamepad.index, gamepad); + } + this._babylonGamepads[newGamepad.index] = newGamepad; + return newGamepad; + }; + GamepadManager.prototype._startMonitoringGamepads = function () { + if (!this._isMonitoring) { + this._isMonitoring = true; + //back-comp + if (!this._scene) { + this._checkGamepadsStatus(); + } + } + }; + GamepadManager.prototype._stopMonitoringGamepads = function () { + this._isMonitoring = false; + }; + /** @hidden */ + GamepadManager.prototype._checkGamepadsStatus = function () { + var _this = this; + // Hack to be compatible Chrome + this._updateGamepadObjects(); + for (var i in this._babylonGamepads) { + var gamepad = this._babylonGamepads[i]; + if (!gamepad || !gamepad.isConnected) { + continue; + } + gamepad.update(); + } + if (this._isMonitoring && !this._scene) { + _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].QueueNewFrame(function () { _this._checkGamepadsStatus(); }); + } + }; + // This function is called only on Chrome, which does not properly support + // connection/disconnection events and forces you to recopy again the gamepad object + GamepadManager.prototype._updateGamepadObjects = function () { + var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []); + for (var i = 0; i < gamepads.length; i++) { + var gamepad = gamepads[i]; + if (gamepad) { + if (!this._babylonGamepads[gamepad.index]) { + var newGamepad = this._addNewGamepad(gamepad); + this.onGamepadConnectedObservable.notifyObservers(newGamepad); + } + else { + // Forced to copy again this object for Chrome for unknown reason + this._babylonGamepads[i].browserGamepad = gamepad; + if (!this._babylonGamepads[i].isConnected) { + this._babylonGamepads[i]._isConnected = true; + this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]); + } + } + } + } + }; + return GamepadManager; +}()); + + + +/***/ }), + +/***/ "./Gamepads/gamepadSceneComponent.ts": +/*!*******************************************!*\ + !*** ./Gamepads/gamepadSceneComponent.ts ***! + \*******************************************/ +/*! exports provided: GamepadSystemSceneComponent */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GamepadSystemSceneComponent", function() { return GamepadSystemSceneComponent; }); +/* harmony import */ var _scene__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../scene */ "./scene.ts"); +/* harmony import */ var _sceneComponent__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../sceneComponent */ "./sceneComponent.ts"); +/* harmony import */ var _gamepadManager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./gamepadManager */ "./Gamepads/gamepadManager.ts"); +/* harmony import */ var _Cameras_freeCameraInputsManager__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Cameras/freeCameraInputsManager */ "./Cameras/freeCameraInputsManager.ts"); +/* harmony import */ var _Cameras_Inputs_freeCameraGamepadInput__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Cameras/Inputs/freeCameraGamepadInput */ "./Cameras/Inputs/freeCameraGamepadInput.ts"); +/* harmony import */ var _Cameras_arcRotateCameraInputsManager__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Cameras/arcRotateCameraInputsManager */ "./Cameras/arcRotateCameraInputsManager.ts"); +/* harmony import */ var _Cameras_Inputs_arcRotateCameraGamepadInput__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Cameras/Inputs/arcRotateCameraGamepadInput */ "./Cameras/Inputs/arcRotateCameraGamepadInput.ts"); + + + + + + + +Object.defineProperty(_scene__WEBPACK_IMPORTED_MODULE_0__["Scene"].prototype, "gamepadManager", { + get: function () { + if (!this._gamepadManager) { + this._gamepadManager = new _gamepadManager__WEBPACK_IMPORTED_MODULE_2__["GamepadManager"](this); + var component = this._getComponent(_sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].NAME_GAMEPAD); + if (!component) { + component = new GamepadSystemSceneComponent(this); + this._addComponent(component); + } + } + return this._gamepadManager; + }, + enumerable: true, + configurable: true +}); +/** + * Adds a gamepad to the free camera inputs manager + */ +_Cameras_freeCameraInputsManager__WEBPACK_IMPORTED_MODULE_3__["FreeCameraInputsManager"].prototype.addGamepad = function () { + this.add(new _Cameras_Inputs_freeCameraGamepadInput__WEBPACK_IMPORTED_MODULE_4__["FreeCameraGamepadInput"]()); + return this; +}; +/** + * Adds a gamepad to the arc rotate camera inputs manager + */ +_Cameras_arcRotateCameraInputsManager__WEBPACK_IMPORTED_MODULE_5__["ArcRotateCameraInputsManager"].prototype.addGamepad = function () { + this.add(new _Cameras_Inputs_arcRotateCameraGamepadInput__WEBPACK_IMPORTED_MODULE_6__["ArcRotateCameraGamepadInput"]()); + return this; +}; +/** + * Defines the gamepad scene component responsible to manage gamepads in a given scene + */ +var GamepadSystemSceneComponent = /** @class */ (function () { + /** + * Creates a new instance of the component for the given scene + * @param scene Defines the scene to register the component in + */ + function GamepadSystemSceneComponent(scene) { + /** + * The component name helpfull to identify the component in the list of scene components. + */ + this.name = _sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].NAME_GAMEPAD; + this.scene = scene; + } + /** + * Registers the component in a given scene + */ + GamepadSystemSceneComponent.prototype.register = function () { + this.scene._beforeCameraUpdateStage.registerStep(_sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate); + }; + /** + * Rebuilds the elements related to this component in case of + * context lost for instance. + */ + GamepadSystemSceneComponent.prototype.rebuild = function () { + // Nothing to do for gamepads + }; + /** + * Disposes the component and the associated ressources + */ + GamepadSystemSceneComponent.prototype.dispose = function () { + var gamepadManager = this.scene._gamepadManager; + if (gamepadManager) { + gamepadManager.dispose(); + this.scene._gamepadManager = null; + } + }; + GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () { + var gamepadManager = this.scene._gamepadManager; + if (gamepadManager && gamepadManager._isMonitoring) { + gamepadManager._checkGamepadsStatus(); + } + }; + return GamepadSystemSceneComponent; +}()); + + + +/***/ }), + +/***/ "./Gamepads/index.ts": +/*!***************************!*\ + !*** ./Gamepads/index.ts ***! + \***************************/ +/*! exports provided: StickValues, Gamepad, GenericPad, GamepadManager, GamepadSystemSceneComponent, Xbox360Button, Xbox360Dpad, Xbox360Pad, DaydreamController, GearVRController, GenericController, OculusTouchController, PoseEnabledControllerType, PoseEnabledControllerHelper, PoseEnabledController, ViveController, WebVRController, WindowsMotionController */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Controllers_index__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Controllers/index */ "./Gamepads/Controllers/index.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DaydreamController", function() { return _Controllers_index__WEBPACK_IMPORTED_MODULE_0__["DaydreamController"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GearVRController", function() { return _Controllers_index__WEBPACK_IMPORTED_MODULE_0__["GearVRController"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GenericController", function() { return _Controllers_index__WEBPACK_IMPORTED_MODULE_0__["GenericController"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OculusTouchController", function() { return _Controllers_index__WEBPACK_IMPORTED_MODULE_0__["OculusTouchController"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PoseEnabledControllerType", function() { return _Controllers_index__WEBPACK_IMPORTED_MODULE_0__["PoseEnabledControllerType"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PoseEnabledControllerHelper", function() { return _Controllers_index__WEBPACK_IMPORTED_MODULE_0__["PoseEnabledControllerHelper"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PoseEnabledController", function() { return _Controllers_index__WEBPACK_IMPORTED_MODULE_0__["PoseEnabledController"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ViveController", function() { return _Controllers_index__WEBPACK_IMPORTED_MODULE_0__["ViveController"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebVRController", function() { return _Controllers_index__WEBPACK_IMPORTED_MODULE_0__["WebVRController"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WindowsMotionController", function() { return _Controllers_index__WEBPACK_IMPORTED_MODULE_0__["WindowsMotionController"]; }); + +/* harmony import */ var _gamepad__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./gamepad */ "./Gamepads/gamepad.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StickValues", function() { return _gamepad__WEBPACK_IMPORTED_MODULE_1__["StickValues"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Gamepad", function() { return _gamepad__WEBPACK_IMPORTED_MODULE_1__["Gamepad"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GenericPad", function() { return _gamepad__WEBPACK_IMPORTED_MODULE_1__["GenericPad"]; }); + +/* harmony import */ var _gamepadManager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./gamepadManager */ "./Gamepads/gamepadManager.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GamepadManager", function() { return _gamepadManager__WEBPACK_IMPORTED_MODULE_2__["GamepadManager"]; }); + +/* harmony import */ var _gamepadSceneComponent__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./gamepadSceneComponent */ "./Gamepads/gamepadSceneComponent.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GamepadSystemSceneComponent", function() { return _gamepadSceneComponent__WEBPACK_IMPORTED_MODULE_3__["GamepadSystemSceneComponent"]; }); + +/* harmony import */ var _xboxGamepad__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./xboxGamepad */ "./Gamepads/xboxGamepad.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Xbox360Button", function() { return _xboxGamepad__WEBPACK_IMPORTED_MODULE_4__["Xbox360Button"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Xbox360Dpad", function() { return _xboxGamepad__WEBPACK_IMPORTED_MODULE_4__["Xbox360Dpad"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Xbox360Pad", function() { return _xboxGamepad__WEBPACK_IMPORTED_MODULE_4__["Xbox360Pad"]; }); + + + + + + + + +/***/ }), + +/***/ "./Gamepads/xboxGamepad.ts": +/*!*********************************!*\ + !*** ./Gamepads/xboxGamepad.ts ***! + \*********************************/ +/*! exports provided: Xbox360Button, Xbox360Dpad, Xbox360Pad */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Xbox360Button", function() { return Xbox360Button; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Xbox360Dpad", function() { return Xbox360Dpad; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Xbox360Pad", function() { return Xbox360Pad; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Gamepads/gamepad */ "./Gamepads/gamepad.ts"); + + + +/** + * Defines supported buttons for XBox360 compatible gamepads + */ +var Xbox360Button; +(function (Xbox360Button) { + /** A */ + Xbox360Button[Xbox360Button["A"] = 0] = "A"; + /** B */ + Xbox360Button[Xbox360Button["B"] = 1] = "B"; + /** X */ + Xbox360Button[Xbox360Button["X"] = 2] = "X"; + /** Y */ + Xbox360Button[Xbox360Button["Y"] = 3] = "Y"; + /** Start */ + Xbox360Button[Xbox360Button["Start"] = 4] = "Start"; + /** Back */ + Xbox360Button[Xbox360Button["Back"] = 5] = "Back"; + /** Left button */ + Xbox360Button[Xbox360Button["LB"] = 6] = "LB"; + /** Right button */ + Xbox360Button[Xbox360Button["RB"] = 7] = "RB"; + /** Left stick */ + Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick"; + /** Right stick */ + Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick"; +})(Xbox360Button || (Xbox360Button = {})); +/** Defines values for XBox360 DPad */ +var Xbox360Dpad; +(function (Xbox360Dpad) { + /** Up */ + Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up"; + /** Down */ + Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down"; + /** Left */ + Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left"; + /** Right */ + Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right"; +})(Xbox360Dpad || (Xbox360Dpad = {})); +/** + * Defines a XBox360 gamepad + */ +var Xbox360Pad = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Xbox360Pad, _super); + /** + * Creates a new XBox360 gamepad object + * @param id defines the id of this gamepad + * @param index defines its index + * @param gamepad defines the internal HTML gamepad object + * @param xboxOne defines if it is a XBox One gamepad + */ + function Xbox360Pad(id, index, gamepad, xboxOne) { + if (xboxOne === void 0) { xboxOne = false; } + var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this; + _this._leftTrigger = 0; + _this._rightTrigger = 0; + /** Observable raised when a button is pressed */ + _this.onButtonDownObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + /** Observable raised when a button is released */ + _this.onButtonUpObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + /** Observable raised when a pad is pressed */ + _this.onPadDownObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + /** Observable raised when a pad is released */ + _this.onPadUpObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + _this._buttonA = 0; + _this._buttonB = 0; + _this._buttonX = 0; + _this._buttonY = 0; + _this._buttonBack = 0; + _this._buttonStart = 0; + _this._buttonLB = 0; + _this._buttonRB = 0; + _this._buttonLeftStick = 0; + _this._buttonRightStick = 0; + _this._dPadUp = 0; + _this._dPadDown = 0; + _this._dPadLeft = 0; + _this._dPadRight = 0; + _this._isXboxOnePad = false; + _this.type = _Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_2__["Gamepad"].XBOX; + _this._isXboxOnePad = xboxOne; + return _this; + } + /** + * Defines the callback to call when left trigger is pressed + * @param callback defines the callback to use + */ + Xbox360Pad.prototype.onlefttriggerchanged = function (callback) { + this._onlefttriggerchanged = callback; + }; + /** + * Defines the callback to call when right trigger is pressed + * @param callback defines the callback to use + */ + Xbox360Pad.prototype.onrighttriggerchanged = function (callback) { + this._onrighttriggerchanged = callback; + }; + Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", { + /** + * Gets the left trigger value + */ + get: function () { + return this._leftTrigger; + }, + /** + * Sets the left trigger value + */ + set: function (newValue) { + if (this._onlefttriggerchanged && this._leftTrigger !== newValue) { + this._onlefttriggerchanged(newValue); + } + this._leftTrigger = newValue; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", { + /** + * Gets the right trigger value + */ + get: function () { + return this._rightTrigger; + }, + /** + * Sets the right trigger value + */ + set: function (newValue) { + if (this._onrighttriggerchanged && this._rightTrigger !== newValue) { + this._onrighttriggerchanged(newValue); + } + this._rightTrigger = newValue; + }, + enumerable: true, + configurable: true + }); + /** + * Defines the callback to call when a button is pressed + * @param callback defines the callback to use + */ + Xbox360Pad.prototype.onbuttondown = function (callback) { + this._onbuttondown = callback; + }; + /** + * Defines the callback to call when a button is released + * @param callback defines the callback to use + */ + Xbox360Pad.prototype.onbuttonup = function (callback) { + this._onbuttonup = callback; + }; + /** + * Defines the callback to call when a pad is pressed + * @param callback defines the callback to use + */ + Xbox360Pad.prototype.ondpaddown = function (callback) { + this._ondpaddown = callback; + }; + /** + * Defines the callback to call when a pad is released + * @param callback defines the callback to use + */ + Xbox360Pad.prototype.ondpadup = function (callback) { + this._ondpadup = callback; + }; + Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) { + if (newValue !== currentValue) { + if (newValue === 1) { + if (this._onbuttondown) { + this._onbuttondown(buttonType); + } + this.onButtonDownObservable.notifyObservers(buttonType); + } + if (newValue === 0) { + if (this._onbuttonup) { + this._onbuttonup(buttonType); + } + this.onButtonUpObservable.notifyObservers(buttonType); + } + } + return newValue; + }; + Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) { + if (newValue !== currentValue) { + if (newValue === 1) { + if (this._ondpaddown) { + this._ondpaddown(buttonType); + } + this.onPadDownObservable.notifyObservers(buttonType); + } + if (newValue === 0) { + if (this._ondpadup) { + this._ondpadup(buttonType); + } + this.onPadUpObservable.notifyObservers(buttonType); + } + } + return newValue; + }; + Object.defineProperty(Xbox360Pad.prototype, "buttonA", { + /** + * Gets the value of the `A` button + */ + get: function () { + return this._buttonA; + }, + /** + * Sets the value of the `A` button + */ + set: function (value) { + this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Xbox360Pad.prototype, "buttonB", { + /** + * Gets the value of the `B` button + */ + get: function () { + return this._buttonB; + }, + /** + * Sets the value of the `B` button + */ + set: function (value) { + this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Xbox360Pad.prototype, "buttonX", { + /** + * Gets the value of the `X` button + */ + get: function () { + return this._buttonX; + }, + /** + * Sets the value of the `X` button + */ + set: function (value) { + this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Xbox360Pad.prototype, "buttonY", { + /** + * Gets the value of the `Y` button + */ + get: function () { + return this._buttonY; + }, + /** + * Sets the value of the `Y` button + */ + set: function (value) { + this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Xbox360Pad.prototype, "buttonStart", { + /** + * Gets the value of the `Start` button + */ + get: function () { + return this._buttonStart; + }, + /** + * Sets the value of the `Start` button + */ + set: function (value) { + this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Xbox360Pad.prototype, "buttonBack", { + /** + * Gets the value of the `Back` button + */ + get: function () { + return this._buttonBack; + }, + /** + * Sets the value of the `Back` button + */ + set: function (value) { + this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Xbox360Pad.prototype, "buttonLB", { + /** + * Gets the value of the `Left` button + */ + get: function () { + return this._buttonLB; + }, + /** + * Sets the value of the `Left` button + */ + set: function (value) { + this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Xbox360Pad.prototype, "buttonRB", { + /** + * Gets the value of the `Right` button + */ + get: function () { + return this._buttonRB; + }, + /** + * Sets the value of the `Right` button + */ + set: function (value) { + this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", { + /** + * Gets the value of the Left joystick + */ + get: function () { + return this._buttonLeftStick; + }, + /** + * Sets the value of the Left joystick + */ + set: function (value) { + this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", { + /** + * Gets the value of the Right joystick + */ + get: function () { + return this._buttonRightStick; + }, + /** + * Sets the value of the Right joystick + */ + set: function (value) { + this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Xbox360Pad.prototype, "dPadUp", { + /** + * Gets the value of D-pad up + */ + get: function () { + return this._dPadUp; + }, + /** + * Sets the value of D-pad up + */ + set: function (value) { + this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Xbox360Pad.prototype, "dPadDown", { + /** + * Gets the value of D-pad down + */ + get: function () { + return this._dPadDown; + }, + /** + * Sets the value of D-pad down + */ + set: function (value) { + this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", { + /** + * Gets the value of D-pad left + */ + get: function () { + return this._dPadLeft; + }, + /** + * Sets the value of D-pad left + */ + set: function (value) { + this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Xbox360Pad.prototype, "dPadRight", { + /** + * Gets the value of D-pad right + */ + get: function () { + return this._dPadRight; + }, + /** + * Sets the value of D-pad right + */ + set: function (value) { + this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right); + }, + enumerable: true, + configurable: true + }); + /** + * Force the gamepad to synchronize with device values + */ + Xbox360Pad.prototype.update = function () { + _super.prototype.update.call(this); + if (this._isXboxOnePad) { + this.buttonA = this.browserGamepad.buttons[0].value; + this.buttonB = this.browserGamepad.buttons[1].value; + this.buttonX = this.browserGamepad.buttons[2].value; + this.buttonY = this.browserGamepad.buttons[3].value; + this.buttonLB = this.browserGamepad.buttons[4].value; + this.buttonRB = this.browserGamepad.buttons[5].value; + this.leftTrigger = this.browserGamepad.axes[2]; + this.rightTrigger = this.browserGamepad.axes[5]; + this.buttonBack = this.browserGamepad.buttons[9].value; + this.buttonStart = this.browserGamepad.buttons[8].value; + this.buttonLeftStick = this.browserGamepad.buttons[6].value; + this.buttonRightStick = this.browserGamepad.buttons[7].value; + this.dPadUp = this.browserGamepad.buttons[11].value; + this.dPadDown = this.browserGamepad.buttons[12].value; + this.dPadLeft = this.browserGamepad.buttons[13].value; + this.dPadRight = this.browserGamepad.buttons[14].value; + } + else { + this.buttonA = this.browserGamepad.buttons[0].value; + this.buttonB = this.browserGamepad.buttons[1].value; + this.buttonX = this.browserGamepad.buttons[2].value; + this.buttonY = this.browserGamepad.buttons[3].value; + this.buttonLB = this.browserGamepad.buttons[4].value; + this.buttonRB = this.browserGamepad.buttons[5].value; + this.leftTrigger = this.browserGamepad.buttons[6].value; + this.rightTrigger = this.browserGamepad.buttons[7].value; + this.buttonBack = this.browserGamepad.buttons[8].value; + this.buttonStart = this.browserGamepad.buttons[9].value; + this.buttonLeftStick = this.browserGamepad.buttons[10].value; + this.buttonRightStick = this.browserGamepad.buttons[11].value; + this.dPadUp = this.browserGamepad.buttons[12].value; + this.dPadDown = this.browserGamepad.buttons[13].value; + this.dPadLeft = this.browserGamepad.buttons[14].value; + this.dPadRight = this.browserGamepad.buttons[15].value; + } + }; + /** + * Disposes the gamepad + */ + Xbox360Pad.prototype.dispose = function () { + _super.prototype.dispose.call(this); + this.onButtonDownObservable.clear(); + this.onButtonUpObservable.clear(); + this.onPadDownObservable.clear(); + this.onPadUpObservable.clear(); + }; + return Xbox360Pad; +}(_Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_2__["Gamepad"])); + + + +/***/ }), + +/***/ "./Gizmos/axisDragGizmo.ts": +/*!*********************************!*\ + !*** ./Gizmos/axisDragGizmo.ts ***! + \*********************************/ +/*! exports provided: AxisDragGizmo */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AxisDragGizmo", function() { return AxisDragGizmo; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Meshes_transformNode__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Meshes/transformNode */ "./Meshes/transformNode.ts"); +/* harmony import */ var _Meshes_Builders_cylinderBuilder__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Meshes/Builders/cylinderBuilder */ "./Meshes/Builders/cylinderBuilder.ts"); +/* harmony import */ var _Behaviors_Meshes_pointerDragBehavior__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Behaviors/Meshes/pointerDragBehavior */ "./Behaviors/Meshes/pointerDragBehavior.ts"); +/* harmony import */ var _gizmo__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./gizmo */ "./Gizmos/gizmo.ts"); +/* harmony import */ var _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Rendering/utilityLayerRenderer */ "./Rendering/utilityLayerRenderer.ts"); +/* harmony import */ var _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Materials/standardMaterial */ "./Materials/standardMaterial.ts"); + + + + + + + + + +/** + * Single axis drag gizmo + */ +var AxisDragGizmo = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](AxisDragGizmo, _super); + /** + * Creates an AxisDragGizmo + * @param gizmoLayer The utility layer the gizmo will be added to + * @param dragAxis The axis which the gizmo will be able to drag on + * @param color The color of the gizmo + */ + function AxisDragGizmo(dragAxis, color, gizmoLayer, parent) { + if (color === void 0) { color = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color3"].Gray(); } + if (gizmoLayer === void 0) { gizmoLayer = _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_7__["UtilityLayerRenderer"].DefaultUtilityLayer; } + if (parent === void 0) { parent = null; } + var _this = _super.call(this, gizmoLayer) || this; + _this._pointerObserver = null; + /** + * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0) + */ + _this.snapDistance = 0; + /** + * Event that fires each time the gizmo snaps to a new location. + * * snapDistance is the the change in distance + */ + _this.onSnapObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + _this._isEnabled = true; + _this._parent = null; + _this._parent = parent; + // Create Material + _this._coloredMaterial = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_8__["StandardMaterial"]("", gizmoLayer.utilityLayerScene); + _this._coloredMaterial.diffuseColor = color; + _this._coloredMaterial.specularColor = color.subtract(new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color3"](0.1, 0.1, 0.1)); + _this._hoverMaterial = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_8__["StandardMaterial"]("", gizmoLayer.utilityLayerScene); + _this._hoverMaterial.diffuseColor = color.add(new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color3"](0.3, 0.3, 0.3)); + // Build mesh on root node + _this._arrow = AxisDragGizmo._CreateArrow(gizmoLayer.utilityLayerScene, _this._coloredMaterial); + _this._arrow.lookAt(_this._rootMesh.position.add(dragAxis)); + _this._arrow.scaling.scaleInPlace(1 / 3); + _this._arrow.parent = _this._rootMesh; + var currentSnapDragDistance = 0; + var tmpVector = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](); + var tmpSnapEvent = { snapDistance: 0 }; + // Add drag behavior to handle events when the gizmo is dragged + _this.dragBehavior = new _Behaviors_Meshes_pointerDragBehavior__WEBPACK_IMPORTED_MODULE_5__["PointerDragBehavior"]({ dragAxis: dragAxis }); + _this.dragBehavior.moveAttached = false; + _this._rootMesh.addBehavior(_this.dragBehavior); + var localDelta = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](); + var tmpMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"](); + _this.dragBehavior.onDragObservable.add(function (event) { + if (_this.attachedMesh) { + // Convert delta to local translation if it has a parent + if (_this.attachedMesh.parent) { + _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix); + tmpMatrix.setTranslationFromFloats(0, 0, 0); + _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta); + } + else { + localDelta.copyFrom(event.delta); + } + // Snapping logic + if (_this.snapDistance == 0) { + _this.attachedMesh.position.addInPlace(localDelta); + } + else { + currentSnapDragDistance += event.dragDistance; + if (Math.abs(currentSnapDragDistance) > _this.snapDistance) { + var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance); + currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance; + localDelta.normalizeToRef(tmpVector); + tmpVector.scaleInPlace(_this.snapDistance * dragSteps); + _this.attachedMesh.position.addInPlace(tmpVector); + tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps; + _this.onSnapObservable.notifyObservers(tmpSnapEvent); + } + } + } + }); + _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo) { + if (_this._customMeshSet) { + return; + } + var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1); + var material = isHovered ? _this._hoverMaterial : _this._coloredMaterial; + _this._rootMesh.getChildMeshes().forEach(function (m) { + m.material = material; + if (m.color) { + m.color = material.diffuseColor; + } + }); + }); + var light = gizmoLayer._getSharedGizmoLight(); + light.includedOnlyMeshes = light.includedOnlyMeshes.concat(_this._rootMesh.getChildMeshes(false)); + return _this; + } + /** @hidden */ + AxisDragGizmo._CreateArrow = function (scene, material) { + var arrow = new _Meshes_transformNode__WEBPACK_IMPORTED_MODULE_3__["TransformNode"]("arrow", scene); + var cylinder = _Meshes_Builders_cylinderBuilder__WEBPACK_IMPORTED_MODULE_4__["CylinderBuilder"].CreateCylinder("cylinder", { diameterTop: 0, height: 0.075, diameterBottom: 0.0375, tessellation: 96 }, scene); + var line = _Meshes_Builders_cylinderBuilder__WEBPACK_IMPORTED_MODULE_4__["CylinderBuilder"].CreateCylinder("cylinder", { diameterTop: 0.005, height: 0.275, diameterBottom: 0.005, tessellation: 96 }, scene); + line.material = material; + cylinder.parent = arrow; + line.parent = arrow; + // Position arrow pointing in its drag axis + cylinder.material = material; + cylinder.rotation.x = Math.PI / 2; + cylinder.position.z += 0.3; + line.position.z += 0.275 / 2; + line.rotation.x = Math.PI / 2; + return arrow; + }; + /** @hidden */ + AxisDragGizmo._CreateArrowInstance = function (scene, arrow) { + var instance = new _Meshes_transformNode__WEBPACK_IMPORTED_MODULE_3__["TransformNode"]("arrow", scene); + for (var _i = 0, _a = arrow.getChildMeshes(); _i < _a.length; _i++) { + var mesh = _a[_i]; + var childInstance = mesh.createInstance(mesh.name); + childInstance.parent = instance; + } + return instance; + }; + AxisDragGizmo.prototype._attachedMeshChanged = function (value) { + if (this.dragBehavior) { + this.dragBehavior.enabled = value ? true : false; + } + }; + Object.defineProperty(AxisDragGizmo.prototype, "isEnabled", { + get: function () { + return this._isEnabled; + }, + /** + * If the gizmo is enabled + */ + set: function (value) { + this._isEnabled = value; + if (!value) { + this.attachedMesh = null; + } + else { + if (this._parent) { + this.attachedMesh = this._parent.attachedMesh; + } + } + }, + enumerable: true, + configurable: true + }); + /** + * Disposes of the gizmo + */ + AxisDragGizmo.prototype.dispose = function () { + this.onSnapObservable.clear(); + this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver); + this.dragBehavior.detach(); + if (this._arrow) { + this._arrow.dispose(); + } + [this._coloredMaterial, this._hoverMaterial].forEach(function (matl) { + if (matl) { + matl.dispose(); + } + }); + _super.prototype.dispose.call(this); + }; + return AxisDragGizmo; +}(_gizmo__WEBPACK_IMPORTED_MODULE_6__["Gizmo"])); + + + +/***/ }), + +/***/ "./Gizmos/axisScaleGizmo.ts": +/*!**********************************!*\ + !*** ./Gizmos/axisScaleGizmo.ts ***! + \**********************************/ +/*! exports provided: AxisScaleGizmo */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AxisScaleGizmo", function() { return AxisScaleGizmo; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Meshes/abstractMesh */ "./Meshes/abstractMesh.ts"); +/* harmony import */ var _Meshes_Builders_boxBuilder__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Meshes/Builders/boxBuilder */ "./Meshes/Builders/boxBuilder.ts"); +/* harmony import */ var _Meshes_Builders_cylinderBuilder__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Meshes/Builders/cylinderBuilder */ "./Meshes/Builders/cylinderBuilder.ts"); +/* harmony import */ var _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Materials/standardMaterial */ "./Materials/standardMaterial.ts"); +/* harmony import */ var _Behaviors_Meshes_pointerDragBehavior__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Behaviors/Meshes/pointerDragBehavior */ "./Behaviors/Meshes/pointerDragBehavior.ts"); +/* harmony import */ var _gizmo__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./gizmo */ "./Gizmos/gizmo.ts"); +/* harmony import */ var _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Rendering/utilityLayerRenderer */ "./Rendering/utilityLayerRenderer.ts"); + + + + + + + + + + +/** + * Single axis scale gizmo + */ +var AxisScaleGizmo = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](AxisScaleGizmo, _super); + /** + * Creates an AxisScaleGizmo + * @param gizmoLayer The utility layer the gizmo will be added to + * @param dragAxis The axis which the gizmo will be able to scale on + * @param color The color of the gizmo + */ + function AxisScaleGizmo(dragAxis, color, gizmoLayer, parent) { + if (color === void 0) { color = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color3"].Gray(); } + if (gizmoLayer === void 0) { gizmoLayer = _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_9__["UtilityLayerRenderer"].DefaultUtilityLayer; } + if (parent === void 0) { parent = null; } + var _this = _super.call(this, gizmoLayer) || this; + _this._pointerObserver = null; + /** + * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0) + */ + _this.snapDistance = 0; + /** + * Event that fires each time the gizmo snaps to a new location. + * * snapDistance is the the change in distance + */ + _this.onSnapObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + /** + * If the scaling operation should be done on all axis (default: false) + */ + _this.uniformScaling = false; + _this._isEnabled = true; + _this._parent = null; + _this._parent = parent; + // Create Material + _this._coloredMaterial = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_6__["StandardMaterial"]("", gizmoLayer.utilityLayerScene); + _this._coloredMaterial.diffuseColor = color; + _this._coloredMaterial.specularColor = color.subtract(new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color3"](0.1, 0.1, 0.1)); + _this._hoverMaterial = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_6__["StandardMaterial"]("", gizmoLayer.utilityLayerScene); + _this._hoverMaterial.diffuseColor = color.add(new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color3"](0.3, 0.3, 0.3)); + // Build mesh on root node + _this._arrow = new _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_3__["AbstractMesh"]("", gizmoLayer.utilityLayerScene); + var arrowMesh = _Meshes_Builders_boxBuilder__WEBPACK_IMPORTED_MODULE_4__["BoxBuilder"].CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene); + var arrowTail = _Meshes_Builders_cylinderBuilder__WEBPACK_IMPORTED_MODULE_5__["CylinderBuilder"].CreateCylinder("cylinder", { diameterTop: 0.005, height: 0.275, diameterBottom: 0.005, tessellation: 96 }, gizmoLayer.utilityLayerScene); + arrowTail.material = _this._coloredMaterial; + _this._arrow.addChild(arrowMesh); + _this._arrow.addChild(arrowTail); + // Position arrow pointing in its drag axis + arrowMesh.scaling.scaleInPlace(0.1); + arrowMesh.material = _this._coloredMaterial; + arrowMesh.rotation.x = Math.PI / 2; + arrowMesh.position.z += 0.3; + arrowTail.position.z += 0.275 / 2; + arrowTail.rotation.x = Math.PI / 2; + _this._arrow.lookAt(_this._rootMesh.position.add(dragAxis)); + _this._rootMesh.addChild(_this._arrow); + _this._arrow.scaling.scaleInPlace(1 / 3); + // Add drag behavior to handle events when the gizmo is dragged + _this.dragBehavior = new _Behaviors_Meshes_pointerDragBehavior__WEBPACK_IMPORTED_MODULE_7__["PointerDragBehavior"]({ dragAxis: dragAxis }); + _this.dragBehavior.moveAttached = false; + _this._rootMesh.addBehavior(_this.dragBehavior); + var currentSnapDragDistance = 0; + var tmpVector = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](); + var tmpSnapEvent = { snapDistance: 0 }; + _this.dragBehavior.onDragObservable.add(function (event) { + if (_this.attachedMesh) { + // Drag strength is modified by the scale of the gizmo (eg. for small objects like boombox the strength will be increased to match the behavior of larger objects) + var dragStrength = event.dragDistance * ((_this.scaleRatio * 3) / _this._rootMesh.scaling.length()); + // Snapping logic + var snapped = false; + var dragSteps = 0; + if (_this.uniformScaling) { + _this.attachedMesh.scaling.normalizeToRef(tmpVector); + if (tmpVector.y < 0) { + tmpVector.scaleInPlace(-1); + } + } + else { + tmpVector.copyFrom(dragAxis); + } + if (_this.snapDistance == 0) { + tmpVector.scaleToRef(dragStrength, tmpVector); + } + else { + currentSnapDragDistance += dragStrength; + if (Math.abs(currentSnapDragDistance) > _this.snapDistance) { + dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance); + if (currentSnapDragDistance < 0) { + dragSteps *= -1; + } + currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance; + tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector); + snapped = true; + } + else { + tmpVector.scaleInPlace(0); + } + } + _this.attachedMesh.scaling.addInPlace(tmpVector); + if (snapped) { + tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps; + _this.onSnapObservable.notifyObservers(tmpSnapEvent); + } + } + }); + _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo) { + if (_this._customMeshSet) { + return; + } + var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1); + var material = isHovered ? _this._hoverMaterial : _this._coloredMaterial; + _this._rootMesh.getChildMeshes().forEach(function (m) { + m.material = material; + if (m.color) { + m.color = material.diffuseColor; + } + }); + }); + var light = gizmoLayer._getSharedGizmoLight(); + light.includedOnlyMeshes = light.includedOnlyMeshes.concat(_this._rootMesh.getChildMeshes()); + return _this; + } + AxisScaleGizmo.prototype._attachedMeshChanged = function (value) { + if (this.dragBehavior) { + this.dragBehavior.enabled = value ? true : false; + } + }; + Object.defineProperty(AxisScaleGizmo.prototype, "isEnabled", { + get: function () { + return this._isEnabled; + }, + /** + * If the gizmo is enabled + */ + set: function (value) { + this._isEnabled = value; + if (!value) { + this.attachedMesh = null; + } + else { + if (this._parent) { + this.attachedMesh = this._parent.attachedMesh; + } + } + }, + enumerable: true, + configurable: true + }); + /** + * Disposes of the gizmo + */ + AxisScaleGizmo.prototype.dispose = function () { + this.onSnapObservable.clear(); + this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver); + this.dragBehavior.detach(); + if (this._arrow) { + this._arrow.dispose(); + } + [this._coloredMaterial, this._hoverMaterial].forEach(function (matl) { + if (matl) { + matl.dispose(); + } + }); + _super.prototype.dispose.call(this); + }; + /** + * Disposes and replaces the current meshes in the gizmo with the specified mesh + * @param mesh The mesh to replace the default mesh of the gizmo + * @param useGizmoMaterial If the gizmo's default material should be used (default: false) + */ + AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) { + var _this = this; + if (useGizmoMaterial === void 0) { useGizmoMaterial = false; } + _super.prototype.setCustomMesh.call(this, mesh); + if (useGizmoMaterial) { + this._rootMesh.getChildMeshes().forEach(function (m) { + m.material = _this._coloredMaterial; + if (m.color) { + m.color = _this._coloredMaterial.diffuseColor; + } + }); + this._customMeshSet = false; + } + }; + return AxisScaleGizmo; +}(_gizmo__WEBPACK_IMPORTED_MODULE_8__["Gizmo"])); + + + +/***/ }), + +/***/ "./Gizmos/boundingBoxGizmo.ts": +/*!************************************!*\ + !*** ./Gizmos/boundingBoxGizmo.ts ***! + \************************************/ +/*! exports provided: BoundingBoxGizmo */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BoundingBoxGizmo", function() { return BoundingBoxGizmo; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Meshes/abstractMesh */ "./Meshes/abstractMesh.ts"); +/* harmony import */ var _Meshes_mesh__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Meshes/mesh */ "./Meshes/mesh.ts"); +/* harmony import */ var _Meshes_Builders_sphereBuilder__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Meshes/Builders/sphereBuilder */ "./Meshes/Builders/sphereBuilder.ts"); +/* harmony import */ var _Meshes_Builders_boxBuilder__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Meshes/Builders/boxBuilder */ "./Meshes/Builders/boxBuilder.ts"); +/* harmony import */ var _Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Meshes/Builders/linesBuilder */ "./Meshes/Builders/linesBuilder.ts"); +/* harmony import */ var _Behaviors_Meshes_pointerDragBehavior__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Behaviors/Meshes/pointerDragBehavior */ "./Behaviors/Meshes/pointerDragBehavior.ts"); +/* harmony import */ var _gizmo__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./gizmo */ "./Gizmos/gizmo.ts"); +/* harmony import */ var _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../Rendering/utilityLayerRenderer */ "./Rendering/utilityLayerRenderer.ts"); +/* harmony import */ var _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../Materials/standardMaterial */ "./Materials/standardMaterial.ts"); +/* harmony import */ var _Misc_pivotTools__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../Misc/pivotTools */ "./Misc/pivotTools.ts"); + + + + + + + + + + + + + + + +/** + * Bounding box gizmo + */ +var BoundingBoxGizmo = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](BoundingBoxGizmo, _super); + /** + * Creates an BoundingBoxGizmo + * @param gizmoLayer The utility layer the gizmo will be added to + * @param color The color of the gizmo + */ + function BoundingBoxGizmo(color, gizmoLayer) { + if (color === void 0) { color = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Color3"].Gray(); } + if (gizmoLayer === void 0) { gizmoLayer = _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_11__["UtilityLayerRenderer"].DefaultKeepDepthUtilityLayer; } + var _this = _super.call(this, gizmoLayer) || this; + _this._boundingDimensions = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](1, 1, 1); + _this._renderObserver = null; + _this._pointerObserver = null; + _this._scaleDragSpeed = 0.2; + _this._tmpQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"](); + _this._tmpVector = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0); + _this._tmpRotationMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"](); + /** + * If child meshes should be ignored when calculating the boudning box. This should be set to true to avoid perf hits with heavily nested meshes (Default: false) + */ + _this.ignoreChildren = false; + /** + * Returns true if a descendant should be included when computing the bounding box. When null, all descendants are included. If ignoreChildren is set this will be ignored. (Default: null) + */ + _this.includeChildPredicate = null; + /** + * The size of the rotation spheres attached to the bounding box (Default: 0.1) + */ + _this.rotationSphereSize = 0.1; + /** + * The size of the scale boxes attached to the bounding box (Default: 0.1) + */ + _this.scaleBoxSize = 0.1; + /** + * If set, the rotation spheres and scale boxes will increase in size based on the distance away from the camera to have a consistent screen size (Default: false) + */ + _this.fixedDragMeshScreenSize = false; + /** + * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10) + */ + _this.fixedDragMeshScreenSizeDistanceFactor = 10; + /** + * Fired when a rotation sphere or scale box is dragged + */ + _this.onDragStartObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + /** + * Fired when a scale box is dragged + */ + _this.onScaleBoxDragObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + /** + * Fired when a scale box drag is ended + */ + _this.onScaleBoxDragEndObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + /** + * Fired when a rotation sphere is dragged + */ + _this.onRotationSphereDragObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + /** + * Fired when a rotation sphere drag is ended + */ + _this.onRotationSphereDragEndObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + /** + * Relative bounding box pivot used when scaling the attached mesh. When null object with scale from the opposite corner. 0.5,0.5,0.5 for center and 0.5,0,0.5 for bottom (Default: null) + */ + _this.scalePivot = null; + _this._existingMeshScale = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](); + // Dragging + _this._dragMesh = null; + _this.pointerDragBehavior = new _Behaviors_Meshes_pointerDragBehavior__WEBPACK_IMPORTED_MODULE_9__["PointerDragBehavior"](); + // Do not update the gizmo's scale so it has a fixed size to the object its attached to + _this._updateScale = false; + _this._anchorMesh = new _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_4__["AbstractMesh"]("anchor", gizmoLayer.utilityLayerScene); + // Create Materials + _this.coloredMaterial = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_12__["StandardMaterial"]("", gizmoLayer.utilityLayerScene); + _this.coloredMaterial.disableLighting = true; + _this.hoverColoredMaterial = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_12__["StandardMaterial"]("", gizmoLayer.utilityLayerScene); + _this.hoverColoredMaterial.disableLighting = true; + // Build bounding box out of lines + _this._lineBoundingBox = new _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_4__["AbstractMesh"]("", gizmoLayer.utilityLayerScene); + _this._lineBoundingBox.rotationQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"](); + var lines = []; + lines.push(_Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_8__["LinesBuilder"].CreateLines("lines", { points: [new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0), new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene)); + lines.push(_Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_8__["LinesBuilder"].CreateLines("lines", { points: [new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0), new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene)); + lines.push(_Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_8__["LinesBuilder"].CreateLines("lines", { points: [new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0), new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene)); + lines.push(_Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_8__["LinesBuilder"].CreateLines("lines", { points: [new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](_this._boundingDimensions.x, 0, 0), new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene)); + lines.push(_Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_8__["LinesBuilder"].CreateLines("lines", { points: [new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](_this._boundingDimensions.x, 0, 0), new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene)); + lines.push(_Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_8__["LinesBuilder"].CreateLines("lines", { points: [new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, _this._boundingDimensions.y, 0), new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene)); + lines.push(_Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_8__["LinesBuilder"].CreateLines("lines", { points: [new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, _this._boundingDimensions.y, 0), new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene)); + lines.push(_Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_8__["LinesBuilder"].CreateLines("lines", { points: [new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, _this._boundingDimensions.z), new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene)); + lines.push(_Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_8__["LinesBuilder"].CreateLines("lines", { points: [new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, _this._boundingDimensions.z), new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene)); + lines.push(_Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_8__["LinesBuilder"].CreateLines("lines", { points: [new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene)); + lines.push(_Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_8__["LinesBuilder"].CreateLines("lines", { points: [new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene)); + lines.push(_Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_8__["LinesBuilder"].CreateLines("lines", { points: [new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene)); + lines.forEach(function (l) { + l.color = color; + l.position.addInPlace(new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2)); + l.isPickable = false; + _this._lineBoundingBox.addChild(l); + }); + _this._rootMesh.addChild(_this._lineBoundingBox); + _this.setColor(color); + // Create rotation spheres + _this._rotateSpheresParent = new _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_4__["AbstractMesh"]("", gizmoLayer.utilityLayerScene); + _this._rotateSpheresParent.rotationQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"](); + var _loop_1 = function (i_1) { + var sphere = _Meshes_Builders_sphereBuilder__WEBPACK_IMPORTED_MODULE_6__["SphereBuilder"].CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene); + sphere.rotationQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"](); + sphere.material = this_1.coloredMaterial; + // Drag behavior + _dragBehavior = new _Behaviors_Meshes_pointerDragBehavior__WEBPACK_IMPORTED_MODULE_9__["PointerDragBehavior"]({}); + _dragBehavior.moveAttached = false; + _dragBehavior.updateDragPlane = false; + sphere.addBehavior(_dragBehavior); + var startingTurnDirection = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](1, 0, 0); + var totalTurnAmountOfDrag = 0; + _dragBehavior.onDragStartObservable.add(function () { + startingTurnDirection.copyFrom(sphere.forward); + totalTurnAmountOfDrag = 0; + }); + _dragBehavior.onDragObservable.add(function (event) { + _this.onRotationSphereDragObservable.notifyObservers({}); + if (_this.attachedMesh) { + var originalParent = _this.attachedMesh.parent; + if (originalParent && (originalParent.scaling && originalParent.scaling.isNonUniformWithinEpsilon(0.001))) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_2__["Logger"].Warn("BoundingBoxGizmo controls are not supported on child meshes with non-uniform parent scaling"); + return; + } + _Misc_pivotTools__WEBPACK_IMPORTED_MODULE_13__["PivotTools"]._RemoveAndStorePivotPoint(_this.attachedMesh); + var worldDragDirection = startingTurnDirection; + // Project the world right on to the drag plane + var toSub = event.dragPlaneNormal.scale(_Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Dot(event.dragPlaneNormal, worldDragDirection)); + var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew(); + // project drag delta on to the resulting drag axis and rotate based on that + var projectDist = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Dot(dragAxis, event.delta) < 0 ? Math.abs(event.delta.length()) : -Math.abs(event.delta.length()); + // Make rotation relative to size of mesh. + projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length(); + // Rotate based on axis + if (!_this.attachedMesh.rotationQuaternion) { + _this.attachedMesh.rotationQuaternion = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z); + } + if (!_this._anchorMesh.rotationQuaternion) { + _this._anchorMesh.rotationQuaternion = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z); + } + // Do not allow the object to turn more than a full circle + totalTurnAmountOfDrag += projectDist; + if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) { + if (i_1 >= 8) { + _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion); + } + else if (i_1 >= 4) { + _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion); + } + else { + _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion); + } + // Rotate around center of bounding box + _this._anchorMesh.addChild(_this.attachedMesh); + _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion); + _this._anchorMesh.removeChild(_this.attachedMesh); + _this.attachedMesh.setParent(originalParent); + } + _this.updateBoundingBox(); + _Misc_pivotTools__WEBPACK_IMPORTED_MODULE_13__["PivotTools"]._RestorePivotPoint(_this.attachedMesh); + } + _this._updateDummy(); + }); + // Selection/deselection + _dragBehavior.onDragStartObservable.add(function () { + _this.onDragStartObservable.notifyObservers({}); + _this._selectNode(sphere); + }); + _dragBehavior.onDragEndObservable.add(function () { + _this.onRotationSphereDragEndObservable.notifyObservers({}); + _this._selectNode(null); + _this._updateDummy(); + }); + this_1._rotateSpheresParent.addChild(sphere); + }; + var this_1 = this, _dragBehavior; + for (var i_1 = 0; i_1 < 12; i_1++) { + _loop_1(i_1); + } + _this._rootMesh.addChild(_this._rotateSpheresParent); + // Create scale cubes + _this._scaleBoxesParent = new _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_4__["AbstractMesh"]("", gizmoLayer.utilityLayerScene); + _this._scaleBoxesParent.rotationQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"](); + for (var i = 0; i < 2; i++) { + for (var j = 0; j < 2; j++) { + var _loop_2 = function () { + var box = _Meshes_Builders_boxBuilder__WEBPACK_IMPORTED_MODULE_7__["BoxBuilder"].CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene); + box.material = this_2.coloredMaterial; + // Dragging logic + var dragAxis = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1); + _dragBehavior = new _Behaviors_Meshes_pointerDragBehavior__WEBPACK_IMPORTED_MODULE_9__["PointerDragBehavior"]({ dragAxis: dragAxis }); + _dragBehavior.moveAttached = false; + box.addBehavior(_dragBehavior); + _dragBehavior.onDragObservable.add(function (event) { + _this.onScaleBoxDragObservable.notifyObservers({}); + if (_this.attachedMesh) { + var originalParent = _this.attachedMesh.parent; + if (originalParent && (originalParent.scaling && originalParent.scaling.isNonUniformWithinEpsilon(0.001))) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_2__["Logger"].Warn("BoundingBoxGizmo controls are not supported on child meshes with non-uniform parent scaling"); + return; + } + _Misc_pivotTools__WEBPACK_IMPORTED_MODULE_13__["PivotTools"]._RemoveAndStorePivotPoint(_this.attachedMesh); + var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length(); + var deltaScale = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](relativeDragDistance, relativeDragDistance, relativeDragDistance); + deltaScale.scaleInPlace(_this._scaleDragSpeed); + _this.updateBoundingBox(); + if (_this.scalePivot) { + _this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix); + // Move anchor to desired pivot point (Bottom left corner + dimension/2) + _this._boundingDimensions.scaleToRef(0.5, _this._tmpVector); + _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector); + _this._anchorMesh.position.subtractInPlace(_this._tmpVector); + _this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector); + _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector); + _this._anchorMesh.position.addInPlace(_this._tmpVector); + } + else { + // Scale from the position of the opposite corner + box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector); + _this._anchorMesh.position.subtractInPlace(_this._tmpVector); + } + _this._anchorMesh.addChild(_this.attachedMesh); + _this._anchorMesh.scaling.addInPlace(deltaScale); + if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) { + _this._anchorMesh.scaling.subtractInPlace(deltaScale); + } + _this._anchorMesh.removeChild(_this.attachedMesh); + _this.attachedMesh.setParent(originalParent); + _Misc_pivotTools__WEBPACK_IMPORTED_MODULE_13__["PivotTools"]._RestorePivotPoint(_this.attachedMesh); + } + _this._updateDummy(); + }); + // Selection/deselection + _dragBehavior.onDragStartObservable.add(function () { + _this.onDragStartObservable.notifyObservers({}); + _this._selectNode(box); + }); + _dragBehavior.onDragEndObservable.add(function () { + _this.onScaleBoxDragEndObservable.notifyObservers({}); + _this._selectNode(null); + _this._updateDummy(); + }); + this_2._scaleBoxesParent.addChild(box); + }; + var this_2 = this, _dragBehavior; + for (var k = 0; k < 2; k++) { + _loop_2(); + } + } + } + _this._rootMesh.addChild(_this._scaleBoxesParent); + // Hover color change + var pointerIds = new Array(); + _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo) { + if (!pointerIds[pointerInfo.event.pointerId]) { + _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) { + if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) { + pointerIds[pointerInfo.event.pointerId] = mesh; + mesh.material = _this.hoverColoredMaterial; + } + }); + } + else { + if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) { + pointerIds[pointerInfo.event.pointerId].material = _this.coloredMaterial; + delete pointerIds[pointerInfo.event.pointerId]; + } + } + }); + // Update bounding box positions + _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () { + // Only update the bouding box if scaling has changed + if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) { + _this.updateBoundingBox(); + } + else if (_this.fixedDragMeshScreenSize) { + _this._updateRotationSpheres(); + _this._updateScaleBoxes(); + } + // If dragg mesh is enabled and dragging, update the attached mesh pose to match the drag mesh + if (_this._dragMesh && _this.attachedMesh && _this.pointerDragBehavior.dragging) { + _this._lineBoundingBox.position.rotateByQuaternionToRef(_this._rootMesh.rotationQuaternion, _this._tmpVector); + _this.attachedMesh.setAbsolutePosition(_this._dragMesh.position.add(_this._tmpVector.scale(-1))); + } + }); + _this.updateBoundingBox(); + return _this; + } + /** + * Sets the color of the bounding box gizmo + * @param color the color to set + */ + BoundingBoxGizmo.prototype.setColor = function (color) { + this.coloredMaterial.emissiveColor = color; + this.hoverColoredMaterial.emissiveColor = color.clone().add(new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Color3"](0.3, 0.3, 0.3)); + this._lineBoundingBox.getChildren().forEach(function (l) { + if (l.color) { + l.color = color; + } + }); + }; + BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) { + var _this = this; + if (value) { + // Reset anchor mesh to match attached mesh's scale + // This is needed to avoid invalid box/sphere position on first drag + _Misc_pivotTools__WEBPACK_IMPORTED_MODULE_13__["PivotTools"]._RemoveAndStorePivotPoint(value); + var originalParent = value.parent; + this._anchorMesh.addChild(value); + this._anchorMesh.removeChild(value); + value.setParent(originalParent); + _Misc_pivotTools__WEBPACK_IMPORTED_MODULE_13__["PivotTools"]._RestorePivotPoint(value); + this.updateBoundingBox(); + value.getChildMeshes(false).forEach(function (m) { + m.markAsDirty("scaling"); + }); + this.gizmoLayer.utilityLayerScene.onAfterRenderObservable.addOnce(function () { + _this._updateDummy(); + }); + } + }; + BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) { + this._rotateSpheresParent.getChildMeshes() + .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m) { + m.isVisible = (!selectedMesh || m == selectedMesh); + }); + }; + /** + * Updates the bounding box information for the Gizmo + */ + BoundingBoxGizmo.prototype.updateBoundingBox = function () { + if (this.attachedMesh) { + _Misc_pivotTools__WEBPACK_IMPORTED_MODULE_13__["PivotTools"]._RemoveAndStorePivotPoint(this.attachedMesh); + // Store original parent + var originalParent = this.attachedMesh.parent; + this.attachedMesh.setParent(null); + // Store original skelton override mesh + var originalSkeletonOverrideMesh = null; + if (this.attachedMesh.skeleton) { + originalSkeletonOverrideMesh = this.attachedMesh.skeleton.overrideMesh; + this.attachedMesh.skeleton.overrideMesh = null; + } + this._update(); + // Rotate based on axis + if (!this.attachedMesh.rotationQuaternion) { + this.attachedMesh.rotationQuaternion = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z); + } + if (!this._anchorMesh.rotationQuaternion) { + this._anchorMesh.rotationQuaternion = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z); + } + this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion); + // Store original position and reset mesh to origin before computing the bounding box + this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion); + this._tmpVector.copyFrom(this.attachedMesh.position); + this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1); + this.attachedMesh.position.set(0, 0, 0); + // Update bounding dimensions/positions + var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate); + boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions); + // Update gizmo to match bounding box scaling and rotation + // The position set here is the offset from the origin for the boundingbox when the attached mesh is at the origin + // The position of the gizmo is then set to the attachedMesh in gizmo._update + this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions); + this._lineBoundingBox.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2); + this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position); + this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position); + this._lineBoundingBox.computeWorldMatrix(); + this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition); + // Restore position/rotation values + this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion); + this.attachedMesh.position.copyFrom(this._tmpVector); + // Restore original parent + this.attachedMesh.setParent(originalParent); + // Restore original skeleton override mesh + if (this.attachedMesh.skeleton) { + this.attachedMesh.skeleton.overrideMesh = originalSkeletonOverrideMesh; + } + } + this._updateRotationSpheres(); + this._updateScaleBoxes(); + if (this.attachedMesh) { + this._existingMeshScale.copyFrom(this.attachedMesh.scaling); + _Misc_pivotTools__WEBPACK_IMPORTED_MODULE_13__["PivotTools"]._RestorePivotPoint(this.attachedMesh); + } + }; + BoundingBoxGizmo.prototype._updateRotationSpheres = function () { + var rotateSpheres = this._rotateSpheresParent.getChildMeshes(); + for (var i = 0; i < 3; i++) { + for (var j = 0; j < 2; j++) { + for (var k = 0; k < 2; k++) { + var index = ((i * 4) + (j * 2)) + k; + if (i == 0) { + rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k); + rotateSpheres[index].position.addInPlace(new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2)); + rotateSpheres[index].lookAt(_Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Cross(rotateSpheres[index].position.normalizeToNew(), _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Right()).normalizeToNew().add(rotateSpheres[index].position)); + } + if (i == 1) { + rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k); + rotateSpheres[index].position.addInPlace(new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2)); + rotateSpheres[index].lookAt(_Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Cross(rotateSpheres[index].position.normalizeToNew(), _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Up()).normalizeToNew().add(rotateSpheres[index].position)); + } + if (i == 2) { + rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2); + rotateSpheres[index].position.addInPlace(new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2)); + rotateSpheres[index].lookAt(_Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Cross(rotateSpheres[index].position.normalizeToNew(), _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Forward()).normalizeToNew().add(rotateSpheres[index].position)); + } + if (this.fixedDragMeshScreenSize && this.gizmoLayer.utilityLayerScene.activeCamera) { + rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector); + var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor; + rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera); + } + else { + rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize); + } + } + } + } + }; + BoundingBoxGizmo.prototype._updateScaleBoxes = function () { + var scaleBoxes = this._scaleBoxesParent.getChildMeshes(); + for (var i = 0; i < 2; i++) { + for (var j = 0; j < 2; j++) { + for (var k = 0; k < 2; k++) { + var index = ((i * 4) + (j * 2)) + k; + if (scaleBoxes[index]) { + scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k); + scaleBoxes[index].position.addInPlace(new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2)); + if (this.fixedDragMeshScreenSize && this.gizmoLayer.utilityLayerScene.activeCamera) { + scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector); + var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor; + scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera); + } + else { + scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize); + } + } + } + } + } + }; + /** + * Enables rotation on the specified axis and disables rotation on the others + * @param axis The list of axis that should be enabled (eg. "xy" or "xyz") + */ + BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) { + this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) { + if (i < 4) { + m.setEnabled(axis.indexOf("x") != -1); + } + else if (i < 8) { + m.setEnabled(axis.indexOf("y") != -1); + } + else { + m.setEnabled(axis.indexOf("z") != -1); + } + }); + }; + /** + * Enables/disables scaling + * @param enable if scaling should be enabled + */ + BoundingBoxGizmo.prototype.setEnabledScaling = function (enable) { + this._scaleBoxesParent.getChildMeshes().forEach(function (m, i) { + m.setEnabled(enable); + }); + }; + BoundingBoxGizmo.prototype._updateDummy = function () { + if (this._dragMesh) { + this._dragMesh.position.copyFrom(this._lineBoundingBox.getAbsolutePosition()); + this._dragMesh.scaling.copyFrom(this._lineBoundingBox.scaling); + this._dragMesh.rotationQuaternion.copyFrom(this._rootMesh.rotationQuaternion); + } + }; + /** + * Enables a pointer drag behavior on the bounding box of the gizmo + */ + BoundingBoxGizmo.prototype.enableDragBehavior = function () { + this._dragMesh = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_5__["Mesh"].CreateBox("dummy", 1, this.gizmoLayer.utilityLayerScene); + this._dragMesh.visibility = 0; + this._dragMesh.rotationQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"](); + this.pointerDragBehavior.useObjectOrienationForDragging = false; + this._dragMesh.addBehavior(this.pointerDragBehavior); + }; + /** + * Disposes of the gizmo + */ + BoundingBoxGizmo.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(); + if (this._dragMesh) { + this._dragMesh.dispose(); + } + _super.prototype.dispose.call(this); + }; + /** + * Makes a mesh not pickable and wraps the mesh inside of a bounding box mesh that is pickable. (This is useful to avoid picking within complex geometry) + * @param mesh the mesh to wrap in the bounding box mesh and make not pickable + * @returns the bounding box mesh with the passed in mesh as a child + */ + BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) { + var makeNotPickable = function (root) { + root.isPickable = false; + root.getChildMeshes().forEach(function (c) { + makeNotPickable(c); + }); + }; + makeNotPickable(mesh); + // Reset position to get boudning box from origin with no rotation + if (!mesh.rotationQuaternion) { + mesh.rotationQuaternion = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z); + } + var oldPos = mesh.position.clone(); + var oldRot = mesh.rotationQuaternion.clone(); + mesh.rotationQuaternion.set(0, 0, 0, 1); + mesh.position.set(0, 0, 0); + // Update bounding dimensions/positions + var box = _Meshes_Builders_boxBuilder__WEBPACK_IMPORTED_MODULE_7__["BoxBuilder"].CreateBox("box", { size: 1 }, mesh.getScene()); + var boundingMinMax = mesh.getHierarchyBoundingVectors(); + boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling); + // Adjust scale to avoid undefined behavior when adding child + if (box.scaling.y === 0) { + box.scaling.y = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Epsilon"]; + } + if (box.scaling.x === 0) { + box.scaling.x = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Epsilon"]; + } + if (box.scaling.z === 0) { + box.scaling.z = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Epsilon"]; + } + box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2); + // Restore original positions + mesh.addChild(box); + mesh.rotationQuaternion.copyFrom(oldRot); + mesh.position.copyFrom(oldPos); + // Reverse parenting + mesh.removeChild(box); + box.addChild(mesh); + box.visibility = 0; + return box; + }; + /** + * CustomMeshes are not supported by this gizmo + * @param mesh The mesh to replace the default mesh of the gizmo + */ + BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_2__["Logger"].Error("Custom meshes are not supported on this gizmo"); + }; + return BoundingBoxGizmo; +}(_gizmo__WEBPACK_IMPORTED_MODULE_10__["Gizmo"])); + + + +/***/ }), + +/***/ "./Gizmos/gizmo.ts": +/*!*************************!*\ + !*** ./Gizmos/gizmo.ts ***! + \*************************/ +/*! exports provided: Gizmo */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Gizmo", function() { return Gizmo; }); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Meshes_mesh__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Meshes/mesh */ "./Meshes/mesh.ts"); +/* harmony import */ var _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Rendering/utilityLayerRenderer */ "./Rendering/utilityLayerRenderer.ts"); + + + +/** + * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc. + */ +var Gizmo = /** @class */ (function () { + /** + * Creates a gizmo + * @param gizmoLayer The utility layer the gizmo will be added to + */ + function Gizmo( + /** The utility layer the gizmo will be added to */ + gizmoLayer) { + var _this = this; + if (gizmoLayer === void 0) { gizmoLayer = _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_2__["UtilityLayerRenderer"].DefaultUtilityLayer; } + this.gizmoLayer = gizmoLayer; + this._attachedMesh = null; + /** + * Ratio for the scale of the gizmo (Default: 1) + */ + this.scaleRatio = 1; + /** + * If a custom mesh has been set (Default: false) + */ + this._customMeshSet = false; + /** + * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true) + */ + this.updateGizmoRotationToMatchAttachedMesh = true; + /** + * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true) + */ + this.updateGizmoPositionToMatchAttachedMesh = true; + /** + * When set, the gizmo will always appear the same size no matter where the camera is (default: false) + */ + this._updateScale = true; + this._interactionsEnabled = true; + this._tempVector = new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"](); + this._rootMesh = new _Meshes_mesh__WEBPACK_IMPORTED_MODULE_1__["Mesh"]("gizmoRootNode", gizmoLayer.utilityLayerScene); + this._rootMesh.rotationQuaternion = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].Identity(); + this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () { + _this._update(); + }); + } + Object.defineProperty(Gizmo.prototype, "attachedMesh", { + /** + * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged) + * * When set, interactions will be enabled + */ + get: function () { + return this._attachedMesh; + }, + set: function (value) { + this._attachedMesh = value; + this._rootMesh.setEnabled(value ? true : false); + this._attachedMeshChanged(value); + }, + enumerable: true, + configurable: true + }); + /** + * Disposes and replaces the current meshes in the gizmo with the specified mesh + * @param mesh The mesh to replace the default mesh of the gizmo + */ + Gizmo.prototype.setCustomMesh = function (mesh) { + if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) { + throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)"; + } + this._rootMesh.getChildMeshes().forEach(function (c) { + c.dispose(); + }); + mesh.parent = this._rootMesh; + this._customMeshSet = true; + }; + Gizmo.prototype._attachedMeshChanged = function (value) { + }; + /** + * Updates the gizmo to match the attached mesh's position/rotation + */ + Gizmo.prototype._update = function () { + if (this.attachedMesh) { + var effectiveMesh = this.attachedMesh._effectiveMesh || this.attachedMesh; + // Position + if (this.updateGizmoPositionToMatchAttachedMesh) { + this._rootMesh.position.copyFrom(effectiveMesh.absolutePosition); + } + // Rotation + if (this.updateGizmoRotationToMatchAttachedMesh) { + effectiveMesh.getWorldMatrix().decompose(undefined, this._rootMesh.rotationQuaternion); + } + else { + this._rootMesh.rotationQuaternion.set(0, 0, 0, 1); + } + // Scale + if (this._updateScale) { + var activeCamera = this.gizmoLayer.utilityLayerScene.activeCamera; + var cameraPosition = activeCamera.globalPosition; + if (activeCamera.devicePosition) { + cameraPosition = activeCamera.devicePosition; + } + this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector); + var dist = this._tempVector.length() * this.scaleRatio; + this._rootMesh.scaling.set(dist, dist, dist); + // Account for handedness, similar to Matrix.decompose + if (effectiveMesh._getWorldMatrixDeterminant() < 0) { + this._rootMesh.scaling.y *= -1; + } + } + } + }; + /** + * Disposes of the gizmo + */ + Gizmo.prototype.dispose = function () { + this._rootMesh.dispose(); + if (this._beforeRenderObserver) { + this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver); + } + }; + return Gizmo; +}()); + + + +/***/ }), + +/***/ "./Gizmos/gizmoManager.ts": +/*!********************************!*\ + !*** ./Gizmos/gizmoManager.ts ***! + \********************************/ +/*! exports provided: GizmoManager */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GizmoManager", function() { return GizmoManager; }); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Events/pointerEvents */ "./Events/pointerEvents.ts"); +/* harmony import */ var _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Meshes/abstractMesh */ "./Meshes/abstractMesh.ts"); +/* harmony import */ var _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Rendering/utilityLayerRenderer */ "./Rendering/utilityLayerRenderer.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Behaviors_Meshes_sixDofDragBehavior__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Behaviors/Meshes/sixDofDragBehavior */ "./Behaviors/Meshes/sixDofDragBehavior.ts"); +/* harmony import */ var _rotationGizmo__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./rotationGizmo */ "./Gizmos/rotationGizmo.ts"); +/* harmony import */ var _positionGizmo__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./positionGizmo */ "./Gizmos/positionGizmo.ts"); +/* harmony import */ var _scaleGizmo__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./scaleGizmo */ "./Gizmos/scaleGizmo.ts"); +/* harmony import */ var _boundingBoxGizmo__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./boundingBoxGizmo */ "./Gizmos/boundingBoxGizmo.ts"); + + + + + + + + + + +/** + * Helps setup gizmo's in the scene to rotate/scale/position meshes + */ +var GizmoManager = /** @class */ (function () { + /** + * Instatiates a gizmo manager + * @param scene the scene to overlay the gizmos on top of + */ + function GizmoManager(scene) { + var _this = this; + this.scene = scene; + /** When true, the gizmo will be detached from the current object when a pointer down occurs with an empty picked mesh */ + this.clearGizmoOnEmptyPointerEvent = false; + /** Fires an event when the manager is attached to a mesh */ + this.onAttachedToMeshObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](); + this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false }; + this._pointerObserver = null; + this._attachedMesh = null; + this._boundingBoxColor = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Color3"].FromHexString("#0984e3"); + /** + * When bounding box gizmo is enabled, this can be used to track drag/end events + */ + this.boundingBoxDragBehavior = new _Behaviors_Meshes_sixDofDragBehavior__WEBPACK_IMPORTED_MODULE_5__["SixDofDragBehavior"](); + /** + * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null) + */ + this.attachableMeshes = null; + /** + * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true) + */ + this.usePointerToAttachGizmos = true; + this._defaultKeepDepthUtilityLayer = new _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_3__["UtilityLayerRenderer"](scene); + this._defaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false; + this._defaultUtilityLayer = _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_3__["UtilityLayerRenderer"].DefaultUtilityLayer; + this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null }; + // Instatiate/dispose gizmos based on pointer actions + this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo) { + if (!_this.usePointerToAttachGizmos) { + return; + } + if (pointerInfo.type == _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_1__["PointerEventTypes"].POINTERDOWN) { + if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) { + var node = pointerInfo.pickInfo.pickedMesh; + if (_this.attachableMeshes == null) { + // Attach to the most parent node + while (node && node.parent != null) { + node = node.parent; + } + } + else { + // Attach to the parent node that is an attachableMesh + var found = false; + _this.attachableMeshes.forEach(function (mesh) { + if (node && (node == mesh || node.isDescendantOf(mesh))) { + node = mesh; + found = true; + } + }); + if (!found) { + node = null; + } + } + if (node instanceof _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_2__["AbstractMesh"]) { + if (_this._attachedMesh != node) { + _this.attachToMesh(node); + } + } + else { + if (_this.clearGizmoOnEmptyPointerEvent) { + _this.attachToMesh(null); + } + } + } + else { + if (_this.clearGizmoOnEmptyPointerEvent) { + _this.attachToMesh(null); + } + } + } + }); + } + Object.defineProperty(GizmoManager.prototype, "keepDepthUtilityLayer", { + /** + * Utility layer that the bounding box gizmo belongs to + */ + get: function () { + return this._defaultKeepDepthUtilityLayer; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(GizmoManager.prototype, "utilityLayer", { + /** + * Utility layer that all gizmos besides bounding box belong to + */ + get: function () { + return this._defaultUtilityLayer; + }, + enumerable: true, + configurable: true + }); + /** + * Attaches a set of gizmos to the specified mesh + * @param mesh The mesh the gizmo's should be attached to + */ + GizmoManager.prototype.attachToMesh = function (mesh) { + if (this._attachedMesh) { + this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior); + } + this._attachedMesh = mesh; + for (var key in this.gizmos) { + var gizmo = (this.gizmos[key]); + if (gizmo && this._gizmosEnabled[key]) { + gizmo.attachedMesh = mesh; + } + } + if (this.boundingBoxGizmoEnabled && this._attachedMesh) { + this._attachedMesh.addBehavior(this.boundingBoxDragBehavior); + } + this.onAttachedToMeshObservable.notifyObservers(mesh); + }; + Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", { + get: function () { + return this._gizmosEnabled.positionGizmo; + }, + /** + * If the position gizmo is enabled + */ + set: function (value) { + if (value) { + if (!this.gizmos.positionGizmo) { + this.gizmos.positionGizmo = new _positionGizmo__WEBPACK_IMPORTED_MODULE_7__["PositionGizmo"](this._defaultUtilityLayer); + } + this.gizmos.positionGizmo.attachedMesh = this._attachedMesh; + } + else if (this.gizmos.positionGizmo) { + this.gizmos.positionGizmo.attachedMesh = null; + } + this._gizmosEnabled.positionGizmo = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", { + get: function () { + return this._gizmosEnabled.rotationGizmo; + }, + /** + * If the rotation gizmo is enabled + */ + set: function (value) { + if (value) { + if (!this.gizmos.rotationGizmo) { + this.gizmos.rotationGizmo = new _rotationGizmo__WEBPACK_IMPORTED_MODULE_6__["RotationGizmo"](this._defaultUtilityLayer); + } + this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh; + } + else if (this.gizmos.rotationGizmo) { + this.gizmos.rotationGizmo.attachedMesh = null; + } + this._gizmosEnabled.rotationGizmo = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", { + get: function () { + return this._gizmosEnabled.scaleGizmo; + }, + /** + * If the scale gizmo is enabled + */ + set: function (value) { + if (value) { + this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new _scaleGizmo__WEBPACK_IMPORTED_MODULE_8__["ScaleGizmo"](this._defaultUtilityLayer); + this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh; + } + else if (this.gizmos.scaleGizmo) { + this.gizmos.scaleGizmo.attachedMesh = null; + } + this._gizmosEnabled.scaleGizmo = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", { + get: function () { + return this._gizmosEnabled.boundingBoxGizmo; + }, + /** + * If the boundingBox gizmo is enabled + */ + set: function (value) { + if (value) { + this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new _boundingBoxGizmo__WEBPACK_IMPORTED_MODULE_9__["BoundingBoxGizmo"](this._boundingBoxColor, this._defaultKeepDepthUtilityLayer); + this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh; + if (this._attachedMesh) { + this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior); + this._attachedMesh.addBehavior(this.boundingBoxDragBehavior); + } + } + else if (this.gizmos.boundingBoxGizmo) { + if (this._attachedMesh) { + this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior); + } + this.gizmos.boundingBoxGizmo.attachedMesh = null; + } + this._gizmosEnabled.boundingBoxGizmo = value; + }, + enumerable: true, + configurable: true + }); + /** + * Disposes of the gizmo manager + */ + GizmoManager.prototype.dispose = function () { + this.scene.onPointerObservable.remove(this._pointerObserver); + for (var key in this.gizmos) { + var gizmo = (this.gizmos[key]); + if (gizmo) { + gizmo.dispose(); + } + } + this._defaultKeepDepthUtilityLayer.dispose(); + this.boundingBoxDragBehavior.detach(); + this.onAttachedToMeshObservable.clear(); + }; + return GizmoManager; +}()); + + + +/***/ }), + +/***/ "./Gizmos/index.ts": +/*!*************************!*\ + !*** ./Gizmos/index.ts ***! + \*************************/ +/*! exports provided: AxisDragGizmo, AxisScaleGizmo, BoundingBoxGizmo, Gizmo, GizmoManager, PlaneRotationGizmo, PositionGizmo, RotationGizmo, ScaleGizmo, LightGizmo */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _axisDragGizmo__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./axisDragGizmo */ "./Gizmos/axisDragGizmo.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AxisDragGizmo", function() { return _axisDragGizmo__WEBPACK_IMPORTED_MODULE_0__["AxisDragGizmo"]; }); + +/* harmony import */ var _axisScaleGizmo__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./axisScaleGizmo */ "./Gizmos/axisScaleGizmo.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AxisScaleGizmo", function() { return _axisScaleGizmo__WEBPACK_IMPORTED_MODULE_1__["AxisScaleGizmo"]; }); + +/* harmony import */ var _boundingBoxGizmo__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./boundingBoxGizmo */ "./Gizmos/boundingBoxGizmo.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoundingBoxGizmo", function() { return _boundingBoxGizmo__WEBPACK_IMPORTED_MODULE_2__["BoundingBoxGizmo"]; }); + +/* harmony import */ var _gizmo__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./gizmo */ "./Gizmos/gizmo.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Gizmo", function() { return _gizmo__WEBPACK_IMPORTED_MODULE_3__["Gizmo"]; }); + +/* harmony import */ var _gizmoManager__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./gizmoManager */ "./Gizmos/gizmoManager.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GizmoManager", function() { return _gizmoManager__WEBPACK_IMPORTED_MODULE_4__["GizmoManager"]; }); + +/* harmony import */ var _planeRotationGizmo__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./planeRotationGizmo */ "./Gizmos/planeRotationGizmo.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PlaneRotationGizmo", function() { return _planeRotationGizmo__WEBPACK_IMPORTED_MODULE_5__["PlaneRotationGizmo"]; }); + +/* harmony import */ var _positionGizmo__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./positionGizmo */ "./Gizmos/positionGizmo.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PositionGizmo", function() { return _positionGizmo__WEBPACK_IMPORTED_MODULE_6__["PositionGizmo"]; }); + +/* harmony import */ var _rotationGizmo__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./rotationGizmo */ "./Gizmos/rotationGizmo.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RotationGizmo", function() { return _rotationGizmo__WEBPACK_IMPORTED_MODULE_7__["RotationGizmo"]; }); + +/* harmony import */ var _scaleGizmo__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./scaleGizmo */ "./Gizmos/scaleGizmo.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ScaleGizmo", function() { return _scaleGizmo__WEBPACK_IMPORTED_MODULE_8__["ScaleGizmo"]; }); + +/* harmony import */ var _lightGizmo__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./lightGizmo */ "./Gizmos/lightGizmo.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LightGizmo", function() { return _lightGizmo__WEBPACK_IMPORTED_MODULE_9__["LightGizmo"]; }); + + + + + + + + + + + + + +/***/ }), + +/***/ "./Gizmos/lightGizmo.ts": +/*!******************************!*\ + !*** ./Gizmos/lightGizmo.ts ***! + \******************************/ +/*! exports provided: LightGizmo */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LightGizmo", function() { return LightGizmo; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Meshes/abstractMesh */ "./Meshes/abstractMesh.ts"); +/* harmony import */ var _Meshes_mesh__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Meshes/mesh */ "./Meshes/mesh.ts"); +/* harmony import */ var _gizmo__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./gizmo */ "./Gizmos/gizmo.ts"); +/* harmony import */ var _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Materials/standardMaterial */ "./Materials/standardMaterial.ts"); +/* harmony import */ var _Lights_hemisphericLight__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Lights/hemisphericLight */ "./Lights/hemisphericLight.ts"); +/* harmony import */ var _Lights_directionalLight__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Lights/directionalLight */ "./Lights/directionalLight.ts"); +/* harmony import */ var _Meshes_Builders_sphereBuilder__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Meshes/Builders/sphereBuilder */ "./Meshes/Builders/sphereBuilder.ts"); +/* harmony import */ var _Meshes_Builders_hemisphereBuilder__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Meshes/Builders/hemisphereBuilder */ "./Meshes/Builders/hemisphereBuilder.ts"); +/* harmony import */ var _Lights_spotLight__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../Lights/spotLight */ "./Lights/spotLight.ts"); + + + + + + + + + + + +/** + * Gizmo that enables viewing a light + */ +var LightGizmo = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](LightGizmo, _super); + /** + * Creates a LightGizmo + * @param gizmoLayer The utility layer the gizmo will be added to + */ + function LightGizmo(gizmoLayer) { + var _this = _super.call(this, gizmoLayer) || this; + _this.cachedPosition = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"](); + _this.cachedForward = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"](0, 0, 1); + _this._light = null; + _this.attachedMesh = new _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_2__["AbstractMesh"]("", _this.gizmoLayer.utilityLayerScene); + _this._material = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_5__["StandardMaterial"]("light", _this.gizmoLayer.originalScene); + _this._material.diffuseColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Color3"](0.5, 0.5, 0.5); + _this._material.specularColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Color3"](0.1, 0.1, 0.1); + return _this; + } + Object.defineProperty(LightGizmo.prototype, "light", { + get: function () { + return this._light; + }, + /** + * The light that the gizmo is attached to + */ + set: function (light) { + var _this = this; + this._light = light; + if (light) { + // Create the mesh for the given light type + if (this._lightMesh) { + this._lightMesh.dispose(); + } + if (light instanceof _Lights_hemisphericLight__WEBPACK_IMPORTED_MODULE_6__["HemisphericLight"]) { + this._lightMesh = LightGizmo._CreateHemisphericLightMesh(this.gizmoLayer.utilityLayerScene); + } + else if (light instanceof _Lights_directionalLight__WEBPACK_IMPORTED_MODULE_7__["DirectionalLight"]) { + this._lightMesh = LightGizmo._CreateDirectionalLightMesh(this.gizmoLayer.utilityLayerScene); + } + else if (light instanceof _Lights_spotLight__WEBPACK_IMPORTED_MODULE_10__["SpotLight"]) { + this._lightMesh = LightGizmo._CreateSpotLightMesh(this.gizmoLayer.utilityLayerScene); + } + else { + this._lightMesh = LightGizmo._CreatePointLightMesh(this.gizmoLayer.utilityLayerScene); + } + this._lightMesh.getChildMeshes(false).forEach(function (m) { + m.material = _this._material; + }); + this._lightMesh.parent = this._rootMesh; + // Add lighting to the light gizmo + var gizmoLight = this.gizmoLayer._getSharedGizmoLight(); + gizmoLight.includedOnlyMeshes = gizmoLight.includedOnlyMeshes.concat(this._lightMesh.getChildMeshes(false)); + this._lightMesh.rotationQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Quaternion"](); + if (!this.attachedMesh.reservedDataStore) { + this.attachedMesh.reservedDataStore = {}; + } + this.attachedMesh.reservedDataStore.lightGizmo = this; + // Get update position and direction if the light has it + if (light.position) { + this.attachedMesh.position.copyFrom(light.position); + } + if (light.direction) { + this.attachedMesh.setDirection(light.direction); + } + this._update(); + } + }, + enumerable: true, + configurable: true + }); + /** + * @hidden + * Updates the gizmo to match the attached mesh's position/rotation + */ + LightGizmo.prototype._update = function () { + _super.prototype._update.call(this); + if (!this._light) { + return; + } + if (this._light.position) { + // If the gizmo is moved update the light otherwise update the gizmo to match the light + if (!this.attachedMesh.position.equals(this.cachedPosition)) { + // update light to match gizmo + this._light.position.copyFrom(this.attachedMesh.position); + this.cachedPosition.copyFrom(this.attachedMesh.position); + } + else { + // update gizmo to match light + this.attachedMesh.position.copyFrom(this._light.position); + } + } + if (this._light.direction) { + // If the gizmo is moved update the light otherwise update the gizmo to match the light + if (_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].DistanceSquared(this.attachedMesh.forward, this.cachedForward) > 0.0001) { + // update light to match gizmo + this._light.direction.copyFrom(this.attachedMesh.forward); + this.cachedForward.copyFrom(this.attachedMesh.forward); + } + else if (_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].DistanceSquared(this.attachedMesh.forward, this._light.direction) > 0.0001) { + // update gizmo to match light + this.attachedMesh.setDirection(this._light.direction); + this.cachedForward.copyFrom(this._lightMesh.forward); + } + } + if (!this._light.isEnabled()) { + this._material.diffuseColor.set(0, 0, 0); + } + else { + this._material.diffuseColor.set(this._light.diffuse.r / 3, this._light.diffuse.g / 3, this._light.diffuse.b / 3); + } + }; + /** + * Disposes of the light gizmo + */ + LightGizmo.prototype.dispose = function () { + this._material.dispose(); + _super.prototype.dispose.call(this); + }; + LightGizmo._CreateHemisphericLightMesh = function (scene) { + var root = new _Meshes_mesh__WEBPACK_IMPORTED_MODULE_3__["Mesh"]("hemisphereLight", scene); + var hemisphere = _Meshes_Builders_hemisphereBuilder__WEBPACK_IMPORTED_MODULE_9__["HemisphereBuilder"].CreateHemisphere(root.name, { segments: 10, diameter: 1 }, scene); + hemisphere.position.z = -0.15; + hemisphere.rotation.x = Math.PI / 2; + hemisphere.parent = root; + var lines = this._createLightLines(3, scene); + lines.parent = root; + lines.position.z - 0.15; + root.scaling.scaleInPlace(LightGizmo._Scale); + root.rotation.x = Math.PI / 2; + return root; + }; + LightGizmo._CreatePointLightMesh = function (scene) { + var root = new _Meshes_mesh__WEBPACK_IMPORTED_MODULE_3__["Mesh"]("pointLight", scene); + var sphere = _Meshes_Builders_sphereBuilder__WEBPACK_IMPORTED_MODULE_8__["SphereBuilder"].CreateSphere(root.name, { segments: 10, diameter: 1 }, scene); + sphere.rotation.x = Math.PI / 2; + sphere.parent = root; + var lines = this._createLightLines(5, scene); + lines.parent = root; + root.scaling.scaleInPlace(LightGizmo._Scale); + root.rotation.x = Math.PI / 2; + return root; + }; + LightGizmo._CreateSpotLightMesh = function (scene) { + var root = new _Meshes_mesh__WEBPACK_IMPORTED_MODULE_3__["Mesh"]("spotLight", scene); + var sphere = _Meshes_Builders_sphereBuilder__WEBPACK_IMPORTED_MODULE_8__["SphereBuilder"].CreateSphere(root.name, { segments: 10, diameter: 1 }, scene); + sphere.parent = root; + var hemisphere = _Meshes_Builders_hemisphereBuilder__WEBPACK_IMPORTED_MODULE_9__["HemisphereBuilder"].CreateHemisphere(root.name, { segments: 10, diameter: 2 }, scene); + hemisphere.parent = root; + hemisphere.rotation.x = -Math.PI / 2; + var lines = this._createLightLines(2, scene); + lines.parent = root; + root.scaling.scaleInPlace(LightGizmo._Scale); + root.rotation.x = Math.PI / 2; + return root; + }; + LightGizmo._CreateDirectionalLightMesh = function (scene) { + var root = new _Meshes_mesh__WEBPACK_IMPORTED_MODULE_3__["Mesh"]("directionalLight", scene); + var mesh = new _Meshes_mesh__WEBPACK_IMPORTED_MODULE_3__["Mesh"](root.name, scene); + mesh.parent = root; + var sphere = _Meshes_Builders_sphereBuilder__WEBPACK_IMPORTED_MODULE_8__["SphereBuilder"].CreateSphere(root.name, { diameter: 1.2, segments: 10 }, scene); + sphere.parent = mesh; + var line = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_3__["Mesh"].CreateCylinder(root.name, 6, 0.3, 0.3, 6, 1, scene); + line.parent = mesh; + var left = line.clone(root.name); + left.scaling.y = 0.5; + left.position.x += 1.25; + var right = line.clone(root.name); + right.scaling.y = 0.5; + right.position.x += -1.25; + var arrowHead = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_3__["Mesh"].CreateCylinder(root.name, 1, 0, 0.6, 6, 1, scene); + arrowHead.position.y += 3; + arrowHead.parent = mesh; + var left = arrowHead.clone(root.name); + left.position.y = 1.5; + left.position.x += 1.25; + var right = arrowHead.clone(root.name); + right.position.y = 1.5; + right.position.x += -1.25; + mesh.scaling.scaleInPlace(LightGizmo._Scale); + mesh.rotation.z = Math.PI / 2; + mesh.rotation.y = Math.PI / 2; + return root; + }; + // Static helper methods + LightGizmo._Scale = 0.007; + /** + * Creates the lines for a light mesh + */ + LightGizmo._createLightLines = function (levels, scene) { + var distFromSphere = 1.2; + var root = new _Meshes_mesh__WEBPACK_IMPORTED_MODULE_3__["Mesh"]("root", scene); + root.rotation.x = Math.PI / 2; + // Create the top line, this will be cloned for all other lines + var linePivot = new _Meshes_mesh__WEBPACK_IMPORTED_MODULE_3__["Mesh"]("linePivot", scene); + linePivot.parent = root; + var line = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_3__["Mesh"].CreateCylinder("line", 2, 0.2, 0.3, 6, 1, scene); + line.position.y = line.scaling.y / 2 + distFromSphere; + line.parent = linePivot; + if (levels < 2) { + return linePivot; + } + for (var i = 0; i < 4; i++) { + var l = linePivot.clone("lineParentClone"); + l.rotation.z = Math.PI / 4; + l.rotation.y = (Math.PI / 2) + (Math.PI / 2 * i); + l.getChildMeshes()[0].scaling.y = 0.5; + l.getChildMeshes()[0].scaling.x = l.getChildMeshes()[0].scaling.z = 0.8; + l.getChildMeshes()[0].position.y = l.getChildMeshes()[0].scaling.y / 2 + distFromSphere; + } + if (levels < 3) { + return root; + } + for (var i = 0; i < 4; i++) { + var l = linePivot.clone("linePivotClone"); + l.rotation.z = Math.PI / 2; + l.rotation.y = (Math.PI / 2 * i); + } + if (levels < 4) { + return root; + } + for (var i = 0; i < 4; i++) { + var l = linePivot.clone("linePivotClone"); + l.rotation.z = Math.PI + (Math.PI / 4); + l.rotation.y = (Math.PI / 2) + (Math.PI / 2 * i); + l.getChildMeshes()[0].scaling.y = 0.5; + l.getChildMeshes()[0].scaling.x = l.getChildMeshes()[0].scaling.z = 0.8; + l.getChildMeshes()[0].position.y = l.getChildMeshes()[0].scaling.y / 2 + distFromSphere; + } + if (levels < 5) { + return root; + } + var l = linePivot.clone("linePivotClone"); + l.rotation.z = Math.PI; + return root; + }; + return LightGizmo; +}(_gizmo__WEBPACK_IMPORTED_MODULE_4__["Gizmo"])); + + + +/***/ }), + +/***/ "./Gizmos/planeDragGizmo.ts": +/*!**********************************!*\ + !*** ./Gizmos/planeDragGizmo.ts ***! + \**********************************/ +/*! exports provided: PlaneDragGizmo */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PlaneDragGizmo", function() { return PlaneDragGizmo; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Meshes_transformNode__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Meshes/transformNode */ "./Meshes/transformNode.ts"); +/* harmony import */ var _Meshes_Builders_planeBuilder__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Meshes/Builders/planeBuilder */ "./Meshes/Builders/planeBuilder.ts"); +/* harmony import */ var _Behaviors_Meshes_pointerDragBehavior__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Behaviors/Meshes/pointerDragBehavior */ "./Behaviors/Meshes/pointerDragBehavior.ts"); +/* harmony import */ var _gizmo__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./gizmo */ "./Gizmos/gizmo.ts"); +/* harmony import */ var _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Rendering/utilityLayerRenderer */ "./Rendering/utilityLayerRenderer.ts"); +/* harmony import */ var _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Materials/standardMaterial */ "./Materials/standardMaterial.ts"); + + + + + + + + + +/** + * Single plane drag gizmo + */ +var PlaneDragGizmo = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PlaneDragGizmo, _super); + /** + * Creates a PlaneDragGizmo + * @param gizmoLayer The utility layer the gizmo will be added to + * @param dragPlaneNormal The axis normal to which the gizmo will be able to drag on + * @param color The color of the gizmo + */ + function PlaneDragGizmo(dragPlaneNormal, color, gizmoLayer, parent) { + if (color === void 0) { color = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color3"].Gray(); } + if (gizmoLayer === void 0) { gizmoLayer = _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_7__["UtilityLayerRenderer"].DefaultUtilityLayer; } + if (parent === void 0) { parent = null; } + var _this = _super.call(this, gizmoLayer) || this; + _this._pointerObserver = null; + /** + * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0) + */ + _this.snapDistance = 0; + /** + * Event that fires each time the gizmo snaps to a new location. + * * snapDistance is the the change in distance + */ + _this.onSnapObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + _this._isEnabled = false; + _this._parent = null; + _this._parent = parent; + // Create Material + _this._coloredMaterial = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_8__["StandardMaterial"]("", gizmoLayer.utilityLayerScene); + _this._coloredMaterial.diffuseColor = color; + _this._coloredMaterial.specularColor = color.subtract(new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color3"](0.1, 0.1, 0.1)); + _this._hoverMaterial = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_8__["StandardMaterial"]("", gizmoLayer.utilityLayerScene); + _this._hoverMaterial.diffuseColor = color.add(new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color3"](0.3, 0.3, 0.3)); + // Build plane mesh on root node + _this._plane = PlaneDragGizmo._CreatePlane(gizmoLayer.utilityLayerScene, _this._coloredMaterial); + _this._plane.lookAt(_this._rootMesh.position.add(dragPlaneNormal)); + _this._plane.scaling.scaleInPlace(1 / 3); + _this._plane.parent = _this._rootMesh; + var currentSnapDragDistance = 0; + var tmpVector = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](); + var tmpSnapEvent = { snapDistance: 0 }; + // Add dragPlaneNormal drag behavior to handle events when the gizmo is dragged + _this.dragBehavior = new _Behaviors_Meshes_pointerDragBehavior__WEBPACK_IMPORTED_MODULE_5__["PointerDragBehavior"]({ dragPlaneNormal: dragPlaneNormal }); + _this.dragBehavior.moveAttached = false; + _this._rootMesh.addBehavior(_this.dragBehavior); + var localDelta = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](); + var tmpMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"](); + _this.dragBehavior.onDragObservable.add(function (event) { + if (_this.attachedMesh) { + // Convert delta to local translation if it has a parent + if (_this.attachedMesh.parent) { + _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix); + tmpMatrix.setTranslationFromFloats(0, 0, 0); + _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta); + } + else { + localDelta.copyFrom(event.delta); + } + // Snapping logic + if (_this.snapDistance == 0) { + _this.attachedMesh.position.addInPlace(localDelta); + } + else { + currentSnapDragDistance += event.dragDistance; + if (Math.abs(currentSnapDragDistance) > _this.snapDistance) { + var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance); + currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance; + localDelta.normalizeToRef(tmpVector); + tmpVector.scaleInPlace(_this.snapDistance * dragSteps); + _this.attachedMesh.position.addInPlace(tmpVector); + tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps; + _this.onSnapObservable.notifyObservers(tmpSnapEvent); + } + } + } + }); + _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo) { + if (_this._customMeshSet) { + return; + } + var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1); + var material = isHovered ? _this._hoverMaterial : _this._coloredMaterial; + _this._rootMesh.getChildMeshes().forEach(function (m) { + m.material = material; + }); + }); + var light = gizmoLayer._getSharedGizmoLight(); + light.includedOnlyMeshes = light.includedOnlyMeshes.concat(_this._rootMesh.getChildMeshes(false)); + return _this; + } + /** @hidden */ + PlaneDragGizmo._CreatePlane = function (scene, material) { + var plane = new _Meshes_transformNode__WEBPACK_IMPORTED_MODULE_3__["TransformNode"]("plane", scene); + //make sure plane is double sided + var dragPlane = _Meshes_Builders_planeBuilder__WEBPACK_IMPORTED_MODULE_4__["PlaneBuilder"].CreatePlane("dragPlane", { width: .1375, height: .1375, sideOrientation: 2 }, scene); + dragPlane.material = material; + dragPlane.parent = plane; + // Position plane pointing normal to dragPlane normal + dragPlane.material = material; + return plane; + }; + /** @hidden */ + PlaneDragGizmo._CreateArrowInstance = function (scene, arrow) { + var instance = new _Meshes_transformNode__WEBPACK_IMPORTED_MODULE_3__["TransformNode"]("arrow", scene); + for (var _i = 0, _a = arrow.getChildMeshes(); _i < _a.length; _i++) { + var mesh = _a[_i]; + var childInstance = mesh.createInstance(mesh.name); + childInstance.parent = instance; + } + return instance; + }; + PlaneDragGizmo.prototype._attachedMeshChanged = function (value) { + if (this.dragBehavior) { + this.dragBehavior.enabled = value ? true : false; + } + }; + Object.defineProperty(PlaneDragGizmo.prototype, "isEnabled", { + get: function () { + return this._isEnabled; + }, + /** + * If the gizmo is enabled + */ + set: function (value) { + this._isEnabled = value; + if (!value) { + this.attachedMesh = null; + } + else { + if (this._parent) { + this.attachedMesh = this._parent.attachedMesh; + } + } + }, + enumerable: true, + configurable: true + }); + /** + * Disposes of the gizmo + */ + PlaneDragGizmo.prototype.dispose = function () { + this.onSnapObservable.clear(); + this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver); + this.dragBehavior.detach(); + _super.prototype.dispose.call(this); + if (this._plane) { + this._plane.dispose(); + } + [this._coloredMaterial, this._hoverMaterial].forEach(function (matl) { + if (matl) { + matl.dispose(); + } + }); + }; + return PlaneDragGizmo; +}(_gizmo__WEBPACK_IMPORTED_MODULE_6__["Gizmo"])); + + + +/***/ }), + +/***/ "./Gizmos/planeRotationGizmo.ts": +/*!**************************************!*\ + !*** ./Gizmos/planeRotationGizmo.ts ***! + \**************************************/ +/*! exports provided: PlaneRotationGizmo */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PlaneRotationGizmo", function() { return PlaneRotationGizmo; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Meshes/abstractMesh */ "./Meshes/abstractMesh.ts"); +/* harmony import */ var _Meshes_mesh__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Meshes/mesh */ "./Meshes/mesh.ts"); +/* harmony import */ var _Behaviors_Meshes_pointerDragBehavior__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Behaviors/Meshes/pointerDragBehavior */ "./Behaviors/Meshes/pointerDragBehavior.ts"); +/* harmony import */ var _gizmo__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./gizmo */ "./Gizmos/gizmo.ts"); +/* harmony import */ var _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Rendering/utilityLayerRenderer */ "./Rendering/utilityLayerRenderer.ts"); +/* harmony import */ var _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Materials/standardMaterial */ "./Materials/standardMaterial.ts"); +/* harmony import */ var _Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Meshes/Builders/linesBuilder */ "./Meshes/Builders/linesBuilder.ts"); + + + + + + + + + + +/** + * Single plane rotation gizmo + */ +var PlaneRotationGizmo = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PlaneRotationGizmo, _super); + /** + * Creates a PlaneRotationGizmo + * @param gizmoLayer The utility layer the gizmo will be added to + * @param planeNormal The normal of the plane which the gizmo will be able to rotate on + * @param color The color of the gizmo + * @param tessellation Amount of tessellation to be used when creating rotation circles + */ + function PlaneRotationGizmo(planeNormal, color, gizmoLayer, tessellation, parent) { + if (color === void 0) { color = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color3"].Gray(); } + if (gizmoLayer === void 0) { gizmoLayer = _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_7__["UtilityLayerRenderer"].DefaultUtilityLayer; } + if (tessellation === void 0) { tessellation = 32; } + if (parent === void 0) { parent = null; } + var _this = _super.call(this, gizmoLayer) || this; + _this._pointerObserver = null; + /** + * Rotation distance in radians that the gizmo will snap to (Default: 0) + */ + _this.snapDistance = 0; + /** + * Event that fires each time the gizmo snaps to a new location. + * * snapDistance is the the change in distance + */ + _this.onSnapObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + _this._isEnabled = true; + _this._parent = null; + _this._parent = parent; + // Create Material + var coloredMaterial = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_8__["StandardMaterial"]("", gizmoLayer.utilityLayerScene); + coloredMaterial.diffuseColor = color; + coloredMaterial.specularColor = color.subtract(new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color3"](0.1, 0.1, 0.1)); + var hoverMaterial = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_8__["StandardMaterial"]("", gizmoLayer.utilityLayerScene); + hoverMaterial.diffuseColor = color.add(new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color3"](0.3, 0.3, 0.3)); + // Build mesh on root node + var parentMesh = new _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_3__["AbstractMesh"]("", gizmoLayer.utilityLayerScene); + var drag = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_4__["Mesh"].CreateTorus("", 0.6, 0.03, tessellation, gizmoLayer.utilityLayerScene); + drag.visibility = 0; + var rotationMesh = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_4__["Mesh"].CreateTorus("", 0.6, 0.005, tessellation, gizmoLayer.utilityLayerScene); + rotationMesh.material = coloredMaterial; + // Position arrow pointing in its drag axis + rotationMesh.rotation.x = Math.PI / 2; + drag.rotation.x = Math.PI / 2; + parentMesh.addChild(rotationMesh); + parentMesh.addChild(drag); + parentMesh.lookAt(_this._rootMesh.position.add(planeNormal)); + _this._rootMesh.addChild(parentMesh); + parentMesh.scaling.scaleInPlace(1 / 3); + // Add drag behavior to handle events when the gizmo is dragged + _this.dragBehavior = new _Behaviors_Meshes_pointerDragBehavior__WEBPACK_IMPORTED_MODULE_5__["PointerDragBehavior"]({ dragPlaneNormal: planeNormal }); + _this.dragBehavior.moveAttached = false; + _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20; + _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true; + _this._rootMesh.addBehavior(_this.dragBehavior); + var lastDragPosition = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](); + _this.dragBehavior.onDragStartObservable.add(function (e) { + if (_this.attachedMesh) { + lastDragPosition.copyFrom(e.dragPlanePoint); + } + }); + var rotationMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"](); + var planeNormalTowardsCamera = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](); + var localPlaneNormalTowardsCamera = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](); + var tmpSnapEvent = { snapDistance: 0 }; + var currentSnapDragDistance = 0; + var tmpMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"](); + var tmpVector = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](); + var amountToRotate = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Quaternion"](); + _this.dragBehavior.onDragObservable.add(function (event) { + if (_this.attachedMesh) { + if (!_this.attachedMesh.rotationQuaternion) { + _this.attachedMesh.rotationQuaternion = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Quaternion"].RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z); + } + // Remove parent priort to rotating + var attachedMeshParent = _this.attachedMesh.parent; + if (attachedMeshParent) { + _this.attachedMesh.setParent(null); + } + // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360) + var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize(); + var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize(); + var cross = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Cross(newVector, originalVector); + var dot = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Dot(newVector, originalVector); + var angle = Math.atan2(cross.length(), dot); + planeNormalTowardsCamera.copyFrom(planeNormal); + localPlaneNormalTowardsCamera.copyFrom(planeNormal); + if (_this.updateGizmoRotationToMatchAttachedMesh) { + _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix); + localPlaneNormalTowardsCamera = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].TransformCoordinates(planeNormalTowardsCamera, rotationMatrix); + } + // Flip up vector depending on which side the camera is on + if (gizmoLayer.utilityLayerScene.activeCamera) { + var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position); + if (_Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Dot(camVec, localPlaneNormalTowardsCamera) > 0) { + planeNormalTowardsCamera.scaleInPlace(-1); + localPlaneNormalTowardsCamera.scaleInPlace(-1); + } + } + var halfCircleSide = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Dot(localPlaneNormalTowardsCamera, cross) > 0.0; + if (halfCircleSide) { + angle = -angle; + } + // Snapping logic + var snapped = false; + if (_this.snapDistance != 0) { + currentSnapDragDistance += angle; + if (Math.abs(currentSnapDragDistance) > _this.snapDistance) { + var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance); + if (currentSnapDragDistance < 0) { + dragSteps *= -1; + } + currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance; + angle = _this.snapDistance * dragSteps; + snapped = true; + } + else { + angle = 0; + } + } + // If the mesh has a parent, convert needed world rotation to local rotation + tmpMatrix.reset(); + if (_this.attachedMesh.parent) { + _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix); + tmpMatrix.getRotationMatrixToRef(tmpMatrix); + _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera); + } + // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm) + var quaternionCoefficient = Math.sin(angle / 2); + amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2)); + // If the meshes local scale is inverted (eg. loaded gltf file parent with z scale of -1) the rotation needs to be inverted on the y axis + if (tmpMatrix.determinant() > 0) { + amountToRotate.toEulerAnglesToRef(tmpVector); + _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Quaternion"].RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate); + } + if (_this.updateGizmoRotationToMatchAttachedMesh) { + // Rotate selected mesh quaternion over fixed axis + _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion); + } + else { + // Rotate selected mesh quaternion over rotated axis + amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion); + } + lastDragPosition.copyFrom(event.dragPlanePoint); + if (snapped) { + tmpSnapEvent.snapDistance = angle; + _this.onSnapObservable.notifyObservers(tmpSnapEvent); + } + // Restore parent + if (attachedMeshParent) { + _this.attachedMesh.setParent(attachedMeshParent); + } + } + }); + _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo) { + if (_this._customMeshSet) { + return; + } + var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1); + var material = isHovered ? hoverMaterial : coloredMaterial; + _this._rootMesh.getChildMeshes().forEach(function (m) { + m.material = material; + if (m.color) { + m.color = material.diffuseColor; + } + }); + }); + var light = gizmoLayer._getSharedGizmoLight(); + light.includedOnlyMeshes = light.includedOnlyMeshes.concat(_this._rootMesh.getChildMeshes(false)); + return _this; + } + PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) { + if (this.dragBehavior) { + this.dragBehavior.enabled = value ? true : false; + } + }; + Object.defineProperty(PlaneRotationGizmo.prototype, "isEnabled", { + get: function () { + return this._isEnabled; + }, + /** + * If the gizmo is enabled + */ + set: function (value) { + this._isEnabled = value; + if (!value) { + this.attachedMesh = null; + } + else { + if (this._parent) { + this.attachedMesh = this._parent.attachedMesh; + } + } + }, + enumerable: true, + configurable: true + }); + /** + * Disposes of the gizmo + */ + PlaneRotationGizmo.prototype.dispose = function () { + this.onSnapObservable.clear(); + this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver); + this.dragBehavior.detach(); + _super.prototype.dispose.call(this); + }; + return PlaneRotationGizmo; +}(_gizmo__WEBPACK_IMPORTED_MODULE_6__["Gizmo"])); + + + +/***/ }), + +/***/ "./Gizmos/positionGizmo.ts": +/*!*********************************!*\ + !*** ./Gizmos/positionGizmo.ts ***! + \*********************************/ +/*! exports provided: PositionGizmo */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PositionGizmo", function() { return PositionGizmo; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts"); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _gizmo__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./gizmo */ "./Gizmos/gizmo.ts"); +/* harmony import */ var _axisDragGizmo__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./axisDragGizmo */ "./Gizmos/axisDragGizmo.ts"); +/* harmony import */ var _planeDragGizmo__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./planeDragGizmo */ "./Gizmos/planeDragGizmo.ts"); +/* harmony import */ var _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Rendering/utilityLayerRenderer */ "./Rendering/utilityLayerRenderer.ts"); + + + + + + + + +/** + * Gizmo that enables dragging a mesh along 3 axis + */ +var PositionGizmo = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PositionGizmo, _super); + /** + * Creates a PositionGizmo + * @param gizmoLayer The utility layer the gizmo will be added to + */ + function PositionGizmo(gizmoLayer) { + if (gizmoLayer === void 0) { gizmoLayer = _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_7__["UtilityLayerRenderer"].DefaultUtilityLayer; } + var _this = _super.call(this, gizmoLayer) || this; + /** + * private variables + */ + _this._meshAttached = null; + /** Fires an event when any of it's sub gizmos are dragged */ + _this.onDragStartObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); + /** Fires an event when any of it's sub gizmos are released from dragging */ + _this.onDragEndObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); + /** + * If set to true, planar drag is enabled + */ + _this._planarGizmoEnabled = false; + _this.xGizmo = new _axisDragGizmo__WEBPACK_IMPORTED_MODULE_5__["AxisDragGizmo"](new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](1, 0, 0), _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Color3"].Red().scale(0.5), gizmoLayer, _this); + _this.yGizmo = new _axisDragGizmo__WEBPACK_IMPORTED_MODULE_5__["AxisDragGizmo"](new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 1, 0), _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Color3"].Green().scale(0.5), gizmoLayer, _this); + _this.zGizmo = new _axisDragGizmo__WEBPACK_IMPORTED_MODULE_5__["AxisDragGizmo"](new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 1), _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Color3"].Blue().scale(0.5), gizmoLayer, _this); + _this.xPlaneGizmo = new _planeDragGizmo__WEBPACK_IMPORTED_MODULE_6__["PlaneDragGizmo"](new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](1, 0, 0), _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Color3"].Red().scale(0.5), _this.gizmoLayer, _this); + _this.yPlaneGizmo = new _planeDragGizmo__WEBPACK_IMPORTED_MODULE_6__["PlaneDragGizmo"](new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 1, 0), _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Color3"].Green().scale(0.5), _this.gizmoLayer, _this); + _this.zPlaneGizmo = new _planeDragGizmo__WEBPACK_IMPORTED_MODULE_6__["PlaneDragGizmo"](new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 1), _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Color3"].Blue().scale(0.5), _this.gizmoLayer, _this); + // Relay drag events + [_this.xGizmo, _this.yGizmo, _this.zGizmo, _this.xPlaneGizmo, _this.yPlaneGizmo, _this.zPlaneGizmo].forEach(function (gizmo) { + gizmo.dragBehavior.onDragStartObservable.add(function () { + _this.onDragStartObservable.notifyObservers({}); + }); + gizmo.dragBehavior.onDragEndObservable.add(function () { + _this.onDragEndObservable.notifyObservers({}); + }); + }); + _this.attachedMesh = null; + return _this; + } + Object.defineProperty(PositionGizmo.prototype, "attachedMesh", { + get: function () { + return this._meshAttached; + }, + set: function (mesh) { + this._meshAttached = mesh; + [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach(function (gizmo) { + if (gizmo.isEnabled) { + gizmo.attachedMesh = mesh; + } + else { + gizmo.attachedMesh = null; + } + }); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(PositionGizmo.prototype, "planarGizmoEnabled", { + get: function () { + return this._planarGizmoEnabled; + }, + /** + * If the planar drag gizmo is enabled + * setting this will enable/disable XY, XZ and YZ planes regardless of individual gizmo settings. + */ + set: function (value) { + var _this = this; + this._planarGizmoEnabled = value; + [this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach(function (gizmo) { + if (gizmo) { + gizmo.isEnabled = value; + if (value) { + gizmo.attachedMesh = _this.attachedMesh; + } + } + }, this); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", { + get: function () { + return this._updateGizmoRotationToMatchAttachedMesh; + }, + set: function (value) { + this._updateGizmoRotationToMatchAttachedMesh = value; + [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach(function (gizmo) { + if (gizmo) { + gizmo.updateGizmoRotationToMatchAttachedMesh = value; + } + }); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(PositionGizmo.prototype, "snapDistance", { + get: function () { + return this._snapDistance; + }, + /** + * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0) + */ + set: function (value) { + this._snapDistance = value; + [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach(function (gizmo) { + if (gizmo) { + gizmo.snapDistance = value; + } + }); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(PositionGizmo.prototype, "scaleRatio", { + get: function () { + return this._scaleRatio; + }, + /** + * Ratio for the scale of the gizmo (Default: 1) + */ + set: function (value) { + this._scaleRatio = value; + [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach(function (gizmo) { + if (gizmo) { + gizmo.scaleRatio = value; + } + }); + }, + enumerable: true, + configurable: true + }); + /** + * Disposes of the gizmo + */ + PositionGizmo.prototype.dispose = function () { + [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach(function (gizmo) { + if (gizmo) { + gizmo.dispose(); + } + }); + this.onDragStartObservable.clear(); + this.onDragEndObservable.clear(); + }; + /** + * CustomMeshes are not supported by this gizmo + * @param mesh The mesh to replace the default mesh of the gizmo + */ + PositionGizmo.prototype.setCustomMesh = function (mesh) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo,gizmo.xPlaneGizmo, gizmo.yPlaneGizmo, gizmo.zPlaneGizmo)"); + }; + return PositionGizmo; +}(_gizmo__WEBPACK_IMPORTED_MODULE_4__["Gizmo"])); + + + +/***/ }), + +/***/ "./Gizmos/rotationGizmo.ts": +/*!*********************************!*\ + !*** ./Gizmos/rotationGizmo.ts ***! + \*********************************/ +/*! exports provided: RotationGizmo */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RotationGizmo", function() { return RotationGizmo; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts"); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _gizmo__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./gizmo */ "./Gizmos/gizmo.ts"); +/* harmony import */ var _planeRotationGizmo__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./planeRotationGizmo */ "./Gizmos/planeRotationGizmo.ts"); +/* harmony import */ var _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Rendering/utilityLayerRenderer */ "./Rendering/utilityLayerRenderer.ts"); + + + + + + + +/** + * Gizmo that enables rotating a mesh along 3 axis + */ +var RotationGizmo = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](RotationGizmo, _super); + /** + * Creates a RotationGizmo + * @param gizmoLayer The utility layer the gizmo will be added to + * @param tessellation Amount of tessellation to be used when creating rotation circles + */ + function RotationGizmo(gizmoLayer, tessellation) { + if (gizmoLayer === void 0) { gizmoLayer = _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_6__["UtilityLayerRenderer"].DefaultUtilityLayer; } + if (tessellation === void 0) { tessellation = 32; } + var _this = _super.call(this, gizmoLayer) || this; + /** Fires an event when any of it's sub gizmos are dragged */ + _this.onDragStartObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); + /** Fires an event when any of it's sub gizmos are released from dragging */ + _this.onDragEndObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); + _this.xGizmo = new _planeRotationGizmo__WEBPACK_IMPORTED_MODULE_5__["PlaneRotationGizmo"](new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](1, 0, 0), _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Color3"].Red().scale(0.5), gizmoLayer, tessellation, _this); + _this.yGizmo = new _planeRotationGizmo__WEBPACK_IMPORTED_MODULE_5__["PlaneRotationGizmo"](new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 1, 0), _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Color3"].Green().scale(0.5), gizmoLayer, tessellation, _this); + _this.zGizmo = new _planeRotationGizmo__WEBPACK_IMPORTED_MODULE_5__["PlaneRotationGizmo"](new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 1), _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Color3"].Blue().scale(0.5), gizmoLayer, tessellation, _this); + // Relay drag events + [_this.xGizmo, _this.yGizmo, _this.zGizmo].forEach(function (gizmo) { + gizmo.dragBehavior.onDragStartObservable.add(function () { + _this.onDragStartObservable.notifyObservers({}); + }); + gizmo.dragBehavior.onDragEndObservable.add(function () { + _this.onDragEndObservable.notifyObservers({}); + }); + }); + _this.attachedMesh = null; + return _this; + } + Object.defineProperty(RotationGizmo.prototype, "attachedMesh", { + get: function () { + return this._meshAttached; + }, + set: function (mesh) { + this._meshAttached = mesh; + [this.xGizmo, this.yGizmo, this.zGizmo].forEach(function (gizmo) { + if (gizmo.isEnabled) { + gizmo.attachedMesh = mesh; + } + else { + gizmo.attachedMesh = null; + } + }); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", { + get: function () { + return this.xGizmo.updateGizmoRotationToMatchAttachedMesh; + }, + set: function (value) { + if (this.xGizmo) { + this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value; + this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value; + this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(RotationGizmo.prototype, "snapDistance", { + get: function () { + return this.xGizmo.snapDistance; + }, + /** + * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0) + */ + set: function (value) { + if (this.xGizmo) { + this.xGizmo.snapDistance = value; + this.yGizmo.snapDistance = value; + this.zGizmo.snapDistance = value; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(RotationGizmo.prototype, "scaleRatio", { + get: function () { + return this.xGizmo.scaleRatio; + }, + /** + * Ratio for the scale of the gizmo (Default: 1) + */ + set: function (value) { + if (this.xGizmo) { + this.xGizmo.scaleRatio = value; + this.yGizmo.scaleRatio = value; + this.zGizmo.scaleRatio = value; + } + }, + enumerable: true, + configurable: true + }); + /** + * Disposes of the gizmo + */ + RotationGizmo.prototype.dispose = function () { + this.xGizmo.dispose(); + this.yGizmo.dispose(); + this.zGizmo.dispose(); + this.onDragStartObservable.clear(); + this.onDragEndObservable.clear(); + }; + /** + * CustomMeshes are not supported by this gizmo + * @param mesh The mesh to replace the default mesh of the gizmo + */ + RotationGizmo.prototype.setCustomMesh = function (mesh) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)"); + }; + return RotationGizmo; +}(_gizmo__WEBPACK_IMPORTED_MODULE_4__["Gizmo"])); + + + +/***/ }), + +/***/ "./Gizmos/scaleGizmo.ts": +/*!******************************!*\ + !*** ./Gizmos/scaleGizmo.ts ***! + \******************************/ +/*! exports provided: ScaleGizmo */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ScaleGizmo", function() { return ScaleGizmo; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts"); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Meshes_Builders_polyhedronBuilder__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Meshes/Builders/polyhedronBuilder */ "./Meshes/Builders/polyhedronBuilder.ts"); +/* harmony import */ var _gizmo__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./gizmo */ "./Gizmos/gizmo.ts"); +/* harmony import */ var _axisScaleGizmo__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./axisScaleGizmo */ "./Gizmos/axisScaleGizmo.ts"); +/* harmony import */ var _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Rendering/utilityLayerRenderer */ "./Rendering/utilityLayerRenderer.ts"); + + + + + + + + +/** + * Gizmo that enables scaling a mesh along 3 axis + */ +var ScaleGizmo = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ScaleGizmo, _super); + /** + * Creates a ScaleGizmo + * @param gizmoLayer The utility layer the gizmo will be added to + */ + function ScaleGizmo(gizmoLayer) { + if (gizmoLayer === void 0) { gizmoLayer = _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_7__["UtilityLayerRenderer"].DefaultUtilityLayer; } + var _this = _super.call(this, gizmoLayer) || this; + _this._meshAttached = null; + /** Fires an event when any of it's sub gizmos are dragged */ + _this.onDragStartObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); + /** Fires an event when any of it's sub gizmos are released from dragging */ + _this.onDragEndObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); + _this.xGizmo = new _axisScaleGizmo__WEBPACK_IMPORTED_MODULE_6__["AxisScaleGizmo"](new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](1, 0, 0), _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Color3"].Red().scale(0.5), gizmoLayer, _this); + _this.yGizmo = new _axisScaleGizmo__WEBPACK_IMPORTED_MODULE_6__["AxisScaleGizmo"](new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 1, 0), _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Color3"].Green().scale(0.5), gizmoLayer, _this); + _this.zGizmo = new _axisScaleGizmo__WEBPACK_IMPORTED_MODULE_6__["AxisScaleGizmo"](new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 1), _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Color3"].Blue().scale(0.5), gizmoLayer, _this); + // Create uniform scale gizmo + _this.uniformScaleGizmo = new _axisScaleGizmo__WEBPACK_IMPORTED_MODULE_6__["AxisScaleGizmo"](new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 1, 0), _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Color3"].Yellow().scale(0.5), gizmoLayer, _this); + _this.uniformScaleGizmo.updateGizmoRotationToMatchAttachedMesh = false; + _this.uniformScaleGizmo.uniformScaling = true; + _this._uniformScalingMesh = _Meshes_Builders_polyhedronBuilder__WEBPACK_IMPORTED_MODULE_4__["PolyhedronBuilder"].CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene); + _this._uniformScalingMesh.scaling.scaleInPlace(0.02); + _this._uniformScalingMesh.visibility = 0; + _this._octahedron = _Meshes_Builders_polyhedronBuilder__WEBPACK_IMPORTED_MODULE_4__["PolyhedronBuilder"].CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene); + _this._octahedron.scaling.scaleInPlace(0.007); + _this._uniformScalingMesh.addChild(_this._octahedron); + _this.uniformScaleGizmo.setCustomMesh(_this._uniformScalingMesh, true); + var light = gizmoLayer._getSharedGizmoLight(); + light.includedOnlyMeshes = light.includedOnlyMeshes.concat(_this._octahedron); + // Relay drag events + [_this.xGizmo, _this.yGizmo, _this.zGizmo, _this.uniformScaleGizmo].forEach(function (gizmo) { + gizmo.dragBehavior.onDragStartObservable.add(function () { + _this.onDragStartObservable.notifyObservers({}); + }); + gizmo.dragBehavior.onDragEndObservable.add(function () { + _this.onDragEndObservable.notifyObservers({}); + }); + }); + _this.attachedMesh = null; + return _this; + } + Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", { + get: function () { + return this._meshAttached; + }, + set: function (mesh) { + this._meshAttached = mesh; + [this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach(function (gizmo) { + if (gizmo.isEnabled) { + gizmo.attachedMesh = mesh; + } + else { + gizmo.attachedMesh = null; + } + }); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", { + get: function () { + return this._updateGizmoRotationToMatchAttachedMesh; + }, + set: function (value) { + if (!value) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn("Setting updateGizmoRotationToMatchAttachedMesh = false on scaling gizmo is not supported."); + } + else { + this._updateGizmoRotationToMatchAttachedMesh = value; + [this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach(function (gizmo) { + if (gizmo) { + gizmo.updateGizmoRotationToMatchAttachedMesh = value; + } + }); + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ScaleGizmo.prototype, "snapDistance", { + get: function () { + return this._snapDistance; + }, + /** + * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0) + */ + set: function (value) { + this._snapDistance = value; + [this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach(function (gizmo) { + if (gizmo) { + gizmo.snapDistance = value; + } + }); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", { + get: function () { + return this._scaleRatio; + }, + /** + * Ratio for the scale of the gizmo (Default: 1) + */ + set: function (value) { + this._scaleRatio = value; + [this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach(function (gizmo) { + if (gizmo) { + gizmo.scaleRatio = value; + } + }); + }, + enumerable: true, + configurable: true + }); + /** + * Disposes of the gizmo + */ + ScaleGizmo.prototype.dispose = function () { + [this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach(function (gizmo) { + if (gizmo) { + gizmo.dispose(); + } + }); + this.onDragStartObservable.clear(); + this.onDragEndObservable.clear(); + [this._uniformScalingMesh, this._octahedron].forEach(function (msh) { + if (msh) { + msh.dispose(); + } + }); + }; + return ScaleGizmo; +}(_gizmo__WEBPACK_IMPORTED_MODULE_5__["Gizmo"])); + + + +/***/ }), + +/***/ "./Helpers/environmentHelper.ts": +/*!**************************************!*\ + !*** ./Helpers/environmentHelper.ts ***! + \**************************************/ +/*! exports provided: EnvironmentHelper */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EnvironmentHelper", function() { return EnvironmentHelper; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _Cameras_arcRotateCamera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Cameras/arcRotateCamera */ "./Cameras/arcRotateCamera.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Meshes_mesh__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Meshes/mesh */ "./Meshes/mesh.ts"); +/* harmony import */ var _Materials_Textures_baseTexture__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Materials/Textures/baseTexture */ "./Materials/Textures/baseTexture.ts"); +/* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Materials/Textures/texture */ "./Materials/Textures/texture.ts"); +/* harmony import */ var _Materials_Textures_mirrorTexture__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Materials/Textures/mirrorTexture */ "./Materials/Textures/mirrorTexture.ts"); +/* harmony import */ var _Materials_Textures_cubeTexture__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Materials/Textures/cubeTexture */ "./Materials/Textures/cubeTexture.ts"); +/* harmony import */ var _Materials_Background_backgroundMaterial__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Materials/Background/backgroundMaterial */ "./Materials/Background/backgroundMaterial.ts"); +/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts"); +/* harmony import */ var _Meshes_Builders_planeBuilder__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../Meshes/Builders/planeBuilder */ "./Meshes/Builders/planeBuilder.ts"); +/* harmony import */ var _Meshes_Builders_boxBuilder__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../Meshes/Builders/boxBuilder */ "./Meshes/Builders/boxBuilder.ts"); + + + + + + + + + + + + + +/** + * The Environment helper class can be used to add a fully featuread none expensive background to your scene. + * It includes by default a skybox and a ground relying on the BackgroundMaterial. + * It also helps with the default setup of your imageProcessing configuration. + */ +var EnvironmentHelper = /** @class */ (function () { + /** + * constructor + * @param options Defines the options we want to customize the helper + * @param scene The scene to add the material to + */ + function EnvironmentHelper(options, scene) { + var _this = this; + this._errorHandler = function (message, exception) { + _this.onErrorObservable.notifyObservers({ message: message, exception: exception }); + }; + this._options = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, EnvironmentHelper._getDefaultOptions(), options); + this._scene = scene; + this.onErrorObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + this._setupBackground(); + this._setupImageProcessing(); + } + /** + * Creates the default options for the helper. + */ + EnvironmentHelper._getDefaultOptions = function () { + return { + createGround: true, + groundSize: 15, + groundTexture: this._groundTextureCDNUrl, + groundColor: new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Color3"](0.2, 0.2, 0.3).toLinearSpace().scale(3), + groundOpacity: 0.9, + enableGroundShadow: true, + groundShadowLevel: 0.5, + enableGroundMirror: false, + groundMirrorSizeRatio: 0.3, + groundMirrorBlurKernel: 64, + groundMirrorAmount: 1, + groundMirrorFresnelWeight: 1, + groundMirrorFallOffDistance: 0, + groundMirrorTextureType: _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].TEXTURETYPE_UNSIGNED_INT, + groundYBias: 0.00001, + createSkybox: true, + skyboxSize: 20, + skyboxTexture: this._skyboxTextureCDNUrl, + skyboxColor: new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Color3"](0.2, 0.2, 0.3).toLinearSpace().scale(3), + backgroundYRotation: 0, + sizeAuto: true, + rootPosition: _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(), + setupImageProcessing: true, + environmentTexture: this._environmentTextureCDNUrl, + cameraExposure: 0.8, + cameraContrast: 1.2, + toneMappingEnabled: true, + }; + }; + Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", { + /** + * Gets the root mesh created by the helper. + */ + get: function () { + return this._rootMesh; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(EnvironmentHelper.prototype, "skybox", { + /** + * Gets the skybox created by the helper. + */ + get: function () { + return this._skybox; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", { + /** + * Gets the skybox texture created by the helper. + */ + get: function () { + return this._skyboxTexture; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", { + /** + * Gets the skybox material created by the helper. + */ + get: function () { + return this._skyboxMaterial; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(EnvironmentHelper.prototype, "ground", { + /** + * Gets the ground mesh created by the helper. + */ + get: function () { + return this._ground; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", { + /** + * Gets the ground texture created by the helper. + */ + get: function () { + return this._groundTexture; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", { + /** + * Gets the ground mirror created by the helper. + */ + get: function () { + return this._groundMirror; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", { + /** + * Gets the ground mirror render list to helps pushing the meshes + * you wish in the ground reflection. + */ + get: function () { + if (this._groundMirror) { + return this._groundMirror.renderList; + } + return null; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", { + /** + * Gets the ground material created by the helper. + */ + get: function () { + return this._groundMaterial; + }, + enumerable: true, + configurable: true + }); + /** + * Updates the background according to the new options + * @param options + */ + EnvironmentHelper.prototype.updateOptions = function (options) { + var newOptions = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, this._options, options); + if (this._ground && !newOptions.createGround) { + this._ground.dispose(); + this._ground = null; + } + if (this._groundMaterial && !newOptions.createGround) { + this._groundMaterial.dispose(); + this._groundMaterial = null; + } + if (this._groundTexture) { + if (this._options.groundTexture != newOptions.groundTexture) { + this._groundTexture.dispose(); + this._groundTexture = null; + } + } + if (this._skybox && !newOptions.createSkybox) { + this._skybox.dispose(); + this._skybox = null; + } + if (this._skyboxMaterial && !newOptions.createSkybox) { + this._skyboxMaterial.dispose(); + this._skyboxMaterial = null; + } + if (this._skyboxTexture) { + if (this._options.skyboxTexture != newOptions.skyboxTexture) { + this._skyboxTexture.dispose(); + this._skyboxTexture = null; + } + } + if (this._groundMirror && !newOptions.enableGroundMirror) { + this._groundMirror.dispose(); + this._groundMirror = null; + } + if (this._scene.environmentTexture) { + if (this._options.environmentTexture != newOptions.environmentTexture) { + this._scene.environmentTexture.dispose(); + } + } + this._options = newOptions; + this._setupBackground(); + this._setupImageProcessing(); + }; + /** + * Sets the primary color of all the available elements. + * @param color the main color to affect to the ground and the background + */ + EnvironmentHelper.prototype.setMainColor = function (color) { + if (this.groundMaterial) { + this.groundMaterial.primaryColor = color; + } + if (this.skyboxMaterial) { + this.skyboxMaterial.primaryColor = color; + } + if (this.groundMirror) { + this.groundMirror.clearColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Color4"](color.r, color.g, color.b, 1.0); + } + }; + /** + * Setup the image processing according to the specified options. + */ + EnvironmentHelper.prototype._setupImageProcessing = function () { + if (this._options.setupImageProcessing) { + this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast; + this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure; + this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled; + this._setupEnvironmentTexture(); + } + }; + /** + * Setup the environment texture according to the specified options. + */ + EnvironmentHelper.prototype._setupEnvironmentTexture = function () { + if (this._scene.environmentTexture) { + return; + } + if (this._options.environmentTexture instanceof _Materials_Textures_baseTexture__WEBPACK_IMPORTED_MODULE_5__["BaseTexture"]) { + this._scene.environmentTexture = this._options.environmentTexture; + return; + } + var environmentTexture = _Materials_Textures_cubeTexture__WEBPACK_IMPORTED_MODULE_8__["CubeTexture"].CreateFromPrefilteredData(this._options.environmentTexture, this._scene); + this._scene.environmentTexture = environmentTexture; + }; + /** + * Setup the background according to the specified options. + */ + EnvironmentHelper.prototype._setupBackground = function () { + if (!this._rootMesh) { + this._rootMesh = new _Meshes_mesh__WEBPACK_IMPORTED_MODULE_4__["Mesh"]("BackgroundHelper", this._scene); + } + this._rootMesh.rotation.y = this._options.backgroundYRotation; + var sceneSize = this._getSceneSize(); + if (this._options.createGround) { + this._setupGround(sceneSize); + this._setupGroundMaterial(); + this._setupGroundDiffuseTexture(); + if (this._options.enableGroundMirror) { + this._setupGroundMirrorTexture(sceneSize); + } + this._setupMirrorInGroundMaterial(); + } + if (this._options.createSkybox) { + this._setupSkybox(sceneSize); + this._setupSkyboxMaterial(); + this._setupSkyboxReflectionTexture(); + } + this._rootMesh.position.x = sceneSize.rootPosition.x; + this._rootMesh.position.z = sceneSize.rootPosition.z; + this._rootMesh.position.y = sceneSize.rootPosition.y; + }; + /** + * Get the scene sizes according to the setup. + */ + EnvironmentHelper.prototype._getSceneSize = function () { + var _this = this; + var groundSize = this._options.groundSize; + var skyboxSize = this._options.skyboxSize; + var rootPosition = this._options.rootPosition; + if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper. + return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition }; + } + var sceneExtends = this._scene.getWorldExtends(function (mesh) { + return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox); + }); + var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min); + if (this._options.sizeAuto) { + if (this._scene.activeCamera instanceof _Cameras_arcRotateCamera__WEBPACK_IMPORTED_MODULE_2__["ArcRotateCamera"] && + this._scene.activeCamera.upperRadiusLimit) { + groundSize = this._scene.activeCamera.upperRadiusLimit * 2; + skyboxSize = groundSize; + } + var sceneDiagonalLenght = sceneDiagonal.length(); + if (sceneDiagonalLenght > groundSize) { + groundSize = sceneDiagonalLenght * 2; + skyboxSize = groundSize; + } + // 10 % bigger. + groundSize *= 1.1; + skyboxSize *= 1.5; + rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5)); + rootPosition.y = sceneExtends.min.y - this._options.groundYBias; + } + return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition }; + }; + /** + * Setup the ground according to the specified options. + */ + EnvironmentHelper.prototype._setupGround = function (sceneSize) { + var _this = this; + if (!this._ground || this._ground.isDisposed()) { + this._ground = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_4__["Mesh"].CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene); + this._ground.rotation.x = Math.PI / 2; // Face up by default. + this._ground.parent = this._rootMesh; + this._ground.onDisposeObservable.add(function () { _this._ground = null; }); + } + this._ground.receiveShadows = this._options.enableGroundShadow; + }; + /** + * Setup the ground material according to the specified options. + */ + EnvironmentHelper.prototype._setupGroundMaterial = function () { + if (!this._groundMaterial) { + this._groundMaterial = new _Materials_Background_backgroundMaterial__WEBPACK_IMPORTED_MODULE_9__["BackgroundMaterial"]("BackgroundPlaneMaterial", this._scene); + } + this._groundMaterial.alpha = this._options.groundOpacity; + this._groundMaterial.alphaMode = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].ALPHA_PREMULTIPLIED_PORTERDUFF; + this._groundMaterial.shadowLevel = this._options.groundShadowLevel; + this._groundMaterial.primaryColor = this._options.groundColor; + this._groundMaterial.useRGBColor = false; + this._groundMaterial.enableNoise = true; + if (this._ground) { + this._ground.material = this._groundMaterial; + } + }; + /** + * Setup the ground diffuse texture according to the specified options. + */ + EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () { + if (!this._groundMaterial) { + return; + } + if (this._groundTexture) { + return; + } + if (this._options.groundTexture instanceof _Materials_Textures_baseTexture__WEBPACK_IMPORTED_MODULE_5__["BaseTexture"]) { + this._groundMaterial.diffuseTexture = this._options.groundTexture; + return; + } + var diffuseTexture = new _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__["Texture"](this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler); + diffuseTexture.gammaSpace = false; + diffuseTexture.hasAlpha = true; + this._groundMaterial.diffuseTexture = diffuseTexture; + }; + /** + * Setup the ground mirror texture according to the specified options. + */ + EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) { + var wrapping = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__["Texture"].CLAMP_ADDRESSMODE; + if (!this._groundMirror) { + this._groundMirror = new _Materials_Textures_mirrorTexture__WEBPACK_IMPORTED_MODULE_7__["MirrorTexture"]("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__["Texture"].BILINEAR_SAMPLINGMODE, true); + this._groundMirror.mirrorPlane = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Plane"](0, -1, 0, sceneSize.rootPosition.y); + this._groundMirror.anisotropicFilteringLevel = 1; + this._groundMirror.wrapU = wrapping; + this._groundMirror.wrapV = wrapping; + this._groundMirror.gammaSpace = false; + if (this._groundMirror.renderList) { + for (var i = 0; i < this._scene.meshes.length; i++) { + var mesh = this._scene.meshes[i]; + if (mesh !== this._ground && + mesh !== this._skybox && + mesh !== this._rootMesh) { + this._groundMirror.renderList.push(mesh); + } + } + } + } + this._groundMirror.clearColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Color4"](this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1); + this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel; + }; + /** + * Setup the ground to receive the mirror texture. + */ + EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () { + if (this._groundMaterial) { + this._groundMaterial.reflectionTexture = this._groundMirror; + this._groundMaterial.reflectionFresnel = true; + this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount; + this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight; + this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance; + } + }; + /** + * Setup the skybox according to the specified options. + */ + EnvironmentHelper.prototype._setupSkybox = function (sceneSize) { + var _this = this; + if (!this._skybox || this._skybox.isDisposed()) { + this._skybox = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_4__["Mesh"].CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, _Meshes_mesh__WEBPACK_IMPORTED_MODULE_4__["Mesh"].BACKSIDE); + this._skybox.onDisposeObservable.add(function () { _this._skybox = null; }); + } + this._skybox.parent = this._rootMesh; + }; + /** + * Setup the skybox material according to the specified options. + */ + EnvironmentHelper.prototype._setupSkyboxMaterial = function () { + if (!this._skybox) { + return; + } + if (!this._skyboxMaterial) { + this._skyboxMaterial = new _Materials_Background_backgroundMaterial__WEBPACK_IMPORTED_MODULE_9__["BackgroundMaterial"]("BackgroundSkyboxMaterial", this._scene); + } + this._skyboxMaterial.useRGBColor = false; + this._skyboxMaterial.primaryColor = this._options.skyboxColor; + this._skyboxMaterial.enableNoise = true; + this._skybox.material = this._skyboxMaterial; + }; + /** + * Setup the skybox reflection texture according to the specified options. + */ + EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () { + if (!this._skyboxMaterial) { + return; + } + if (this._skyboxTexture) { + return; + } + if (this._options.skyboxTexture instanceof _Materials_Textures_baseTexture__WEBPACK_IMPORTED_MODULE_5__["BaseTexture"]) { + this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture; + return; + } + this._skyboxTexture = new _Materials_Textures_cubeTexture__WEBPACK_IMPORTED_MODULE_8__["CubeTexture"](this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler); + this._skyboxTexture.coordinatesMode = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__["Texture"].SKYBOX_MODE; + this._skyboxTexture.gammaSpace = false; + this._skyboxMaterial.reflectionTexture = this._skyboxTexture; + }; + /** + * Dispose all the elements created by the Helper. + */ + EnvironmentHelper.prototype.dispose = function () { + if (this._groundMaterial) { + this._groundMaterial.dispose(true, true); + } + if (this._skyboxMaterial) { + this._skyboxMaterial.dispose(true, true); + } + this._rootMesh.dispose(false); + }; + /** + * Default ground texture URL. + */ + EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png"; + /** + * Default skybox texture URL. + */ + EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds"; + /** + * Default environment texture URL. + */ + EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env"; + return EnvironmentHelper; +}()); + + + +/***/ }), + +/***/ "./Helpers/index.ts": +/*!**************************!*\ + !*** ./Helpers/index.ts ***! + \**************************/ +/*! exports provided: EnvironmentHelper, PhotoDome, _forceSceneHelpersToBundle, VideoDome */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _environmentHelper__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./environmentHelper */ "./Helpers/environmentHelper.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EnvironmentHelper", function() { return _environmentHelper__WEBPACK_IMPORTED_MODULE_0__["EnvironmentHelper"]; }); + +/* harmony import */ var _photoDome__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./photoDome */ "./Helpers/photoDome.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PhotoDome", function() { return _photoDome__WEBPACK_IMPORTED_MODULE_1__["PhotoDome"]; }); + +/* harmony import */ var _sceneHelpers__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./sceneHelpers */ "./Helpers/sceneHelpers.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_forceSceneHelpersToBundle", function() { return _sceneHelpers__WEBPACK_IMPORTED_MODULE_2__["_forceSceneHelpersToBundle"]; }); + +/* harmony import */ var _videoDome__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./videoDome */ "./Helpers/videoDome.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VideoDome", function() { return _videoDome__WEBPACK_IMPORTED_MODULE_3__["VideoDome"]; }); + + + + + + + +/***/ }), + +/***/ "./Helpers/photoDome.ts": +/*!******************************!*\ + !*** ./Helpers/photoDome.ts ***! + \******************************/ +/*! exports provided: PhotoDome */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PhotoDome", function() { return PhotoDome; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _Meshes_transformNode__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Meshes/transformNode */ "./Meshes/transformNode.ts"); +/* harmony import */ var _Meshes_mesh__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Meshes/mesh */ "./Meshes/mesh.ts"); +/* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Materials/Textures/texture */ "./Materials/Textures/texture.ts"); +/* harmony import */ var _Materials_Background_backgroundMaterial__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Materials/Background/backgroundMaterial */ "./Materials/Background/backgroundMaterial.ts"); +/* harmony import */ var _Meshes_Builders_sphereBuilder__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Meshes/Builders/sphereBuilder */ "./Meshes/Builders/sphereBuilder.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); + + + + + + + + +/** + * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes. + * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene. + * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere. + * Potential additions to this helper include zoom and and non-infinite distance rendering effects. + */ +var PhotoDome = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PhotoDome, _super); + /** + * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh. + * @param name Element's name, child elements will append suffixes for their own names. + * @param urlsOfPhoto defines the url of the photo to display + * @param options defines an object containing optional or exposed sub element properties + * @param onError defines a callback called when an error occured while loading the texture + */ + function PhotoDome(name, urlOfPhoto, options, scene, onError) { + if (onError === void 0) { onError = null; } + var _this = _super.call(this, name, scene) || this; + _this._useDirectMapping = false; + /** + * Observable raised when an error occured while loading the 360 image + */ + _this.onLoadErrorObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + _this._imageMode = PhotoDome.MODE_MONOSCOPIC; + _this._onBeforeCameraRenderObserver = null; + // set defaults and manage values + name = name || "photoDome"; + options.resolution = (Math.abs(options.resolution) | 0) || 32; + options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000); + if (options.useDirectMapping === undefined) { + _this._useDirectMapping = true; + } + else { + _this._useDirectMapping = options.useDirectMapping; + } + if (options.faceForward === undefined) { + options.faceForward = true; + } + _this._setReady(false); + // create + var material = _this._material = new _Materials_Background_backgroundMaterial__WEBPACK_IMPORTED_MODULE_5__["BackgroundMaterial"](name + "_material", scene); + _this._mesh = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_3__["Mesh"].CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, _Meshes_mesh__WEBPACK_IMPORTED_MODULE_3__["Mesh"].BACKSIDE); + // configure material + material.opacityFresnel = false; + material.useEquirectangularFOV = true; + material.fovMultiplier = 1.0; + _this.photoTexture = new _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"](urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) { + _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured"); + if (onError) { + onError(message, exception); + } + }); + _this.photoTexture.onLoadObservable.addOnce(function () { + _this._setReady(true); + }); + // configure mesh + _this._mesh.material = material; + _this._mesh.parent = _this; + // Initial rotation + if (options.faceForward && scene.activeCamera) { + var camera = scene.activeCamera; + var forward = _Maths_math__WEBPACK_IMPORTED_MODULE_7__["Vector3"].Forward(); + var direction = _Maths_math__WEBPACK_IMPORTED_MODULE_7__["Vector3"].TransformNormal(forward, camera.getViewMatrix()); + direction.normalize(); + _this.rotation.y = Math.acos(_Maths_math__WEBPACK_IMPORTED_MODULE_7__["Vector3"].Dot(forward, direction)); + } + return _this; + } + Object.defineProperty(PhotoDome.prototype, "photoTexture", { + /** + * Gets or sets the texture being displayed on the sphere + */ + get: function () { + return this._photoTexture; + }, + set: function (value) { + if (this._photoTexture === value) { + return; + } + this._photoTexture = value; + if (this._useDirectMapping) { + this._photoTexture.wrapU = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].CLAMP_ADDRESSMODE; + this._photoTexture.wrapV = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].CLAMP_ADDRESSMODE; + this._material.diffuseTexture = this._photoTexture; + } + else { + this._photoTexture.coordinatesMode = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation + this._photoTexture.wrapV = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].CLAMP_ADDRESSMODE; + this._material.reflectionTexture = this._photoTexture; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(PhotoDome.prototype, "fovMultiplier", { + /** + * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out". + * Also see the options.resolution property. + */ + get: function () { + return this._material.fovMultiplier; + }, + set: function (value) { + this._material.fovMultiplier = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(PhotoDome.prototype, "imageMode", { + /** + * Gets or set the current video mode for the video. It can be: + * * PhotoDome.MODE_MONOSCOPIC : Define the image as a Monoscopic panoramic 360 image. + * * PhotoDome.MODE_TOPBOTTOM : Define the image as a Stereoscopic TopBottom/OverUnder panoramic 360 image. + * * PhotoDome.MODE_SIDEBYSIDE : Define the image as a Stereoscopic Side by Side panoramic 360 image. + */ + get: function () { + return this._imageMode; + }, + set: function (value) { + if (this._imageMode === value) { + return; + } + this._changeImageMode(value); + }, + enumerable: true, + configurable: true + }); + PhotoDome.prototype._changeImageMode = function (value) { + var _this = this; + this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver); + this._imageMode = value; + // Default Setup and Reset. + this._photoTexture.uScale = 1; + this._photoTexture.vScale = 1; + this._photoTexture.uOffset = 0; + this._photoTexture.vOffset = 0; + switch (value) { + case PhotoDome.MODE_SIDEBYSIDE: + this._photoTexture.uScale = 0.5; + this._onBeforeCameraRenderObserver = this._scene.onBeforeCameraRenderObservable.add(function (camera) { + _this._photoTexture.uOffset = camera.isRightCamera ? 0.5 : 0.0; + }); + break; + case PhotoDome.MODE_TOPBOTTOM: + this._photoTexture.vScale = 0.5; + this._onBeforeCameraRenderObserver = this._scene.onBeforeCameraRenderObservable.add(function (camera) { + _this._photoTexture.vOffset = camera.isRightCamera ? 0.5 : 0.0; + }); + break; + } + }; + /** + * Releases resources associated with this node. + * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default) + * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default) + */ + PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) { + if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; } + this._photoTexture.dispose(); + this._mesh.dispose(); + this._material.dispose(); + this.onLoadErrorObservable.clear(); + this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver); + _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures); + }; + /** + * Define the image as a Monoscopic panoramic 360 image. + */ + PhotoDome.MODE_MONOSCOPIC = 0; + /** + * Define the image as a Stereoscopic TopBottom/OverUnder panoramic 360 image. + */ + PhotoDome.MODE_TOPBOTTOM = 1; + /** + * Define the image as a Stereoscopic Side by Side panoramic 360 image. + */ + PhotoDome.MODE_SIDEBYSIDE = 2; + return PhotoDome; +}(_Meshes_transformNode__WEBPACK_IMPORTED_MODULE_2__["TransformNode"])); + + + +/***/ }), + +/***/ "./Helpers/sceneHelpers.ts": +/*!*********************************!*\ + !*** ./Helpers/sceneHelpers.ts ***! + \*********************************/ +/*! exports provided: _forceSceneHelpersToBundle */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_forceSceneHelpersToBundle", function() { return _forceSceneHelpersToBundle; }); +/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts"); +/* harmony import */ var _scene__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../scene */ "./scene.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Meshes_mesh__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Meshes/mesh */ "./Meshes/mesh.ts"); +/* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Materials/Textures/texture */ "./Materials/Textures/texture.ts"); +/* harmony import */ var _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Materials/standardMaterial */ "./Materials/standardMaterial.ts"); +/* harmony import */ var _Materials_PBR_pbrMaterial__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Materials/PBR/pbrMaterial */ "./Materials/PBR/pbrMaterial.ts"); +/* harmony import */ var _Lights_hemisphericLight__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Lights/hemisphericLight */ "./Lights/hemisphericLight.ts"); +/* harmony import */ var _environmentHelper__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./environmentHelper */ "./Helpers/environmentHelper.ts"); +/* harmony import */ var _Cameras_freeCamera__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Cameras/freeCamera */ "./Cameras/freeCamera.ts"); +/* harmony import */ var _Cameras_arcRotateCamera__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../Cameras/arcRotateCamera */ "./Cameras/arcRotateCamera.ts"); +/* harmony import */ var _Cameras_XR_webXRManagedOutputCanvas__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../Cameras/XR/webXRManagedOutputCanvas */ "./Cameras/XR/webXRManagedOutputCanvas.ts"); +/* harmony import */ var _Cameras_XR_webXRInput__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../Cameras/XR/webXRInput */ "./Cameras/XR/webXRInput.ts"); +/* harmony import */ var _Cameras_XR_webXREnterExitUI__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../Cameras/XR/webXREnterExitUI */ "./Cameras/XR/webXREnterExitUI.ts"); +/* harmony import */ var _Cameras_XR_webXRExperienceHelper__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../Cameras/XR/webXRExperienceHelper */ "./Cameras/XR/webXRExperienceHelper.ts"); +/* harmony import */ var _Cameras_VR_vrExperienceHelper__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../Cameras/VR/vrExperienceHelper */ "./Cameras/VR/vrExperienceHelper.ts"); +/* harmony import */ var _Materials_Textures_Loaders_ddsTextureLoader__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../Materials/Textures/Loaders/ddsTextureLoader */ "./Materials/Textures/Loaders/ddsTextureLoader.ts"); +/* harmony import */ var _Materials_Textures_Loaders_envTextureLoader__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../Materials/Textures/Loaders/envTextureLoader */ "./Materials/Textures/Loaders/envTextureLoader.ts"); +/* harmony import */ var _Materials_Textures_Loaders_ktxTextureLoader__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../Materials/Textures/Loaders/ktxTextureLoader */ "./Materials/Textures/Loaders/ktxTextureLoader.ts"); +/* harmony import */ var _Meshes_Builders_boxBuilder__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../Meshes/Builders/boxBuilder */ "./Meshes/Builders/boxBuilder.ts"); + + + + + + + + + + + + + + + + + + + + +/** @hidden */ +var _forceSceneHelpersToBundle = true; +_scene__WEBPACK_IMPORTED_MODULE_1__["Scene"].prototype.createDefaultLight = function (replace) { + if (replace === void 0) { replace = false; } + // Dispose existing light in replace mode. + if (replace) { + if (this.lights) { + for (var i = 0; i < this.lights.length; i++) { + this.lights[i].dispose(); + } + } + } + // Light + if (this.lights.length === 0) { + new _Lights_hemisphericLight__WEBPACK_IMPORTED_MODULE_7__["HemisphericLight"]("default light", _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Up(), this); + } +}; +_scene__WEBPACK_IMPORTED_MODULE_1__["Scene"].prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) { + if (createArcRotateCamera === void 0) { createArcRotateCamera = false; } + if (replace === void 0) { replace = false; } + if (attachCameraControls === void 0) { attachCameraControls = false; } + // Dispose existing camera in replace mode. + if (replace) { + if (this.activeCamera) { + this.activeCamera.dispose(); + this.activeCamera = null; + } + } + // Camera + if (!this.activeCamera) { + var worldExtends = this.getWorldExtends(); + var worldSize = worldExtends.max.subtract(worldExtends.min); + var worldCenter = worldExtends.min.add(worldSize.scale(0.5)); + var camera; + var radius = worldSize.length() * 1.5; + // empty scene scenario! + if (!isFinite(radius)) { + radius = 1; + worldCenter.copyFromFloats(0, 0, 0); + } + if (createArcRotateCamera) { + var arcRotateCamera = new _Cameras_arcRotateCamera__WEBPACK_IMPORTED_MODULE_10__["ArcRotateCamera"]("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this); + arcRotateCamera.lowerRadiusLimit = radius * 0.01; + arcRotateCamera.wheelPrecision = 100 / radius; + camera = arcRotateCamera; + } + else { + var freeCamera = new _Cameras_freeCamera__WEBPACK_IMPORTED_MODULE_9__["FreeCamera"]("default camera", new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](worldCenter.x, worldCenter.y, -radius), this); + freeCamera.setTarget(worldCenter); + camera = freeCamera; + } + camera.minZ = radius * 0.01; + camera.maxZ = radius * 1000; + camera.speed = radius * 0.2; + this.activeCamera = camera; + var canvas = this.getEngine().getRenderingCanvas(); + if (attachCameraControls && canvas) { + camera.attachControl(canvas); + } + } +}; +_scene__WEBPACK_IMPORTED_MODULE_1__["Scene"].prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) { + if (createArcRotateCamera === void 0) { createArcRotateCamera = false; } + if (replace === void 0) { replace = false; } + if (attachCameraControls === void 0) { attachCameraControls = false; } + this.createDefaultLight(replace); + this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls); +}; +_scene__WEBPACK_IMPORTED_MODULE_1__["Scene"].prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) { + if (pbr === void 0) { pbr = false; } + if (scale === void 0) { scale = 1000; } + if (blur === void 0) { blur = 0; } + if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; } + if (!environmentTexture) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_0__["Logger"].Warn("Can not create default skybox without environment texture."); + return null; + } + if (setGlobalEnvTexture) { + if (environmentTexture) { + this.environmentTexture = environmentTexture; + } + } + // Skybox + var hdrSkybox = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_3__["Mesh"].CreateBox("hdrSkyBox", scale, this); + if (pbr) { + var hdrSkyboxMaterial = new _Materials_PBR_pbrMaterial__WEBPACK_IMPORTED_MODULE_6__["PBRMaterial"]("skyBox", this); + hdrSkyboxMaterial.backFaceCulling = false; + hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone(); + if (hdrSkyboxMaterial.reflectionTexture) { + hdrSkyboxMaterial.reflectionTexture.coordinatesMode = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].SKYBOX_MODE; + } + hdrSkyboxMaterial.microSurface = 1.0 - blur; + hdrSkyboxMaterial.disableLighting = true; + hdrSkyboxMaterial.twoSidedLighting = true; + hdrSkybox.infiniteDistance = true; + hdrSkybox.material = hdrSkyboxMaterial; + } + else { + var skyboxMaterial = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_5__["StandardMaterial"]("skyBox", this); + skyboxMaterial.backFaceCulling = false; + skyboxMaterial.reflectionTexture = environmentTexture.clone(); + if (skyboxMaterial.reflectionTexture) { + skyboxMaterial.reflectionTexture.coordinatesMode = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].SKYBOX_MODE; + } + skyboxMaterial.disableLighting = true; + hdrSkybox.infiniteDistance = true; + hdrSkybox.material = skyboxMaterial; + } + hdrSkybox.isPickable = false; + return hdrSkybox; +}; +_scene__WEBPACK_IMPORTED_MODULE_1__["Scene"].prototype.createDefaultEnvironment = function (options) { + if (_environmentHelper__WEBPACK_IMPORTED_MODULE_8__["EnvironmentHelper"]) { + return new _environmentHelper__WEBPACK_IMPORTED_MODULE_8__["EnvironmentHelper"](options, this); + } + return null; +}; +_scene__WEBPACK_IMPORTED_MODULE_1__["Scene"].prototype.createDefaultVRExperience = function (webVROptions) { + if (webVROptions === void 0) { webVROptions = {}; } + return new _Cameras_VR_vrExperienceHelper__WEBPACK_IMPORTED_MODULE_15__["VRExperienceHelper"](this, webVROptions); +}; +_scene__WEBPACK_IMPORTED_MODULE_1__["Scene"].prototype.createDefaultXRExperienceAsync = function () { + var _this = this; + return _Cameras_XR_webXRExperienceHelper__WEBPACK_IMPORTED_MODULE_14__["WebXRExperienceHelper"].CreateAsync(this).then(function (helper) { + var outputCanvas = new _Cameras_XR_webXRManagedOutputCanvas__WEBPACK_IMPORTED_MODULE_11__["WebXRManagedOutputCanvas"](helper); + return _Cameras_XR_webXREnterExitUI__WEBPACK_IMPORTED_MODULE_13__["WebXREnterExitUI"].CreateAsync(_this, helper, { outputCanvasContext: outputCanvas.canvasContext }) + .then(function (ui) { + new _Cameras_XR_webXRInput__WEBPACK_IMPORTED_MODULE_12__["WebXRInput"](helper); + return helper; + }); + }); +}; + + +/***/ }), + +/***/ "./Helpers/videoDome.ts": +/*!******************************!*\ + !*** ./Helpers/videoDome.ts ***! + \******************************/ +/*! exports provided: VideoDome */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VideoDome", function() { return VideoDome; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Meshes_transformNode__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Meshes/transformNode */ "./Meshes/transformNode.ts"); +/* harmony import */ var _Meshes_mesh__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Meshes/mesh */ "./Meshes/mesh.ts"); +/* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Materials/Textures/texture */ "./Materials/Textures/texture.ts"); +/* harmony import */ var _Materials_Textures_videoTexture__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Materials/Textures/videoTexture */ "./Materials/Textures/videoTexture.ts"); +/* harmony import */ var _Materials_Background_backgroundMaterial__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Materials/Background/backgroundMaterial */ "./Materials/Background/backgroundMaterial.ts"); +/* harmony import */ var _Meshes_Builders_sphereBuilder__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Meshes/Builders/sphereBuilder */ "./Meshes/Builders/sphereBuilder.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); + + + + + + + + +/** + * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes. + * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene. + * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere. + * Potential additions to this helper include zoom and and non-infinite distance rendering effects. + */ +var VideoDome = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](VideoDome, _super); + /** + * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh. + * @param name Element's name, child elements will append suffixes for their own names. + * @param urlsOrVideo defines the url(s) or the video element to use + * @param options An object containing optional or exposed sub element properties + */ + function VideoDome(name, urlsOrVideo, options, scene) { + var _this = _super.call(this, name, scene) || this; + _this._useDirectMapping = false; + _this._videoMode = VideoDome.MODE_MONOSCOPIC; + /** + * Oberserver used in Stereoscopic VR Mode. + */ + _this._onBeforeCameraRenderObserver = null; + scene = _this.getScene(); + // set defaults and manage values + name = name || "videoDome"; + options.resolution = (Math.abs(options.resolution) | 0) || 32; + options.clickToPlay = Boolean(options.clickToPlay); + options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay); + options.loop = options.loop === undefined ? true : Boolean(options.loop); + options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000); + if (options.useDirectMapping === undefined) { + _this._useDirectMapping = true; + } + else { + _this._useDirectMapping = options.useDirectMapping; + } + if (options.faceForward === undefined) { + options.faceForward = true; + } + _this._setReady(false); + // create + var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster }; + var material = _this._material = new _Materials_Background_backgroundMaterial__WEBPACK_IMPORTED_MODULE_5__["BackgroundMaterial"](name + "_material", scene); + var texture = _this._videoTexture = new _Materials_Textures_videoTexture__WEBPACK_IMPORTED_MODULE_4__["VideoTexture"](name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_3__["Texture"].TRILINEAR_SAMPLINGMODE, tempOptions); + _this._mesh = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_2__["Mesh"].CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, _Meshes_mesh__WEBPACK_IMPORTED_MODULE_2__["Mesh"].BACKSIDE); + texture.onLoadObservable.addOnce(function () { + _this._setReady(true); + }); + // configure material + material.useEquirectangularFOV = true; + material.fovMultiplier = 1.0; + material.opacityFresnel = false; + if (_this._useDirectMapping) { + texture.wrapU = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_3__["Texture"].CLAMP_ADDRESSMODE; + texture.wrapV = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_3__["Texture"].CLAMP_ADDRESSMODE; + material.diffuseTexture = texture; + } + else { + texture.coordinatesMode = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_3__["Texture"].FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation + texture.wrapV = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_3__["Texture"].CLAMP_ADDRESSMODE; + material.reflectionTexture = texture; + } + // configure mesh + _this._mesh.material = material; + _this._mesh.parent = _this; + // optional configuration + if (options.clickToPlay) { + scene.onPointerUp = function () { + _this._videoTexture.video.play(); + }; + } + // Initial rotation + if (options.faceForward && scene.activeCamera) { + var camera = scene.activeCamera; + var forward = _Maths_math__WEBPACK_IMPORTED_MODULE_7__["Vector3"].Forward(); + var direction = _Maths_math__WEBPACK_IMPORTED_MODULE_7__["Vector3"].TransformNormal(forward, camera.getViewMatrix()); + direction.normalize(); + _this.rotation.y = Math.acos(_Maths_math__WEBPACK_IMPORTED_MODULE_7__["Vector3"].Dot(forward, direction)); + } + return _this; + } + Object.defineProperty(VideoDome.prototype, "videoTexture", { + /** + * Gets the video texture being displayed on the sphere + */ + get: function () { + return this._videoTexture; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(VideoDome.prototype, "fovMultiplier", { + /** + * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out". + * Also see the options.resolution property. + */ + get: function () { + return this._material.fovMultiplier; + }, + set: function (value) { + this._material.fovMultiplier = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(VideoDome.prototype, "videoMode", { + /** + * Gets or set the current video mode for the video. It can be: + * * VideoDome.MODE_MONOSCOPIC : Define the video source as a Monoscopic panoramic 360 video. + * * VideoDome.MODE_TOPBOTTOM : Define the video source as a Stereoscopic TopBottom/OverUnder panoramic 360 video. + * * VideoDome.MODE_SIDEBYSIDE : Define the video source as a Stereoscopic Side by Side panoramic 360 video. + */ + get: function () { + return this._videoMode; + }, + set: function (value) { + if (this._videoMode === value) { + return; + } + this._changeVideoMode(value); + }, + enumerable: true, + configurable: true + }); + VideoDome.prototype._changeVideoMode = function (value) { + var _this = this; + this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver); + this._videoMode = value; + // Default Setup and Reset. + this._videoTexture.uScale = 1; + this._videoTexture.vScale = 1; + this._videoTexture.uOffset = 0; + this._videoTexture.vOffset = 0; + switch (value) { + case VideoDome.MODE_SIDEBYSIDE: + this._videoTexture.uScale = 0.5; + this._onBeforeCameraRenderObserver = this._scene.onBeforeCameraRenderObservable.add(function (camera) { + _this._videoTexture.uOffset = camera.isRightCamera ? 0.5 : 0.0; + }); + break; + case VideoDome.MODE_TOPBOTTOM: + this._videoTexture.vScale = 0.5; + this._onBeforeCameraRenderObserver = this._scene.onBeforeCameraRenderObservable.add(function (camera) { + _this._videoTexture.vOffset = camera.isRightCamera ? 0.5 : 0.0; + }); + break; + } + }; + /** + * Releases resources associated with this node. + * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default) + * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default) + */ + VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) { + if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; } + this._videoTexture.dispose(); + this._mesh.dispose(); + this._material.dispose(); + this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver); + _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures); + }; + /** + * Define the video source as a Monoscopic panoramic 360 video. + */ + VideoDome.MODE_MONOSCOPIC = 0; + /** + * Define the video source as a Stereoscopic TopBottom/OverUnder panoramic 360 video. + */ + VideoDome.MODE_TOPBOTTOM = 1; + /** + * Define the video source as a Stereoscopic Side by Side panoramic 360 video. + */ + VideoDome.MODE_SIDEBYSIDE = 2; + return VideoDome; +}(_Meshes_transformNode__WEBPACK_IMPORTED_MODULE_1__["TransformNode"])); + + + +/***/ }), + +/***/ "./Inputs/scene.inputManager.ts": +/*!**************************************!*\ + !*** ./Inputs/scene.inputManager.ts ***! + \**************************************/ +/*! exports provided: InputManager */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InputManager", function() { return InputManager; }); +/* harmony import */ var _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Events/pointerEvents */ "./Events/pointerEvents.ts"); +/* harmony import */ var _Actions_abstractActionManager__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Actions/abstractActionManager */ "./Actions/abstractActionManager.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts"); +/* harmony import */ var _Actions_actionEvent__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Actions/actionEvent */ "./Actions/actionEvent.ts"); +/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Misc/tools */ "./Misc/tools.ts"); +/* harmony import */ var _Events_keyboardEvents__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Events/keyboardEvents */ "./Events/keyboardEvents.ts"); + + + + + + + +/** @hidden */ +var _ClickInfo = /** @class */ (function () { + function _ClickInfo() { + this._singleClick = false; + this._doubleClick = false; + this._hasSwiped = false; + this._ignore = false; + } + Object.defineProperty(_ClickInfo.prototype, "singleClick", { + get: function () { + return this._singleClick; + }, + set: function (b) { + this._singleClick = b; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(_ClickInfo.prototype, "doubleClick", { + get: function () { + return this._doubleClick; + }, + set: function (b) { + this._doubleClick = b; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(_ClickInfo.prototype, "hasSwiped", { + get: function () { + return this._hasSwiped; + }, + set: function (b) { + this._hasSwiped = b; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(_ClickInfo.prototype, "ignore", { + get: function () { + return this._ignore; + }, + set: function (b) { + this._ignore = b; + }, + enumerable: true, + configurable: true + }); + return _ClickInfo; +}()); +/** + * Class used to manage all inputs for the scene. + */ +var InputManager = /** @class */ (function () { + /** + * Creates a new InputManager + * @param scene defines the hosting scene + */ + function InputManager(scene) { + // Pointers + this._wheelEventName = ""; + this._meshPickProceed = false; + this._currentPickResult = null; + this._previousPickResult = null; + this._totalPointersPressed = 0; + this._doubleClickOccured = false; + this._pointerX = 0; + this._pointerY = 0; + this._startingPointerPosition = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector2"](0, 0); + this._previousStartingPointerPosition = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector2"](0, 0); + this._startingPointerTime = 0; + this._previousStartingPointerTime = 0; + this._pointerCaptures = {}; + this._scene = scene; + } + Object.defineProperty(InputManager.prototype, "meshUnderPointer", { + /** + * Gets the mesh that is currently under the pointer + */ + get: function () { + return this._pointerOverMesh; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(InputManager.prototype, "unTranslatedPointer", { + /** + * Gets the pointer coordinates in 2D without any translation (ie. straight out of the pointer event) + */ + get: function () { + return new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector2"](this._unTranslatedPointerX, this._unTranslatedPointerY); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(InputManager.prototype, "pointerX", { + /** + * Gets or sets the current on-screen X position of the pointer + */ + get: function () { + return this._pointerX; + }, + set: function (value) { + this._pointerX = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(InputManager.prototype, "pointerY", { + /** + * Gets or sets the current on-screen Y position of the pointer + */ + get: function () { + return this._pointerY; + }, + set: function (value) { + this._pointerY = value; + }, + enumerable: true, + configurable: true + }); + InputManager.prototype._updatePointerPosition = function (evt) { + var canvasRect = this._scene.getEngine().getRenderingCanvasClientRect(); + if (!canvasRect) { + return; + } + this._pointerX = evt.clientX - canvasRect.left; + this._pointerY = evt.clientY - canvasRect.top; + this._unTranslatedPointerX = this._pointerX; + this._unTranslatedPointerY = this._pointerY; + }; + InputManager.prototype._processPointerMove = function (pickResult, evt) { + var scene = this._scene; + var canvas = scene.getEngine().getRenderingCanvas(); + if (!canvas) { + return; + } + canvas.tabIndex = 1; + // Restore pointer + canvas.style.cursor = scene.defaultCursor; + var isMeshPicked = (pickResult && pickResult.hit && pickResult.pickedMesh) ? true : false; + if (isMeshPicked) { + scene.setPointerOverMesh(pickResult.pickedMesh); + if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) { + if (this._pointerOverMesh.actionManager.hoverCursor) { + canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor; + } + else { + canvas.style.cursor = scene.hoverCursor; + } + } + } + else { + scene.setPointerOverMesh(null); + } + for (var _i = 0, _a = scene._pointerMoveStage; _i < _a.length; _i++) { + var step = _a[_i]; + pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas); + } + if (pickResult) { + var type = evt.type === this._wheelEventName ? _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERWHEEL : _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERMOVE; + if (scene.onPointerMove) { + scene.onPointerMove(evt, pickResult, type); + } + if (scene.onPointerObservable.hasObservers()) { + var pi = new _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerInfo"](type, evt, pickResult); + this._setRayOnPointerInfo(pi); + scene.onPointerObservable.notifyObservers(pi, type); + } + } + }; + // Pointers handling + InputManager.prototype._setRayOnPointerInfo = function (pointerInfo) { + var scene = this._scene; + if (pointerInfo.pickInfo && !pointerInfo.pickInfo._pickingUnavailable) { + if (!pointerInfo.pickInfo.ray) { + pointerInfo.pickInfo.ray = scene.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"].Identity(), scene.activeCamera); + } + } + }; + InputManager.prototype._checkPrePointerObservable = function (pickResult, evt, type) { + var scene = this._scene; + var pi = new _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerInfoPre"](type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY); + if (pickResult) { + pi.ray = pickResult.ray; + } + scene.onPrePointerObservable.notifyObservers(pi, type); + if (pi.skipOnPointerObservable) { + return true; + } + else { + return false; + } + }; + /** + * Use this method to simulate a pointer move on a mesh + * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay + * @param pickResult pickingInfo of the object wished to simulate pointer event on + * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch) + */ + InputManager.prototype.simulatePointerMove = function (pickResult, pointerEventInit) { + var evt = new PointerEvent("pointermove", pointerEventInit); + if (this._checkPrePointerObservable(pickResult, evt, _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERMOVE)) { + return; + } + this._processPointerMove(pickResult, evt); + }; + /** + * Use this method to simulate a pointer down on a mesh + * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay + * @param pickResult pickingInfo of the object wished to simulate pointer event on + * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch) + */ + InputManager.prototype.simulatePointerDown = function (pickResult, pointerEventInit) { + var evt = new PointerEvent("pointerdown", pointerEventInit); + if (this._checkPrePointerObservable(pickResult, evt, _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERDOWN)) { + return; + } + this._processPointerDown(pickResult, evt); + }; + InputManager.prototype._processPointerDown = function (pickResult, evt) { + var _this = this; + var scene = this._scene; + if (pickResult && pickResult.hit && pickResult.pickedMesh) { + this._pickedDownMesh = pickResult.pickedMesh; + var actionManager = pickResult.pickedMesh._getActionManagerForTrigger(); + if (actionManager) { + if (actionManager.hasPickTriggers) { + actionManager.processTrigger(_Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].ACTION_OnPickDownTrigger, _Actions_actionEvent__WEBPACK_IMPORTED_MODULE_4__["ActionEvent"].CreateNew(pickResult.pickedMesh, evt)); + switch (evt.button) { + case 0: + actionManager.processTrigger(_Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].ACTION_OnLeftPickTrigger, _Actions_actionEvent__WEBPACK_IMPORTED_MODULE_4__["ActionEvent"].CreateNew(pickResult.pickedMesh, evt)); + break; + case 1: + actionManager.processTrigger(_Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].ACTION_OnCenterPickTrigger, _Actions_actionEvent__WEBPACK_IMPORTED_MODULE_4__["ActionEvent"].CreateNew(pickResult.pickedMesh, evt)); + break; + case 2: + actionManager.processTrigger(_Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].ACTION_OnRightPickTrigger, _Actions_actionEvent__WEBPACK_IMPORTED_MODULE_4__["ActionEvent"].CreateNew(pickResult.pickedMesh, evt)); + break; + } + } + if (actionManager.hasSpecificTrigger(_Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].ACTION_OnLongPressTrigger)) { + window.setTimeout(function () { + var pickResult = scene.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, function (mesh) { return (mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(_Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].ACTION_OnLongPressTrigger) && mesh == _this._pickedDownMesh); }, false, scene.cameraToUseForPointers); + if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) { + if (_this._totalPointersPressed !== 0 && + ((Date.now() - _this._startingPointerTime) > InputManager.LongPressDelay) && + !_this._isPointerSwiping()) { + _this._startingPointerTime = 0; + actionManager.processTrigger(_Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].ACTION_OnLongPressTrigger, _Actions_actionEvent__WEBPACK_IMPORTED_MODULE_4__["ActionEvent"].CreateNew(pickResult.pickedMesh, evt)); + } + } + }, InputManager.LongPressDelay); + } + } + } + else { + for (var _i = 0, _a = scene._pointerDownStage; _i < _a.length; _i++) { + var step = _a[_i]; + pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt); + } + } + if (pickResult) { + var type = _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERDOWN; + if (scene.onPointerDown) { + scene.onPointerDown(evt, pickResult, type); + } + if (scene.onPointerObservable.hasObservers()) { + var pi = new _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerInfo"](type, evt, pickResult); + this._setRayOnPointerInfo(pi); + scene.onPointerObservable.notifyObservers(pi, type); + } + } + }; + /** @hidden */ + InputManager.prototype._isPointerSwiping = function () { + return Math.abs(this._startingPointerPosition.x - this._pointerX) > InputManager.DragMovementThreshold || + Math.abs(this._startingPointerPosition.y - this._pointerY) > InputManager.DragMovementThreshold; + }; + /** + * Use this method to simulate a pointer up on a mesh + * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay + * @param pickResult pickingInfo of the object wished to simulate pointer event on + * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch) + * @param doubleTap indicates that the pointer up event should be considered as part of a double click (false by default) + */ + InputManager.prototype.simulatePointerUp = function (pickResult, pointerEventInit, doubleTap) { + var evt = new PointerEvent("pointerup", pointerEventInit); + var clickInfo = new _ClickInfo(); + if (doubleTap) { + clickInfo.doubleClick = true; + } + else { + clickInfo.singleClick = true; + } + if (this._checkPrePointerObservable(pickResult, evt, _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERUP)) { + return; + } + this._processPointerUp(pickResult, evt, clickInfo); + }; + InputManager.prototype._processPointerUp = function (pickResult, evt, clickInfo) { + var scene = this._scene; + if (pickResult && pickResult && pickResult.pickedMesh) { + this._pickedUpMesh = pickResult.pickedMesh; + if (this._pickedDownMesh === this._pickedUpMesh) { + if (scene.onPointerPick) { + scene.onPointerPick(evt, pickResult); + } + if (clickInfo.singleClick && !clickInfo.ignore && scene.onPointerObservable.hasObservers()) { + var type_1 = _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERPICK; + var pi = new _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerInfo"](type_1, evt, pickResult); + this._setRayOnPointerInfo(pi); + scene.onPointerObservable.notifyObservers(pi, type_1); + } + } + var actionManager = pickResult.pickedMesh._getActionManagerForTrigger(); + if (actionManager && !clickInfo.ignore) { + actionManager.processTrigger(_Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].ACTION_OnPickUpTrigger, _Actions_actionEvent__WEBPACK_IMPORTED_MODULE_4__["ActionEvent"].CreateNew(pickResult.pickedMesh, evt)); + if (!clickInfo.hasSwiped && clickInfo.singleClick) { + actionManager.processTrigger(_Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].ACTION_OnPickTrigger, _Actions_actionEvent__WEBPACK_IMPORTED_MODULE_4__["ActionEvent"].CreateNew(pickResult.pickedMesh, evt)); + } + var doubleClickActionManager = pickResult.pickedMesh._getActionManagerForTrigger(_Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].ACTION_OnDoublePickTrigger); + if (clickInfo.doubleClick && doubleClickActionManager) { + doubleClickActionManager.processTrigger(_Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].ACTION_OnDoublePickTrigger, _Actions_actionEvent__WEBPACK_IMPORTED_MODULE_4__["ActionEvent"].CreateNew(pickResult.pickedMesh, evt)); + } + } + } + else { + if (!clickInfo.ignore) { + for (var _i = 0, _a = scene._pointerUpStage; _i < _a.length; _i++) { + var step = _a[_i]; + pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt); + } + } + } + if (this._pickedDownMesh && this._pickedDownMesh !== this._pickedUpMesh) { + var pickedDownActionManager = this._pickedDownMesh._getActionManagerForTrigger(_Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].ACTION_OnPickOutTrigger); + if (pickedDownActionManager) { + pickedDownActionManager.processTrigger(_Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].ACTION_OnPickOutTrigger, _Actions_actionEvent__WEBPACK_IMPORTED_MODULE_4__["ActionEvent"].CreateNew(this._pickedDownMesh, evt)); + } + } + var type = 0; + if (scene.onPointerObservable.hasObservers()) { + if (!clickInfo.ignore && !clickInfo.hasSwiped) { + if (clickInfo.singleClick && scene.onPointerObservable.hasSpecificMask(_Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERTAP)) { + type = _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERTAP; + } + else if (clickInfo.doubleClick && scene.onPointerObservable.hasSpecificMask(_Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERDOUBLETAP)) { + type = _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERDOUBLETAP; + } + if (type) { + var pi = new _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerInfo"](type, evt, pickResult); + this._setRayOnPointerInfo(pi); + scene.onPointerObservable.notifyObservers(pi, type); + } + } + if (!clickInfo.ignore) { + type = _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERUP; + var pi = new _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerInfo"](type, evt, pickResult); + this._setRayOnPointerInfo(pi); + scene.onPointerObservable.notifyObservers(pi, type); + } + } + if (scene.onPointerUp && !clickInfo.ignore) { + scene.onPointerUp(evt, pickResult, type); + } + }; + /** + * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down) + * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default) + * @returns true if the pointer was captured + */ + InputManager.prototype.isPointerCaptured = function (pointerId) { + if (pointerId === void 0) { pointerId = 0; } + return this._pointerCaptures[pointerId]; + }; + /** + * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp + * @param attachUp defines if you want to attach events to pointerup + * @param attachDown defines if you want to attach events to pointerdown + * @param attachMove defines if you want to attach events to pointermove + */ + InputManager.prototype.attachControl = function (attachUp, attachDown, attachMove) { + var _this = this; + if (attachUp === void 0) { attachUp = true; } + if (attachDown === void 0) { attachDown = true; } + if (attachMove === void 0) { attachMove = true; } + var scene = this._scene; + var canvas = scene.getEngine().getRenderingCanvas(); + if (!canvas) { + return; + } + var engine = scene.getEngine(); + this._initActionManager = function (act, clickInfo) { + if (!_this._meshPickProceed) { + var pickResult = scene.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, scene.pointerDownPredicate, false, scene.cameraToUseForPointers); + _this._currentPickResult = pickResult; + if (pickResult) { + act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh._getActionManagerForTrigger() : null; + } + _this._meshPickProceed = true; + } + return act; + }; + this._delayedSimpleClick = function (btn, clickInfo, cb) { + // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different + if ((Date.now() - _this._previousStartingPointerTime > InputManager.DoubleClickDelay && !_this._doubleClickOccured) || + btn !== _this._previousButtonPressed) { + _this._doubleClickOccured = false; + clickInfo.singleClick = true; + clickInfo.ignore = false; + cb(clickInfo, _this._currentPickResult); + } + }; + this._initClickEvent = function (obs1, obs2, evt, cb) { + var clickInfo = new _ClickInfo(); + _this._currentPickResult = null; + var act = null; + var checkPicking = obs1.hasSpecificMask(_Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERPICK) || obs2.hasSpecificMask(_Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERPICK) + || obs1.hasSpecificMask(_Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERTAP) || obs2.hasSpecificMask(_Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERTAP) + || obs1.hasSpecificMask(_Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERDOUBLETAP) || obs2.hasSpecificMask(_Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERDOUBLETAP); + if (!checkPicking && _Actions_abstractActionManager__WEBPACK_IMPORTED_MODULE_1__["AbstractActionManager"]) { + act = _this._initActionManager(act, clickInfo); + if (act) { + checkPicking = act.hasPickTriggers; + } + } + var needToIgnoreNext = false; + if (checkPicking) { + var btn = evt.button; + clickInfo.hasSwiped = _this._isPointerSwiping(); + if (!clickInfo.hasSwiped) { + var checkSingleClickImmediately = !InputManager.ExclusiveDoubleClickMode; + if (!checkSingleClickImmediately) { + checkSingleClickImmediately = !obs1.hasSpecificMask(_Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERDOUBLETAP) && + !obs2.hasSpecificMask(_Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERDOUBLETAP); + if (checkSingleClickImmediately && !_Actions_abstractActionManager__WEBPACK_IMPORTED_MODULE_1__["AbstractActionManager"].HasSpecificTrigger(_Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].ACTION_OnDoublePickTrigger)) { + act = _this._initActionManager(act, clickInfo); + if (act) { + checkSingleClickImmediately = !act.hasSpecificTrigger(_Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].ACTION_OnDoublePickTrigger); + } + } + } + if (checkSingleClickImmediately) { + // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required + if (Date.now() - _this._previousStartingPointerTime > InputManager.DoubleClickDelay || + btn !== _this._previousButtonPressed) { + clickInfo.singleClick = true; + cb(clickInfo, _this._currentPickResult); + needToIgnoreNext = true; + } + } + // at least one double click is required to be check and exclusive double click is enabled + else { + // wait that no double click has been raised during the double click delay + _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout; + _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), InputManager.DoubleClickDelay); + } + var checkDoubleClick = obs1.hasSpecificMask(_Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERDOUBLETAP) || + obs2.hasSpecificMask(_Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERDOUBLETAP); + if (!checkDoubleClick && _Actions_abstractActionManager__WEBPACK_IMPORTED_MODULE_1__["AbstractActionManager"].HasSpecificTrigger(_Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].ACTION_OnDoublePickTrigger)) { + act = _this._initActionManager(act, clickInfo); + if (act) { + checkDoubleClick = act.hasSpecificTrigger(_Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].ACTION_OnDoublePickTrigger); + } + } + if (checkDoubleClick) { + // two successive keys pressed are equal, double click delay is not over and double click has not just occurred + if (btn === _this._previousButtonPressed && + Date.now() - _this._previousStartingPointerTime < InputManager.DoubleClickDelay && + !_this._doubleClickOccured) { + // pointer has not moved for 2 clicks, it's a double click + if (!clickInfo.hasSwiped && + !_this._isPointerSwiping()) { + _this._previousStartingPointerTime = 0; + _this._doubleClickOccured = true; + clickInfo.doubleClick = true; + clickInfo.ignore = false; + if (InputManager.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) { + clearTimeout(_this._previousDelayedSimpleClickTimeout); + } + _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout; + cb(clickInfo, _this._currentPickResult); + } + // if the two successive clicks are too far, it's just two simple clicks + else { + _this._doubleClickOccured = false; + _this._previousStartingPointerTime = _this._startingPointerTime; + _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x; + _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y; + _this._previousButtonPressed = btn; + if (InputManager.ExclusiveDoubleClickMode) { + if (_this._previousDelayedSimpleClickTimeout) { + clearTimeout(_this._previousDelayedSimpleClickTimeout); + } + _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout; + cb(clickInfo, _this._previousPickResult); + } + else { + cb(clickInfo, _this._currentPickResult); + } + } + needToIgnoreNext = true; + } + // just the first click of the double has been raised + else { + _this._doubleClickOccured = false; + _this._previousStartingPointerTime = _this._startingPointerTime; + _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x; + _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y; + _this._previousButtonPressed = btn; + } + } + } + } + if (!needToIgnoreNext) { + cb(clickInfo, _this._currentPickResult); + } + }; + this._onPointerMove = function (evt) { + _this._updatePointerPosition(evt); + // PreObservable support + if (_this._checkPrePointerObservable(null, evt, evt.type === _this._wheelEventName ? _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERWHEEL : _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERMOVE)) { + return; + } + if (!scene.cameraToUseForPointers && !scene.activeCamera) { + return; + } + if (!scene.pointerMovePredicate) { + scene.pointerMovePredicate = function (mesh) { return (mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || scene.constantlyUpdateMeshUnderPointer || (mesh._getActionManagerForTrigger() != null)) && (!scene.cameraToUseForPointers || (scene.cameraToUseForPointers.layerMask & mesh.layerMask) !== 0)); }; + } + // Meshes + var pickResult = scene.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, scene.pointerMovePredicate, false, scene.cameraToUseForPointers); + _this._processPointerMove(pickResult, evt); + }; + this._onPointerDown = function (evt) { + _this._totalPointersPressed++; + _this._pickedDownMesh = null; + _this._meshPickProceed = false; + _this._updatePointerPosition(evt); + if (scene.preventDefaultOnPointerDown && canvas) { + evt.preventDefault(); + canvas.focus(); + } + _this._startingPointerPosition.x = _this._pointerX; + _this._startingPointerPosition.y = _this._pointerY; + _this._startingPointerTime = Date.now(); + // PreObservable support + if (_this._checkPrePointerObservable(null, evt, _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERDOWN)) { + return; + } + if (!scene.cameraToUseForPointers && !scene.activeCamera) { + return; + } + _this._pointerCaptures[evt.pointerId] = true; + if (!scene.pointerDownPredicate) { + scene.pointerDownPredicate = function (mesh) { + return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (!scene.cameraToUseForPointers || (scene.cameraToUseForPointers.layerMask & mesh.layerMask) !== 0); + }; + } + // Meshes + _this._pickedDownMesh = null; + var pickResult = scene.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, scene.pointerDownPredicate, false, scene.cameraToUseForPointers); + _this._processPointerDown(pickResult, evt); + }; + this._onPointerUp = function (evt) { + if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF + return; // So we need to test it the pointer down was pressed before. + } + _this._totalPointersPressed--; + _this._pickedUpMesh = null; + _this._meshPickProceed = false; + _this._updatePointerPosition(evt); + if (scene.preventDefaultOnPointerUp && canvas) { + evt.preventDefault(); + canvas.focus(); + } + _this._initClickEvent(scene.onPrePointerObservable, scene.onPointerObservable, evt, function (clickInfo, pickResult) { + // PreObservable support + if (scene.onPrePointerObservable.hasObservers()) { + if (!clickInfo.ignore) { + if (!clickInfo.hasSwiped) { + if (clickInfo.singleClick && scene.onPrePointerObservable.hasSpecificMask(_Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERTAP)) { + if (_this._checkPrePointerObservable(null, evt, _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERTAP)) { + return; + } + } + if (clickInfo.doubleClick && scene.onPrePointerObservable.hasSpecificMask(_Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERDOUBLETAP)) { + if (_this._checkPrePointerObservable(null, evt, _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERDOUBLETAP)) { + return; + } + } + } + if (_this._checkPrePointerObservable(null, evt, _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERUP)) { + return; + } + } + } + if (!_this._pointerCaptures[evt.pointerId]) { + return; + } + _this._pointerCaptures[evt.pointerId] = false; + if (!scene.cameraToUseForPointers && !scene.activeCamera) { + return; + } + if (!scene.pointerUpPredicate) { + scene.pointerUpPredicate = function (mesh) { + return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (!scene.cameraToUseForPointers || (scene.cameraToUseForPointers.layerMask & mesh.layerMask) !== 0); + }; + } + // Meshes + if (!_this._meshPickProceed && (_Actions_abstractActionManager__WEBPACK_IMPORTED_MODULE_1__["AbstractActionManager"] && _Actions_abstractActionManager__WEBPACK_IMPORTED_MODULE_1__["AbstractActionManager"].HasTriggers || scene.onPointerObservable.hasObservers())) { + _this._initActionManager(null, clickInfo); + } + if (!pickResult) { + pickResult = _this._currentPickResult; + } + _this._processPointerUp(pickResult, evt, clickInfo); + _this._previousPickResult = _this._currentPickResult; + }); + }; + this._onKeyDown = function (evt) { + var type = _Events_keyboardEvents__WEBPACK_IMPORTED_MODULE_6__["KeyboardEventTypes"].KEYDOWN; + if (scene.onPreKeyboardObservable.hasObservers()) { + var pi = new _Events_keyboardEvents__WEBPACK_IMPORTED_MODULE_6__["KeyboardInfoPre"](type, evt); + scene.onPreKeyboardObservable.notifyObservers(pi, type); + if (pi.skipOnPointerObservable) { + return; + } + } + if (scene.onKeyboardObservable.hasObservers()) { + var pi = new _Events_keyboardEvents__WEBPACK_IMPORTED_MODULE_6__["KeyboardInfo"](type, evt); + scene.onKeyboardObservable.notifyObservers(pi, type); + } + if (scene.actionManager) { + scene.actionManager.processTrigger(_Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].ACTION_OnKeyDownTrigger, _Actions_actionEvent__WEBPACK_IMPORTED_MODULE_4__["ActionEvent"].CreateNewFromScene(scene, evt)); + } + }; + this._onKeyUp = function (evt) { + var type = _Events_keyboardEvents__WEBPACK_IMPORTED_MODULE_6__["KeyboardEventTypes"].KEYUP; + if (scene.onPreKeyboardObservable.hasObservers()) { + var pi = new _Events_keyboardEvents__WEBPACK_IMPORTED_MODULE_6__["KeyboardInfoPre"](type, evt); + scene.onPreKeyboardObservable.notifyObservers(pi, type); + if (pi.skipOnPointerObservable) { + return; + } + } + if (scene.onKeyboardObservable.hasObservers()) { + var pi = new _Events_keyboardEvents__WEBPACK_IMPORTED_MODULE_6__["KeyboardInfo"](type, evt); + scene.onKeyboardObservable.notifyObservers(pi, type); + } + if (scene.actionManager) { + scene.actionManager.processTrigger(_Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].ACTION_OnKeyUpTrigger, _Actions_actionEvent__WEBPACK_IMPORTED_MODULE_4__["ActionEvent"].CreateNewFromScene(scene, evt)); + } + }; + // Keyboard events + this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add((function () { + var fn = function () { + if (!canvas) { + return; + } + canvas.addEventListener("keydown", _this._onKeyDown, false); + canvas.addEventListener("keyup", _this._onKeyUp, false); + }; + if (document.activeElement === canvas) { + fn(); + } + return fn; + })()); + this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () { + if (!canvas) { + return; + } + canvas.removeEventListener("keydown", _this._onKeyDown); + canvas.removeEventListener("keyup", _this._onKeyUp); + }); + // Pointer events + var eventPrefix = _Misc_tools__WEBPACK_IMPORTED_MODULE_5__["Tools"].GetPointerPrefix(); + if (attachMove) { + canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false); + // Wheel + this._wheelEventName = "onwheel" in document.createElement("div") ? "wheel" : // Modern browsers support "wheel" + document.onmousewheel !== undefined ? "mousewheel" : // Webkit and IE support at least "mousewheel" + "DOMMouseScroll"; // let's assume that remaining browsers are older Firefox + canvas.addEventListener(this._wheelEventName, this._onPointerMove, false); + } + if (attachDown) { + canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false); + } + if (attachUp) { + window.addEventListener(eventPrefix + "up", this._onPointerUp, false); + } + }; + /** + * Detaches all event handlers + */ + InputManager.prototype.detachControl = function () { + var eventPrefix = _Misc_tools__WEBPACK_IMPORTED_MODULE_5__["Tools"].GetPointerPrefix(); + var canvas = this._scene.getEngine().getRenderingCanvas(); + var engine = this._scene.getEngine(); + if (!canvas) { + return; + } + // Pointer + canvas.removeEventListener(eventPrefix + "move", this._onPointerMove); + canvas.removeEventListener(eventPrefix + "down", this._onPointerDown); + window.removeEventListener(eventPrefix + "up", this._onPointerUp); + // Blur / Focus + if (this._onCanvasBlurObserver) { + engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver); + } + if (this._onCanvasFocusObserver) { + engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver); + } + // Keyboard + canvas.removeEventListener("keydown", this._onKeyDown); + canvas.removeEventListener("keyup", this._onKeyUp); + // Cursor + canvas.style.cursor = this._scene.defaultCursor; + }; + /** + * Force the value of meshUnderPointer + * @param mesh defines the mesh to use + */ + InputManager.prototype.setPointerOverMesh = function (mesh) { + if (this._pointerOverMesh === mesh) { + return; + } + var actionManager; + if (this._pointerOverMesh) { + actionManager = this._pointerOverMesh._getActionManagerForTrigger(_Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].ACTION_OnPointerOutTrigger); + if (actionManager) { + actionManager.processTrigger(_Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].ACTION_OnPointerOutTrigger, _Actions_actionEvent__WEBPACK_IMPORTED_MODULE_4__["ActionEvent"].CreateNew(this._pointerOverMesh)); + } + } + this._pointerOverMesh = mesh; + if (this._pointerOverMesh) { + actionManager = this._pointerOverMesh._getActionManagerForTrigger(_Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].ACTION_OnPointerOverTrigger); + if (actionManager) { + actionManager.processTrigger(_Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].ACTION_OnPointerOverTrigger, _Actions_actionEvent__WEBPACK_IMPORTED_MODULE_4__["ActionEvent"].CreateNew(this._pointerOverMesh)); + } + } + }; + /** + * Gets the mesh under the pointer + * @returns a Mesh or null if no mesh is under the pointer + */ + InputManager.prototype.getPointerOverMesh = function () { + return this._pointerOverMesh; + }; + /** The distance in pixel that you have to move to prevent some events */ + InputManager.DragMovementThreshold = 10; // in pixels + /** Time in milliseconds to wait to raise long press events if button is still pressed */ + InputManager.LongPressDelay = 500; // in milliseconds + /** Time in milliseconds with two consecutive clicks will be considered as a double click */ + InputManager.DoubleClickDelay = 300; // in milliseconds + /** If you need to check double click without raising a single click at first click, enable this flag */ + InputManager.ExclusiveDoubleClickMode = false; + return InputManager; +}()); + + + +/***/ }), + +/***/ "./Instrumentation/engineInstrumentation.ts": +/*!**************************************************!*\ + !*** ./Instrumentation/engineInstrumentation.ts ***! + \**************************************************/ +/*! exports provided: EngineInstrumentation */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EngineInstrumentation", function() { return EngineInstrumentation; }); +/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/tools */ "./Misc/tools.ts"); + +/** + * This class can be used to get instrumentation data from a Babylon engine + * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation + */ +var EngineInstrumentation = /** @class */ (function () { + /** + * Instantiates a new engine instrumentation. + * This class can be used to get instrumentation data from a Babylon engine + * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation + * @param engine Defines the engine to instrument + */ + function EngineInstrumentation( + /** + * Define the instrumented engine. + */ + engine) { + this.engine = engine; + this._captureGPUFrameTime = false; + this._gpuFrameTime = new _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["PerfCounter"](); + this._captureShaderCompilationTime = false; + this._shaderCompilationTime = new _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["PerfCounter"](); + // Observers + this._onBeginFrameObserver = null; + this._onEndFrameObserver = null; + this._onBeforeShaderCompilationObserver = null; + this._onAfterShaderCompilationObserver = null; + } + Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", { + // Properties + /** + * Gets the perf counter used for GPU frame time + */ + get: function () { + return this._gpuFrameTime; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", { + /** + * Gets the GPU frame time capture status + */ + get: function () { + return this._captureGPUFrameTime; + }, + /** + * Enable or disable the GPU frame time capture + */ + set: function (value) { + var _this = this; + if (value === this._captureGPUFrameTime) { + return; + } + this._captureGPUFrameTime = value; + if (value) { + this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () { + if (!_this._gpuFrameTimeToken) { + _this._gpuFrameTimeToken = _this.engine.startTimeQuery(); + } + }); + this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () { + if (!_this._gpuFrameTimeToken) { + return; + } + var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken); + if (time > -1) { + _this._gpuFrameTimeToken = null; + _this._gpuFrameTime.fetchNewFrame(); + _this._gpuFrameTime.addCount(time, true); + } + }); + } + else { + this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver); + this._onBeginFrameObserver = null; + this.engine.onEndFrameObservable.remove(this._onEndFrameObserver); + this._onEndFrameObserver = null; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", { + /** + * Gets the perf counter used for shader compilation time + */ + get: function () { + return this._shaderCompilationTime; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", { + /** + * Gets the shader compilation time capture status + */ + get: function () { + return this._captureShaderCompilationTime; + }, + /** + * Enable or disable the shader compilation time capture + */ + set: function (value) { + var _this = this; + if (value === this._captureShaderCompilationTime) { + return; + } + this._captureShaderCompilationTime = value; + if (value) { + this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () { + _this._shaderCompilationTime.fetchNewFrame(); + _this._shaderCompilationTime.beginMonitoring(); + }); + this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () { + _this._shaderCompilationTime.endMonitoring(); + }); + } + else { + this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver); + this._onBeforeShaderCompilationObserver = null; + this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver); + this._onAfterShaderCompilationObserver = null; + } + }, + enumerable: true, + configurable: true + }); + /** + * Dispose and release associated resources. + */ + EngineInstrumentation.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; + }; + return EngineInstrumentation; +}()); + + + +/***/ }), + +/***/ "./Instrumentation/index.ts": +/*!**********************************!*\ + !*** ./Instrumentation/index.ts ***! + \**********************************/ +/*! exports provided: EngineInstrumentation, SceneInstrumentation, _TimeToken */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _engineInstrumentation__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./engineInstrumentation */ "./Instrumentation/engineInstrumentation.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EngineInstrumentation", function() { return _engineInstrumentation__WEBPACK_IMPORTED_MODULE_0__["EngineInstrumentation"]; }); + +/* harmony import */ var _sceneInstrumentation__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./sceneInstrumentation */ "./Instrumentation/sceneInstrumentation.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SceneInstrumentation", function() { return _sceneInstrumentation__WEBPACK_IMPORTED_MODULE_1__["SceneInstrumentation"]; }); + +/* harmony import */ var _timeToken__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./timeToken */ "./Instrumentation/timeToken.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_TimeToken", function() { return _timeToken__WEBPACK_IMPORTED_MODULE_2__["_TimeToken"]; }); + + + + + + +/***/ }), + +/***/ "./Instrumentation/sceneInstrumentation.ts": +/*!*************************************************!*\ + !*** ./Instrumentation/sceneInstrumentation.ts ***! + \*************************************************/ +/*! exports provided: SceneInstrumentation */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SceneInstrumentation", function() { return SceneInstrumentation; }); +/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/tools */ "./Misc/tools.ts"); + +/** + * This class can be used to get instrumentation data from a Babylon engine + * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation + */ +var SceneInstrumentation = /** @class */ (function () { + /** + * Instantiates a new scene instrumentation. + * This class can be used to get instrumentation data from a Babylon engine + * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation + * @param scene Defines the scene to instrument + */ + function SceneInstrumentation( + /** + * Defines the scene to instrument + */ + scene) { + var _this = this; + this.scene = scene; + this._captureActiveMeshesEvaluationTime = false; + this._activeMeshesEvaluationTime = new _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["PerfCounter"](); + this._captureRenderTargetsRenderTime = false; + this._renderTargetsRenderTime = new _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["PerfCounter"](); + this._captureFrameTime = false; + this._frameTime = new _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["PerfCounter"](); + this._captureRenderTime = false; + this._renderTime = new _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["PerfCounter"](); + this._captureInterFrameTime = false; + this._interFrameTime = new _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["PerfCounter"](); + this._captureParticlesRenderTime = false; + this._particlesRenderTime = new _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["PerfCounter"](); + this._captureSpritesRenderTime = false; + this._spritesRenderTime = new _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["PerfCounter"](); + this._capturePhysicsTime = false; + this._physicsTime = new _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["PerfCounter"](); + this._captureAnimationsTime = false; + this._animationsTime = new _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["PerfCounter"](); + this._captureCameraRenderTime = false; + this._cameraRenderTime = new _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["PerfCounter"](); + // Observers + this._onBeforeActiveMeshesEvaluationObserver = null; + this._onAfterActiveMeshesEvaluationObserver = null; + this._onBeforeRenderTargetsRenderObserver = null; + this._onAfterRenderTargetsRenderObserver = null; + this._onAfterRenderObserver = null; + this._onBeforeDrawPhaseObserver = null; + this._onAfterDrawPhaseObserver = null; + this._onBeforeAnimationsObserver = null; + this._onBeforeParticlesRenderingObserver = null; + this._onAfterParticlesRenderingObserver = null; + this._onBeforeSpritesRenderingObserver = null; + this._onAfterSpritesRenderingObserver = null; + this._onBeforePhysicsObserver = null; + this._onAfterPhysicsObserver = null; + this._onAfterAnimationsObserver = null; + this._onBeforeCameraRenderObserver = null; + this._onAfterCameraRenderObserver = null; + // Before render + this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () { + if (_this._captureActiveMeshesEvaluationTime) { + _this._activeMeshesEvaluationTime.fetchNewFrame(); + } + if (_this._captureRenderTargetsRenderTime) { + _this._renderTargetsRenderTime.fetchNewFrame(); + } + if (_this._captureFrameTime) { + _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].StartPerformanceCounter("Scene rendering"); + _this._frameTime.beginMonitoring(); + } + if (_this._captureInterFrameTime) { + _this._interFrameTime.endMonitoring(); + } + if (_this._captureParticlesRenderTime) { + _this._particlesRenderTime.fetchNewFrame(); + } + if (_this._captureSpritesRenderTime) { + _this._spritesRenderTime.fetchNewFrame(); + } + if (_this._captureAnimationsTime) { + _this._animationsTime.beginMonitoring(); + } + _this.scene.getEngine()._drawCalls.fetchNewFrame(); + }); + // After render + this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () { + if (_this._captureFrameTime) { + _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].EndPerformanceCounter("Scene rendering"); + _this._frameTime.endMonitoring(); + } + if (_this._captureRenderTime) { + _this._renderTime.endMonitoring(false); + } + if (_this._captureInterFrameTime) { + _this._interFrameTime.beginMonitoring(); + } + }); + } + Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", { + // Properties + /** + * Gets the perf counter used for active meshes evaluation time + */ + get: function () { + return this._activeMeshesEvaluationTime; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", { + /** + * Gets the active meshes evaluation time capture status + */ + get: function () { + return this._captureActiveMeshesEvaluationTime; + }, + /** + * Enable or disable the active meshes evaluation time capture + */ + set: function (value) { + var _this = this; + if (value === this._captureActiveMeshesEvaluationTime) { + return; + } + this._captureActiveMeshesEvaluationTime = value; + if (value) { + this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () { + _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].StartPerformanceCounter("Active meshes evaluation"); + _this._activeMeshesEvaluationTime.beginMonitoring(); + }); + this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () { + _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].EndPerformanceCounter("Active meshes evaluation"); + _this._activeMeshesEvaluationTime.endMonitoring(); + }); + } + else { + this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver); + this._onBeforeActiveMeshesEvaluationObserver = null; + this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver); + this._onAfterActiveMeshesEvaluationObserver = null; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", { + /** + * Gets the perf counter used for render targets render time + */ + get: function () { + return this._renderTargetsRenderTime; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", { + /** + * Gets the render targets render time capture status + */ + get: function () { + return this._captureRenderTargetsRenderTime; + }, + /** + * Enable or disable the render targets render time capture + */ + set: function (value) { + var _this = this; + if (value === this._captureRenderTargetsRenderTime) { + return; + } + this._captureRenderTargetsRenderTime = value; + if (value) { + this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () { + _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].StartPerformanceCounter("Render targets rendering"); + _this._renderTargetsRenderTime.beginMonitoring(); + }); + this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () { + _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].EndPerformanceCounter("Render targets rendering"); + _this._renderTargetsRenderTime.endMonitoring(false); + }); + } + else { + this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver); + this._onBeforeRenderTargetsRenderObserver = null; + this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver); + this._onAfterRenderTargetsRenderObserver = null; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", { + /** + * Gets the perf counter used for particles render time + */ + get: function () { + return this._particlesRenderTime; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", { + /** + * Gets the particles render time capture status + */ + get: function () { + return this._captureParticlesRenderTime; + }, + /** + * Enable or disable the particles render time capture + */ + set: function (value) { + var _this = this; + if (value === this._captureParticlesRenderTime) { + return; + } + this._captureParticlesRenderTime = value; + if (value) { + this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () { + _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].StartPerformanceCounter("Particles"); + _this._particlesRenderTime.beginMonitoring(); + }); + this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () { + _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].EndPerformanceCounter("Particles"); + _this._particlesRenderTime.endMonitoring(false); + }); + } + else { + this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver); + this._onBeforeParticlesRenderingObserver = null; + this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver); + this._onAfterParticlesRenderingObserver = null; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", { + /** + * Gets the perf counter used for sprites render time + */ + get: function () { + return this._spritesRenderTime; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", { + /** + * Gets the sprites render time capture status + */ + get: function () { + return this._captureSpritesRenderTime; + }, + /** + * Enable or disable the sprites render time capture + */ + set: function (value) { + var _this = this; + if (value === this._captureSpritesRenderTime) { + return; + } + this._captureSpritesRenderTime = value; + if (!this.scene.spriteManagers) { + return; + } + if (value) { + this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () { + _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].StartPerformanceCounter("Sprites"); + _this._spritesRenderTime.beginMonitoring(); + }); + this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () { + _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].EndPerformanceCounter("Sprites"); + _this._spritesRenderTime.endMonitoring(false); + }); + } + else { + this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver); + this._onBeforeSpritesRenderingObserver = null; + this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver); + this._onAfterSpritesRenderingObserver = null; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", { + /** + * Gets the perf counter used for physics time + */ + get: function () { + return this._physicsTime; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", { + /** + * Gets the physics time capture status + */ + get: function () { + return this._capturePhysicsTime; + }, + /** + * Enable or disable the physics time capture + */ + set: function (value) { + var _this = this; + if (value === this._capturePhysicsTime) { + return; + } + if (!this.scene.onBeforePhysicsObservable) { + return; + } + this._capturePhysicsTime = value; + if (value) { + this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () { + _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].StartPerformanceCounter("Physics"); + _this._physicsTime.beginMonitoring(); + }); + this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () { + _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].EndPerformanceCounter("Physics"); + _this._physicsTime.endMonitoring(); + }); + } + else { + this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver); + this._onBeforePhysicsObserver = null; + this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver); + this._onAfterPhysicsObserver = null; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", { + /** + * Gets the perf counter used for animations time + */ + get: function () { + return this._animationsTime; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", { + /** + * Gets the animations time capture status + */ + get: function () { + return this._captureAnimationsTime; + }, + /** + * Enable or disable the animations time capture + */ + set: function (value) { + var _this = this; + if (value === this._captureAnimationsTime) { + return; + } + this._captureAnimationsTime = value; + if (value) { + this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () { + _this._animationsTime.endMonitoring(); + }); + } + else { + this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver); + this._onAfterAnimationsObserver = null; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", { + /** + * Gets the perf counter used for frame time capture + */ + get: function () { + return this._frameTime; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", { + /** + * Gets the frame time capture status + */ + get: function () { + return this._captureFrameTime; + }, + /** + * Enable or disable the frame time capture + */ + set: function (value) { + this._captureFrameTime = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", { + /** + * Gets the perf counter used for inter-frames time capture + */ + get: function () { + return this._interFrameTime; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", { + /** + * Gets the inter-frames time capture status + */ + get: function () { + return this._captureInterFrameTime; + }, + /** + * Enable or disable the inter-frames time capture + */ + set: function (value) { + this._captureInterFrameTime = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", { + /** + * Gets the perf counter used for render time capture + */ + get: function () { + return this._renderTime; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", { + /** + * Gets the render time capture status + */ + get: function () { + return this._captureRenderTime; + }, + /** + * Enable or disable the render time capture + */ + set: function (value) { + var _this = this; + if (value === this._captureRenderTime) { + return; + } + this._captureRenderTime = value; + if (value) { + this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () { + _this._renderTime.beginMonitoring(); + _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].StartPerformanceCounter("Main render"); + }); + this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () { + _this._renderTime.endMonitoring(false); + _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].EndPerformanceCounter("Main render"); + }); + } + else { + this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver); + this._onBeforeDrawPhaseObserver = null; + this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver); + this._onAfterDrawPhaseObserver = null; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", { + /** + * Gets the perf counter used for camera render time capture + */ + get: function () { + return this._cameraRenderTime; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", { + /** + * Gets the camera render time capture status + */ + get: function () { + return this._captureCameraRenderTime; + }, + /** + * Enable or disable the camera render time capture + */ + set: function (value) { + var _this = this; + if (value === this._captureCameraRenderTime) { + return; + } + this._captureCameraRenderTime = value; + if (value) { + this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) { + _this._cameraRenderTime.beginMonitoring(); + _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].StartPerformanceCounter("Rendering camera " + camera.name); + }); + this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) { + _this._cameraRenderTime.endMonitoring(false); + _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].EndPerformanceCounter("Rendering camera " + camera.name); + }); + } + else { + this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver); + this._onBeforeCameraRenderObserver = null; + this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver); + this._onAfterCameraRenderObserver = null; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", { + /** + * Gets the perf counter used for draw calls + */ + get: function () { + return this.scene.getEngine()._drawCalls; + }, + enumerable: true, + configurable: true + }); + /** + * Dispose and release associated resources. + */ + SceneInstrumentation.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; + if (this._onBeforeSpritesRenderingObserver) { + this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver); + this._onBeforeSpritesRenderingObserver = null; + } + if (this._onAfterSpritesRenderingObserver) { + this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver); + this._onAfterSpritesRenderingObserver = null; + } + this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver); + this._onBeforeDrawPhaseObserver = null; + this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver); + this._onAfterDrawPhaseObserver = null; + if (this._onBeforePhysicsObserver) { + this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver); + this._onBeforePhysicsObserver = null; + } + if (this._onAfterPhysicsObserver) { + this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver); + this._onAfterPhysicsObserver = null; + } + this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver); + this._onAfterAnimationsObserver = null; + this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver); + this._onBeforeCameraRenderObserver = null; + this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver); + this._onAfterCameraRenderObserver = null; + this.scene = null; + }; + return SceneInstrumentation; +}()); + + + +/***/ }), + +/***/ "./Instrumentation/timeToken.ts": +/*!**************************************!*\ + !*** ./Instrumentation/timeToken.ts ***! + \**************************************/ +/*! exports provided: _TimeToken */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_TimeToken", function() { return _TimeToken; }); +/** + * @hidden + **/ +var _TimeToken = /** @class */ (function () { + function _TimeToken() { + this._timeElapsedQueryEnded = false; + } + return _TimeToken; +}()); + + + +/***/ }), + +/***/ "./Layers/effectLayer.ts": +/*!*******************************!*\ + !*** ./Layers/effectLayer.ts ***! + \*******************************/ +/*! exports provided: EffectLayer */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EffectLayer", function() { return EffectLayer; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/tools */ "./Misc/tools.ts"); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Engines_engineStore__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Engines/engineStore */ "./Engines/engineStore.ts"); +/* harmony import */ var _Meshes_buffer__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Meshes/buffer */ "./Meshes/buffer.ts"); +/* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Materials/Textures/texture */ "./Materials/Textures/texture.ts"); +/* harmony import */ var _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Materials/Textures/renderTargetTexture */ "./Materials/Textures/renderTargetTexture.ts"); +/* harmony import */ var _Materials_material__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Materials/material */ "./Materials/material.ts"); +/* harmony import */ var _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../Materials/materialHelper */ "./Materials/materialHelper.ts"); +/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts"); +/* harmony import */ var _Shaders_glowMapGeneration_fragment__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../Shaders/glowMapGeneration.fragment */ "./Shaders/glowMapGeneration.fragment.ts"); +/* harmony import */ var _Shaders_glowMapGeneration_vertex__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../Shaders/glowMapGeneration.vertex */ "./Shaders/glowMapGeneration.vertex.ts"); +/* harmony import */ var _Misc_devTools__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../Misc/devTools */ "./Misc/devTools.ts"); + + + + + + + + + + + + + + + +/** + * The effect layer Helps adding post process effect blended with the main pass. + * + * This can be for instance use to generate glow or higlight effects on the scene. + * + * The effect layer class can not be used directly and is intented to inherited from to be + * customized per effects. + */ +var EffectLayer = /** @class */ (function () { + /** + * Instantiates a new effect Layer and references it in the scene. + * @param name The name of the layer + * @param scene The scene to use the layer in + */ + function EffectLayer( + /** The Friendly of the effect in the scene */ + name, scene) { + this._vertexBuffers = {}; + this._maxSize = 0; + this._mainTextureDesiredSize = { width: 0, height: 0 }; + this._shouldRender = true; + this._postProcesses = []; + this._textures = []; + this._emissiveTextureAndColor = { texture: null, color: new _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Color4"]() }; + /** + * The clear color of the texture used to generate the glow map. + */ + this.neutralColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Color4"](); + /** + * Specifies wether the highlight layer is enabled or not. + */ + this.isEnabled = true; + /** + * An event triggered when the effect layer has been disposed. + */ + this.onDisposeObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_3__["Observable"](); + /** + * An event triggered when the effect layer is about rendering the main texture with the glowy parts. + */ + this.onBeforeRenderMainTextureObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_3__["Observable"](); + /** + * An event triggered when the generated texture is being merged in the scene. + */ + this.onBeforeComposeObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_3__["Observable"](); + /** + * An event triggered when the generated texture has been merged in the scene. + */ + this.onAfterComposeObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_3__["Observable"](); + /** + * An event triggered when the efffect layer changes its size. + */ + this.onSizeChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_3__["Observable"](); + this.name = name; + this._scene = scene || _Engines_engineStore__WEBPACK_IMPORTED_MODULE_5__["EngineStore"].LastCreatedScene; + EffectLayer._SceneComponentInitialization(this._scene); + this._engine = this._scene.getEngine(); + this._maxSize = this._engine.getCaps().maxTextureSize; + this._scene.effectLayers.push(this); + // Generate Buffers + this._generateIndexBuffer(); + this._generateVertexBuffer(); + } + Object.defineProperty(EffectLayer.prototype, "camera", { + /** + * Gets the camera attached to the layer. + */ + get: function () { + return this._effectLayerOptions.camera; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(EffectLayer.prototype, "renderingGroupId", { + /** + * Gets the rendering group id the layer should render in. + */ + get: function () { + return this._effectLayerOptions.renderingGroupId; + }, + enumerable: true, + configurable: true + }); + /** + * Initializes the effect layer with the required options. + * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information) + */ + EffectLayer.prototype._init = function (options) { + // Adapt options + this._effectLayerOptions = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({ mainTextureRatio: 0.5, alphaBlendingMode: _Engines_constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options); + this._setMainTextureSize(); + this._createMainTexture(); + this._createTextureAndPostProcesses(); + this._mergeEffect = this._createMergeEffect(); + }; + /** + * Generates the index buffer of the full screen quad blending to the main canvas. + */ + EffectLayer.prototype._generateIndexBuffer = function () { + // Indices + var indices = []; + indices.push(0); + indices.push(1); + indices.push(2); + indices.push(0); + indices.push(2); + indices.push(3); + this._indexBuffer = this._engine.createIndexBuffer(indices); + }; + /** + * Generates the vertex buffer of the full screen quad blending to the main canvas. + */ + EffectLayer.prototype._generateVertexBuffer = function () { + // VBO + var vertices = []; + vertices.push(1, 1); + vertices.push(-1, 1); + vertices.push(-1, -1); + vertices.push(1, -1); + var vertexBuffer = new _Meshes_buffer__WEBPACK_IMPORTED_MODULE_6__["VertexBuffer"](this._engine, vertices, _Meshes_buffer__WEBPACK_IMPORTED_MODULE_6__["VertexBuffer"].PositionKind, false, false, 2); + this._vertexBuffers[_Meshes_buffer__WEBPACK_IMPORTED_MODULE_6__["VertexBuffer"].PositionKind] = vertexBuffer; + }; + /** + * Sets the main texture desired size which is the closest power of two + * of the engine canvas size. + */ + EffectLayer.prototype._setMainTextureSize = function () { + if (this._effectLayerOptions.mainTextureFixedSize) { + this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize; + this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize; + } + else { + this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio; + this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio; + this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width; + this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height; + } + this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width); + this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height); + }; + /** + * Creates the main texture for the effect layer. + */ + EffectLayer.prototype._createMainTexture = function () { + var _this = this; + this._mainTexture = new _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_8__["RenderTargetTexture"]("HighlightLayerMainRTT", { + width: this._mainTextureDesiredSize.width, + height: this._mainTextureDesiredSize.height + }, this._scene, false, true, _Engines_constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURETYPE_UNSIGNED_INT); + this._mainTexture.activeCamera = this._effectLayerOptions.camera; + this._mainTexture.wrapU = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_7__["Texture"].CLAMP_ADDRESSMODE; + this._mainTexture.wrapV = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_7__["Texture"].CLAMP_ADDRESSMODE; + this._mainTexture.anisotropicFilteringLevel = 1; + this._mainTexture.updateSamplingMode(_Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_7__["Texture"].BILINEAR_SAMPLINGMODE); + this._mainTexture.renderParticles = false; + this._mainTexture.renderList = null; + this._mainTexture.ignoreCameraViewport = true; + // Custom render function + this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) { + _this.onBeforeRenderMainTextureObservable.notifyObservers(_this); + var index; + var engine = _this._scene.getEngine(); + if (depthOnlySubMeshes.length) { + engine.setColorWrite(false); + for (index = 0; index < depthOnlySubMeshes.length; index++) { + _this._renderSubMesh(depthOnlySubMeshes.data[index]); + } + engine.setColorWrite(true); + } + for (index = 0; index < opaqueSubMeshes.length; index++) { + _this._renderSubMesh(opaqueSubMeshes.data[index]); + } + for (index = 0; index < alphaTestSubMeshes.length; index++) { + _this._renderSubMesh(alphaTestSubMeshes.data[index]); + } + var previousAlphaMode = engine.getAlphaMode(); + for (index = 0; index < transparentSubMeshes.length; index++) { + _this._renderSubMesh(transparentSubMeshes.data[index], true); + } + engine.setAlphaMode(previousAlphaMode); + }; + this._mainTexture.onClearObservable.add(function (engine) { + engine.clear(_this.neutralColor, true, true, true); + }); + }; + /** + * Adds specific effects defines. + * @param defines The defines to add specifics to. + */ + EffectLayer.prototype._addCustomEffectDefines = function (defines) { + // Nothing to add by default. + }; + /** + * Checks for the readiness of the element composing the layer. + * @param subMesh the mesh to check for + * @param useInstances specify wether or not to use instances to render the mesh + * @param emissiveTexture the associated emissive texture used to generate the glow + * @return true if ready otherwise, false + */ + EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) { + var material = subMesh.getMaterial(); + if (!material) { + return false; + } + if (!material.isReadyForSubMesh(subMesh.getMesh(), subMesh, useInstances)) { + return false; + } + var defines = []; + var attribs = [_Meshes_buffer__WEBPACK_IMPORTED_MODULE_6__["VertexBuffer"].PositionKind]; + var mesh = subMesh.getMesh(); + var uv1 = false; + var uv2 = false; + // Diffuse + if (material) { + var needAlphaTest = material.needAlphaTesting(); + var diffuseTexture = material.getAlphaTestTexture(); + var needAlphaBlendFromDiffuse = diffuseTexture && diffuseTexture.hasAlpha && + (material.useAlphaFromDiffuseTexture || material._useAlphaFromAlbedoTexture); + if (diffuseTexture && (needAlphaTest || needAlphaBlendFromDiffuse)) { + defines.push("#define DIFFUSE"); + if (mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_6__["VertexBuffer"].UV2Kind) && + diffuseTexture.coordinatesIndex === 1) { + defines.push("#define DIFFUSEUV2"); + uv2 = true; + } + else if (mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_6__["VertexBuffer"].UVKind)) { + defines.push("#define DIFFUSEUV1"); + uv1 = true; + } + if (needAlphaTest) { + defines.push("#define ALPHATEST"); + defines.push("#define ALPHATESTVALUE 0.4"); + } + } + var opacityTexture = material.opacityTexture; + if (opacityTexture) { + defines.push("#define OPACITY"); + if (mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_6__["VertexBuffer"].UV2Kind) && + opacityTexture.coordinatesIndex === 1) { + defines.push("#define OPACITYUV2"); + uv2 = true; + } + else if (mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_6__["VertexBuffer"].UVKind)) { + defines.push("#define OPACITYUV1"); + uv1 = true; + } + } + } + // Emissive + if (emissiveTexture) { + defines.push("#define EMISSIVE"); + if (mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_6__["VertexBuffer"].UV2Kind) && + emissiveTexture.coordinatesIndex === 1) { + defines.push("#define EMISSIVEUV2"); + uv2 = true; + } + else if (mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_6__["VertexBuffer"].UVKind)) { + defines.push("#define EMISSIVEUV1"); + uv1 = true; + } + } + // Vertex + if (mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_6__["VertexBuffer"].ColorKind) && mesh.hasVertexAlpha) { + attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_6__["VertexBuffer"].ColorKind); + defines.push("#define VERTEXALPHA"); + } + if (uv1) { + attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_6__["VertexBuffer"].UVKind); + defines.push("#define UV1"); + } + if (uv2) { + attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_6__["VertexBuffer"].UV2Kind); + defines.push("#define UV2"); + } + // Bones + if (mesh.useBones && mesh.computeBonesUsingShaders) { + attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_6__["VertexBuffer"].MatricesIndicesKind); + attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_6__["VertexBuffer"].MatricesWeightsKind); + if (mesh.numBoneInfluencers > 4) { + attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_6__["VertexBuffer"].MatricesIndicesExtraKind); + attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_6__["VertexBuffer"].MatricesWeightsExtraKind); + } + defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers); + defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0)); + } + else { + defines.push("#define NUM_BONE_INFLUENCERS 0"); + } + // Morph targets + var manager = mesh.morphTargetManager; + var morphInfluencers = 0; + if (manager) { + if (manager.numInfluencers > 0) { + defines.push("#define MORPHTARGETS"); + morphInfluencers = manager.numInfluencers; + defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers); + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_10__["MaterialHelper"].PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers }); + } + } + // Instances + if (useInstances) { + defines.push("#define INSTANCES"); + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_10__["MaterialHelper"].PushAttributesForInstances(attribs); + } + this._addCustomEffectDefines(defines); + // Get correct effect + var join = defines.join("\n"); + if (this._cachedDefines !== join) { + this._cachedDefines = join; + this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", + "glowColor", "morphTargetInfluences", + "diffuseMatrix", "emissiveMatrix", "opacityMatrix", "opacityIntensity"], ["diffuseSampler", "emissiveSampler", "opacitySampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers }); + } + return this._effectLayerMapGenerationEffect.isReady(); + }; + /** + * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene. + */ + EffectLayer.prototype.render = function () { + var currentEffect = this._mergeEffect; + // Check + if (!currentEffect.isReady()) { + return; + } + for (var i = 0; i < this._postProcesses.length; i++) { + if (!this._postProcesses[i].isReady()) { + return; + } + } + var engine = this._scene.getEngine(); + this.onBeforeComposeObservable.notifyObservers(this); + // Render + engine.enableEffect(currentEffect); + engine.setState(false); + // VBOs + engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect); + // Cache + var previousAlphaMode = engine.getAlphaMode(); + // Go Blend. + engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode); + // Blends the map on the main canvas. + this._internalRender(currentEffect); + // Restore Alpha + engine.setAlphaMode(previousAlphaMode); + this.onAfterComposeObservable.notifyObservers(this); + // Handle size changes. + var size = this._mainTexture.getSize(); + this._setMainTextureSize(); + if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) { + // Recreate RTT and post processes on size change. + this.onSizeChangedObservable.notifyObservers(this); + this._disposeTextureAndPostProcesses(); + this._createMainTexture(); + this._createTextureAndPostProcesses(); + } + }; + /** + * Determine if a given mesh will be used in the current effect. + * @param mesh mesh to test + * @returns true if the mesh will be used + */ + EffectLayer.prototype.hasMesh = function (mesh) { + if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) { + return true; + } + return false; + }; + /** + * Returns true if the layer contains information to display, otherwise false. + * @returns true if the glow layer should be rendered + */ + EffectLayer.prototype.shouldRender = function () { + return this.isEnabled && this._shouldRender; + }; + /** + * Returns true if the mesh should render, otherwise false. + * @param mesh The mesh to render + * @returns true if it should render otherwise false + */ + EffectLayer.prototype._shouldRenderMesh = function (mesh) { + return true; + }; + /** + * Returns true if the mesh can be rendered, otherwise false. + * @param mesh The mesh to render + * @param material The material used on the mesh + * @returns true if it can be rendered otherwise false + */ + EffectLayer.prototype._canRenderMesh = function (mesh, material) { + return !material.needAlphaBlendingForMesh(mesh); + }; + /** + * Returns true if the mesh should render, otherwise false. + * @param mesh The mesh to render + * @returns true if it should render otherwise false + */ + EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function () { + return true; + }; + /** + * Renders the submesh passed in parameter to the generation map. + */ + EffectLayer.prototype._renderSubMesh = function (subMesh, enableAlphaMode) { + var _this = this; + if (enableAlphaMode === void 0) { enableAlphaMode = false; } + if (!this.shouldRender()) { + return; + } + var material = subMesh.getMaterial(); + var mesh = subMesh.getRenderingMesh(); + var scene = this._scene; + var engine = scene.getEngine(); + mesh._internalAbstractMeshDataInfo._isActiveIntermediate = false; + if (!material) { + return; + } + // Do not block in blend mode. + if (!this._canRenderMesh(mesh, material)) { + return; + } + // Culling + engine.setState(material.backFaceCulling); + // Managing instances + var batch = mesh._getInstancesRenderList(subMesh._id); + if (batch.mustReturn) { + return; + } + // Early Exit per mesh + if (!this._shouldRenderMesh(mesh)) { + return; + } + var hardwareInstancedRendering = batch.hardwareInstancedRendering[subMesh._id]; + this._setEmissiveTextureAndColor(mesh, subMesh, material); + if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) { + engine.enableEffect(this._effectLayerMapGenerationEffect); + mesh._bind(subMesh, this._effectLayerMapGenerationEffect, _Materials_material__WEBPACK_IMPORTED_MODULE_9__["Material"].TriangleFillMode); + this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix()); + this._effectLayerMapGenerationEffect.setFloat4("glowColor", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a); + var needAlphaTest = material.needAlphaTesting(); + var diffuseTexture = material.getAlphaTestTexture(); + var needAlphaBlendFromDiffuse = diffuseTexture && diffuseTexture.hasAlpha && + (material.useAlphaFromDiffuseTexture || material._useAlphaFromAlbedoTexture); + if (diffuseTexture && (needAlphaTest || needAlphaBlendFromDiffuse)) { + this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", diffuseTexture); + var textureMatrix = diffuseTexture.getTextureMatrix(); + if (textureMatrix) { + this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix); + } + } + var opacityTexture = material.opacityTexture; + if (opacityTexture) { + this._effectLayerMapGenerationEffect.setTexture("opacitySampler", opacityTexture); + this._effectLayerMapGenerationEffect.setFloat("opacityIntensity", opacityTexture.level); + var textureMatrix = opacityTexture.getTextureMatrix(); + if (textureMatrix) { + this._effectLayerMapGenerationEffect.setMatrix("opacityMatrix", textureMatrix); + } + } + // Glow emissive only + if (this._emissiveTextureAndColor.texture) { + this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture); + this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix()); + } + // Bones + if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) { + this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh)); + } + // Morph targets + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_10__["MaterialHelper"].BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect); + // Alpha mode + if (enableAlphaMode) { + engine.setAlphaMode(material.alphaMode); + } + // Draw + mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, _Materials_material__WEBPACK_IMPORTED_MODULE_9__["Material"].TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); }); + } + else { + // Need to reset refresh rate of the main map + this._mainTexture.resetRefreshCounter(); + } + }; + /** + * Rebuild the required buffers. + * @hidden Internal use only. + */ + EffectLayer.prototype._rebuild = function () { + var vb = this._vertexBuffers[_Meshes_buffer__WEBPACK_IMPORTED_MODULE_6__["VertexBuffer"].PositionKind]; + if (vb) { + vb._rebuild(); + } + this._generateIndexBuffer(); + }; + /** + * Dispose only the render target textures and post process. + */ + EffectLayer.prototype._disposeTextureAndPostProcesses = function () { + this._mainTexture.dispose(); + for (var i = 0; i < this._postProcesses.length; i++) { + if (this._postProcesses[i]) { + this._postProcesses[i].dispose(); + } + } + this._postProcesses = []; + for (var i = 0; i < this._textures.length; i++) { + if (this._textures[i]) { + this._textures[i].dispose(); + } + } + this._textures = []; + }; + /** + * Dispose the highlight layer and free resources. + */ + EffectLayer.prototype.dispose = function () { + var vertexBuffer = this._vertexBuffers[_Meshes_buffer__WEBPACK_IMPORTED_MODULE_6__["VertexBuffer"].PositionKind]; + if (vertexBuffer) { + vertexBuffer.dispose(); + this._vertexBuffers[_Meshes_buffer__WEBPACK_IMPORTED_MODULE_6__["VertexBuffer"].PositionKind] = null; + } + if (this._indexBuffer) { + this._scene.getEngine()._releaseBuffer(this._indexBuffer); + this._indexBuffer = null; + } + // Clean textures and post processes + this._disposeTextureAndPostProcesses(); + // Remove from scene + var index = this._scene.effectLayers.indexOf(this, 0); + if (index > -1) { + this._scene.effectLayers.splice(index, 1); + } + // Callback + this.onDisposeObservable.notifyObservers(this); + this.onDisposeObservable.clear(); + this.onBeforeRenderMainTextureObservable.clear(); + this.onBeforeComposeObservable.clear(); + this.onAfterComposeObservable.clear(); + this.onSizeChangedObservable.clear(); + }; + /** + * Gets the class name of the effect layer + * @returns the string with the class name of the effect layer + */ + EffectLayer.prototype.getClassName = function () { + return "EffectLayer"; + }; + /** + * Creates an effect layer from parsed effect layer data + * @param parsedEffectLayer defines effect layer data + * @param scene defines the current scene + * @param rootUrl defines the root URL containing the effect layer information + * @returns a parsed effect Layer + */ + EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) { + var effectLayerType = _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].Instantiate(parsedEffectLayer.customType); + return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl); + }; + /** @hidden */ + EffectLayer._SceneComponentInitialization = function (_) { + throw _Misc_devTools__WEBPACK_IMPORTED_MODULE_14__["_DevTools"].WarnImport("EffectLayerSceneComponent"); + }; + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], EffectLayer.prototype, "name", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor4"])() + ], EffectLayer.prototype, "neutralColor", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], EffectLayer.prototype, "isEnabled", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsCameraReference"])() + ], EffectLayer.prototype, "camera", null); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], EffectLayer.prototype, "renderingGroupId", null); + return EffectLayer; +}()); + + + +/***/ }), + +/***/ "./Layers/effectLayerSceneComponent.ts": +/*!*********************************************!*\ + !*** ./Layers/effectLayerSceneComponent.ts ***! + \*********************************************/ +/*! exports provided: EffectLayerSceneComponent */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EffectLayerSceneComponent", function() { return EffectLayerSceneComponent; }); +/* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Cameras/camera */ "./Cameras/camera.ts"); +/* harmony import */ var _sceneComponent__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../sceneComponent */ "./sceneComponent.ts"); +/* harmony import */ var _effectLayer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./effectLayer */ "./Layers/effectLayer.ts"); +/* harmony import */ var _abstractScene__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../abstractScene */ "./abstractScene.ts"); + + + + +// Adds the parser to the scene parsers. +_abstractScene__WEBPACK_IMPORTED_MODULE_3__["AbstractScene"].AddParser(_sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) { + if (parsedData.effectLayers) { + if (!container.effectLayers) { + container.effectLayers = new Array(); + } + for (var index = 0; index < parsedData.effectLayers.length; index++) { + var effectLayer = _effectLayer__WEBPACK_IMPORTED_MODULE_2__["EffectLayer"].Parse(parsedData.effectLayers[index], scene, rootUrl); + container.effectLayers.push(effectLayer); + } + } +}); +_abstractScene__WEBPACK_IMPORTED_MODULE_3__["AbstractScene"].prototype.removeEffectLayer = function (toRemove) { + var index = this.effectLayers.indexOf(toRemove); + if (index !== -1) { + this.effectLayers.splice(index, 1); + } + return index; +}; +_abstractScene__WEBPACK_IMPORTED_MODULE_3__["AbstractScene"].prototype.addEffectLayer = function (newEffectLayer) { + this.effectLayers.push(newEffectLayer); +}; +/** + * Defines the layer scene component responsible to manage any effect layers + * in a given scene. + */ +var EffectLayerSceneComponent = /** @class */ (function () { + /** + * Creates a new instance of the component for the given scene + * @param scene Defines the scene to register the component in + */ + function EffectLayerSceneComponent(scene) { + /** + * The component name helpfull to identify the component in the list of scene components. + */ + this.name = _sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].NAME_EFFECTLAYER; + this._renderEffects = false; + this._needStencil = false; + this._previousStencilState = false; + this.scene = scene; + this._engine = scene.getEngine(); + scene.effectLayers = new Array(); + } + /** + * Registers the component in a given scene + */ + EffectLayerSceneComponent.prototype.register = function () { + this.scene._isReadyForMeshStage.registerStep(_sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh); + this.scene._cameraDrawRenderTargetStage.registerStep(_sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture); + this.scene._beforeCameraDrawStage.registerStep(_sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil); + this.scene._afterRenderingGroupDrawStage.registerStep(_sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup); + this.scene._afterCameraDrawStage.registerStep(_sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack); + this.scene._afterCameraDrawStage.registerStep(_sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera); + }; + /** + * Rebuilds the elements related to this component in case of + * context lost for instance. + */ + EffectLayerSceneComponent.prototype.rebuild = function () { + var layers = this.scene.effectLayers; + for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) { + var effectLayer = layers_1[_i]; + effectLayer._rebuild(); + } + }; + /** + * Serializes the component data to the specified json object + * @param serializationObject The object to serialize to + */ + EffectLayerSceneComponent.prototype.serialize = function (serializationObject) { + // Effect layers + serializationObject.effectLayers = []; + var layers = this.scene.effectLayers; + for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) { + var effectLayer = layers_2[_i]; + if (effectLayer.serialize) { + serializationObject.effectLayers.push(effectLayer.serialize()); + } + } + }; + /** + * Adds all the elements from the container to the scene + * @param container the container holding the elements + */ + EffectLayerSceneComponent.prototype.addFromContainer = function (container) { + var _this = this; + if (!container.effectLayers) { + return; + } + container.effectLayers.forEach(function (o) { + _this.scene.addEffectLayer(o); + }); + }; + /** + * Removes all the elements in the container from the scene + * @param container contains the elements to remove + * @param dispose if the removed element should be disposed (default: false) + */ + EffectLayerSceneComponent.prototype.removeFromContainer = function (container, dispose) { + var _this = this; + if (!container.effectLayers) { + return; + } + container.effectLayers.forEach(function (o) { + _this.scene.removeEffectLayer(o); + if (dispose) { + o.dispose(); + } + }); + }; + /** + * Disposes the component and the associated ressources. + */ + EffectLayerSceneComponent.prototype.dispose = function () { + var layers = this.scene.effectLayers; + while (layers.length) { + layers[0].dispose(); + } + }; + EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) { + var layers = this.scene.effectLayers; + for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) { + var layer = layers_3[_i]; + if (!layer.hasMesh(mesh)) { + continue; + } + for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) { + var subMesh = _b[_a]; + if (!layer.isReady(subMesh, hardwareInstancedRendering)) { + return false; + } + } + } + return true; + }; + EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) { + this._renderEffects = false; + this._needStencil = false; + var needRebind = false; + var layers = this.scene.effectLayers; + if (layers && layers.length > 0) { + this._previousStencilState = this._engine.getStencilBuffer(); + for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) { + var effectLayer = layers_4[_i]; + if (effectLayer.shouldRender() && + (!effectLayer.camera || + (effectLayer.camera.cameraRigMode === _Cameras_camera__WEBPACK_IMPORTED_MODULE_0__["Camera"].RIG_MODE_NONE && camera === effectLayer.camera) || + (effectLayer.camera.cameraRigMode !== _Cameras_camera__WEBPACK_IMPORTED_MODULE_0__["Camera"].RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) { + this._renderEffects = true; + this._needStencil = this._needStencil || effectLayer.needStencil(); + var renderTarget = effectLayer._mainTexture; + if (renderTarget._shouldRender()) { + this.scene.incrementRenderId(); + renderTarget.render(false, false); + needRebind = true; + } + } + } + this.scene.incrementRenderId(); + } + return needRebind; + }; + EffectLayerSceneComponent.prototype._setStencil = function () { + // Activate effect Layer stencil + if (this._needStencil) { + this._engine.setStencilBuffer(true); + } + }; + EffectLayerSceneComponent.prototype._setStencilBack = function () { + // Restore effect Layer stencil + if (this._needStencil) { + this._engine.setStencilBuffer(this._previousStencilState); + } + }; + EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) { + if (this._renderEffects) { + this._engine.setDepthBuffer(false); + var layers = this.scene.effectLayers; + for (var i = 0; i < layers.length; i++) { + var effectLayer = layers[i]; + if (effectLayer.renderingGroupId === renderingGroupId) { + if (effectLayer.shouldRender()) { + effectLayer.render(); + } + } + } + this._engine.setDepthBuffer(true); + } + }; + EffectLayerSceneComponent.prototype._drawCamera = function () { + if (this._renderEffects) { + this._draw(-1); + } + }; + EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) { + if (!this.scene._isInIntermediateRendering() && this._renderEffects) { + this._draw(index); + } + }; + return EffectLayerSceneComponent; +}()); + +_effectLayer__WEBPACK_IMPORTED_MODULE_2__["EffectLayer"]._SceneComponentInitialization = function (scene) { + var component = scene._getComponent(_sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].NAME_EFFECTLAYER); + if (!component) { + component = new EffectLayerSceneComponent(scene); + scene._addComponent(component); + } +}; + + +/***/ }), + +/***/ "./Layers/glowLayer.ts": +/*!*****************************!*\ + !*** ./Layers/glowLayer.ts ***! + \*****************************/ +/*! exports provided: GlowLayer */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GlowLayer", function() { return GlowLayer; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/tools */ "./Misc/tools.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Meshes/buffer */ "./Meshes/buffer.ts"); +/* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Materials/Textures/texture */ "./Materials/Textures/texture.ts"); +/* harmony import */ var _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Materials/Textures/renderTargetTexture */ "./Materials/Textures/renderTargetTexture.ts"); +/* harmony import */ var _Materials_material__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Materials/material */ "./Materials/material.ts"); +/* harmony import */ var _PostProcesses_blurPostProcess__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../PostProcesses/blurPostProcess */ "./PostProcesses/blurPostProcess.ts"); +/* harmony import */ var _effectLayer__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./effectLayer */ "./Layers/effectLayer.ts"); +/* harmony import */ var _abstractScene__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../abstractScene */ "./abstractScene.ts"); +/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts"); +/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../Misc/typeStore */ "./Misc/typeStore.ts"); +/* harmony import */ var _Shaders_glowMapMerge_fragment__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../Shaders/glowMapMerge.fragment */ "./Shaders/glowMapMerge.fragment.ts"); +/* harmony import */ var _Shaders_glowMapMerge_vertex__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../Shaders/glowMapMerge.vertex */ "./Shaders/glowMapMerge.vertex.ts"); +/* harmony import */ var _Layers_effectLayerSceneComponent__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../Layers/effectLayerSceneComponent */ "./Layers/effectLayerSceneComponent.ts"); + + + + + + + + + + + + + + + + +_abstractScene__WEBPACK_IMPORTED_MODULE_10__["AbstractScene"].prototype.getGlowLayerByName = function (name) { + for (var index = 0; index < this.effectLayers.length; index++) { + if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) { + return this.effectLayers[index]; + } + } + return null; +}; +/** + * The glow layer Helps adding a glow effect around the emissive parts of a mesh. + * + * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove + * glowy meshes to your scene. + * + * Documentation: https://doc.babylonjs.com/how_to/glow_layer + */ +var GlowLayer = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](GlowLayer, _super); + /** + * Instantiates a new glow Layer and references it to the scene. + * @param name The name of the layer + * @param scene The scene to use the layer in + * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information) + */ + function GlowLayer(name, scene, options) { + var _this = _super.call(this, name, scene) || this; + _this._intensity = 1.0; + _this._includedOnlyMeshes = []; + _this._excludedMeshes = []; + _this.neutralColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Color4"](0, 0, 0, 1); + // Adapt options + _this._options = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options); + // Initialize the layer + _this._init({ + alphaBlendingMode: _Engines_constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].ALPHA_ADD, + camera: _this._options.camera, + mainTextureFixedSize: _this._options.mainTextureFixedSize, + mainTextureRatio: _this._options.mainTextureRatio, + renderingGroupId: _this._options.renderingGroupId + }); + return _this; + } + Object.defineProperty(GlowLayer.prototype, "blurKernelSize", { + /** + * Gets the kernel size of the blur. + */ + get: function () { + return this._horizontalBlurPostprocess1.kernel; + }, + /** + * Sets the kernel size of the blur. + */ + set: function (value) { + this._horizontalBlurPostprocess1.kernel = value; + this._verticalBlurPostprocess1.kernel = value; + this._horizontalBlurPostprocess2.kernel = value; + this._verticalBlurPostprocess2.kernel = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(GlowLayer.prototype, "intensity", { + /** + * Gets the glow intensity. + */ + get: function () { + return this._intensity; + }, + /** + * Sets the glow intensity. + */ + set: function (value) { + this._intensity = value; + }, + enumerable: true, + configurable: true + }); + /** + * Get the effect name of the layer. + * @return The effect name + */ + GlowLayer.prototype.getEffectName = function () { + return GlowLayer.EffectName; + }; + /** + * Create the merge effect. This is the shader use to blit the information back + * to the main canvas at the end of the scene rendering. + */ + GlowLayer.prototype._createMergeEffect = function () { + // Effect + return this._engine.createEffect("glowMapMerge", [_Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"].PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n"); + }; + /** + * Creates the render target textures and post processes used in the glow layer. + */ + GlowLayer.prototype._createTextureAndPostProcesses = function () { + var _this = this; + var blurTextureWidth = this._mainTextureDesiredSize.width; + var blurTextureHeight = this._mainTextureDesiredSize.height; + blurTextureWidth = this._engine.needPOTTextures ? _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth; + blurTextureHeight = this._engine.needPOTTextures ? _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight; + var textureType = 0; + if (this._engine.getCaps().textureHalfFloatRender) { + textureType = _Engines_constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURETYPE_HALF_FLOAT; + } + else { + textureType = _Engines_constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURETYPE_UNSIGNED_INT; + } + this._blurTexture1 = new _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_6__["RenderTargetTexture"]("GlowLayerBlurRTT", { + width: blurTextureWidth, + height: blurTextureHeight + }, this._scene, false, true, textureType); + this._blurTexture1.wrapU = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_5__["Texture"].CLAMP_ADDRESSMODE; + this._blurTexture1.wrapV = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_5__["Texture"].CLAMP_ADDRESSMODE; + this._blurTexture1.updateSamplingMode(_Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_5__["Texture"].BILINEAR_SAMPLINGMODE); + this._blurTexture1.renderParticles = false; + this._blurTexture1.ignoreCameraViewport = true; + var blurTextureWidth2 = Math.floor(blurTextureWidth / 2); + var blurTextureHeight2 = Math.floor(blurTextureHeight / 2); + this._blurTexture2 = new _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_6__["RenderTargetTexture"]("GlowLayerBlurRTT2", { + width: blurTextureWidth2, + height: blurTextureHeight2 + }, this._scene, false, true, textureType); + this._blurTexture2.wrapU = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_5__["Texture"].CLAMP_ADDRESSMODE; + this._blurTexture2.wrapV = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_5__["Texture"].CLAMP_ADDRESSMODE; + this._blurTexture2.updateSamplingMode(_Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_5__["Texture"].BILINEAR_SAMPLINGMODE); + this._blurTexture2.renderParticles = false; + this._blurTexture2.ignoreCameraViewport = true; + this._textures = [this._blurTexture1, this._blurTexture2]; + this._horizontalBlurPostprocess1 = new _PostProcesses_blurPostProcess__WEBPACK_IMPORTED_MODULE_8__["BlurPostProcess"]("GlowLayerHBP1", new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector2"](1.0, 0), this._options.blurKernelSize / 2, { + width: blurTextureWidth, + height: blurTextureHeight + }, null, _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_5__["Texture"].BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType); + this._horizontalBlurPostprocess1.width = blurTextureWidth; + this._horizontalBlurPostprocess1.height = blurTextureHeight; + this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) { + effect.setTexture("textureSampler", _this._mainTexture); + }); + this._verticalBlurPostprocess1 = new _PostProcesses_blurPostProcess__WEBPACK_IMPORTED_MODULE_8__["BlurPostProcess"]("GlowLayerVBP1", new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector2"](0, 1.0), this._options.blurKernelSize / 2, { + width: blurTextureWidth, + height: blurTextureHeight + }, null, _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_5__["Texture"].BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType); + this._horizontalBlurPostprocess2 = new _PostProcesses_blurPostProcess__WEBPACK_IMPORTED_MODULE_8__["BlurPostProcess"]("GlowLayerHBP2", new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector2"](1.0, 0), this._options.blurKernelSize / 2, { + width: blurTextureWidth2, + height: blurTextureHeight2 + }, null, _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_5__["Texture"].BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType); + this._horizontalBlurPostprocess2.width = blurTextureWidth2; + this._horizontalBlurPostprocess2.height = blurTextureHeight2; + this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) { + effect.setTexture("textureSampler", _this._blurTexture1); + }); + this._verticalBlurPostprocess2 = new _PostProcesses_blurPostProcess__WEBPACK_IMPORTED_MODULE_8__["BlurPostProcess"]("GlowLayerVBP2", new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector2"](0, 1.0), this._options.blurKernelSize / 2, { + width: blurTextureWidth2, + height: blurTextureHeight2 + }, null, _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_5__["Texture"].BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType); + this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2]; + this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1]; + this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2]; + this._mainTexture.samples = this._options.mainTextureSamples; + this._mainTexture.onAfterUnbindObservable.add(function () { + var internalTexture = _this._blurTexture1.getInternalTexture(); + if (internalTexture) { + _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true); + internalTexture = _this._blurTexture2.getInternalTexture(); + if (internalTexture) { + _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true); + } + } + }); + // Prevent autoClear. + this._postProcesses.map(function (pp) { pp.autoClear = false; }); + }; + /** + * Checks for the readiness of the element composing the layer. + * @param subMesh the mesh to check for + * @param useInstances specify wether or not to use instances to render the mesh + * @param emissiveTexture the associated emissive texture used to generate the glow + * @return true if ready otherwise, false + */ + GlowLayer.prototype.isReady = function (subMesh, useInstances) { + var material = subMesh.getMaterial(); + var mesh = subMesh.getRenderingMesh(); + if (!material || !mesh) { + return false; + } + var emissiveTexture = material.emissiveTexture; + return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture); + }; + /** + * Returns wether or nood the layer needs stencil enabled during the mesh rendering. + */ + GlowLayer.prototype.needStencil = function () { + return false; + }; + /** + * Returns true if the mesh can be rendered, otherwise false. + * @param mesh The mesh to render + * @param material The material used on the mesh + * @returns true if it can be rendered otherwise false + */ + GlowLayer.prototype._canRenderMesh = function (mesh, material) { + return true; + }; + /** + * Implementation specific of rendering the generating effect on the main canvas. + * @param effect The effect used to render through + */ + GlowLayer.prototype._internalRender = function (effect) { + // Texture + effect.setTexture("textureSampler", this._blurTexture1); + effect.setTexture("textureSampler2", this._blurTexture2); + effect.setFloat("offset", this._intensity); + // Cache + var engine = this._engine; + var previousStencilBuffer = engine.getStencilBuffer(); + // Draw order + engine.setStencilBuffer(false); + engine.drawElementsType(_Materials_material__WEBPACK_IMPORTED_MODULE_7__["Material"].TriangleFillMode, 0, 6); + // Draw order + engine.setStencilBuffer(previousStencilBuffer); + }; + /** + * Sets the required values for both the emissive texture and and the main color. + */ + GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) { + var textureLevel = 1.0; + if (this.customEmissiveTextureSelector) { + this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material); + } + else { + if (material) { + this._emissiveTextureAndColor.texture = material.emissiveTexture; + if (this._emissiveTextureAndColor.texture) { + textureLevel = this._emissiveTextureAndColor.texture.level; + } + } + else { + this._emissiveTextureAndColor.texture = null; + } + } + if (this.customEmissiveColorSelector) { + this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color); + } + else { + if (material.emissiveColor) { + this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, material.alpha); + } + else { + this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a); + } + } + }; + /** + * Returns true if the mesh should render, otherwise false. + * @param mesh The mesh to render + * @returns true if it should render otherwise false + */ + GlowLayer.prototype._shouldRenderMesh = function (mesh) { + return this.hasMesh(mesh); + }; + /** + * Adds specific effects defines. + * @param defines The defines to add specifics to. + */ + GlowLayer.prototype._addCustomEffectDefines = function (defines) { + defines.push("#define GLOW"); + }; + /** + * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer. + * @param mesh The mesh to exclude from the glow layer + */ + GlowLayer.prototype.addExcludedMesh = function (mesh) { + if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) { + this._excludedMeshes.push(mesh.uniqueId); + } + }; + /** + * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer. + * @param mesh The mesh to remove + */ + GlowLayer.prototype.removeExcludedMesh = function (mesh) { + var index = this._excludedMeshes.indexOf(mesh.uniqueId); + if (index !== -1) { + this._excludedMeshes.splice(index, 1); + } + }; + /** + * Add a mesh in the inclusion list to impact or being impacted by the glow layer. + * @param mesh The mesh to include in the glow layer + */ + GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) { + if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) { + this._includedOnlyMeshes.push(mesh.uniqueId); + } + }; + /** + * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer. + * @param mesh The mesh to remove + */ + GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) { + var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId); + if (index !== -1) { + this._includedOnlyMeshes.splice(index, 1); + } + }; + /** + * Determine if a given mesh will be used in the glow layer + * @param mesh The mesh to test + * @returns true if the mesh will be highlighted by the current glow layer + */ + GlowLayer.prototype.hasMesh = function (mesh) { + if (!_super.prototype.hasMesh.call(this, mesh)) { + return false; + } + // Included Mesh + if (this._includedOnlyMeshes.length) { + return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1; + } + // Excluded Mesh + if (this._excludedMeshes.length) { + return this._excludedMeshes.indexOf(mesh.uniqueId) === -1; + } + return true; + }; + /** + * Free any resources and references associated to a mesh. + * Internal use + * @param mesh The mesh to free. + * @hidden + */ + GlowLayer.prototype._disposeMesh = function (mesh) { + this.removeIncludedOnlyMesh(mesh); + this.removeExcludedMesh(mesh); + }; + /** + * Gets the class name of the effect layer + * @returns the string with the class name of the effect layer + */ + GlowLayer.prototype.getClassName = function () { + return "GlowLayer"; + }; + /** + * Serializes this glow layer + * @returns a serialized glow layer object + */ + GlowLayer.prototype.serialize = function () { + var serializationObject = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(this); + serializationObject.customType = "BABYLON.GlowLayer"; + var index; + // Included meshes + serializationObject.includedMeshes = []; + if (this._includedOnlyMeshes.length) { + for (index = 0; index < this._includedOnlyMeshes.length; index++) { + var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]); + if (mesh) { + serializationObject.includedMeshes.push(mesh.id); + } + } + } + // Excluded meshes + serializationObject.excludedMeshes = []; + if (this._excludedMeshes.length) { + for (index = 0; index < this._excludedMeshes.length; index++) { + var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]); + if (mesh) { + serializationObject.excludedMeshes.push(mesh.id); + } + } + } + return serializationObject; + }; + /** + * Creates a Glow Layer from parsed glow layer data + * @param parsedGlowLayer defines glow layer data + * @param scene defines the current scene + * @param rootUrl defines the root URL containing the glow layer information + * @returns a parsed Glow Layer + */ + GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) { + var gl = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl); + var index; + // Excluded meshes + for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) { + var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]); + if (mesh) { + gl.addExcludedMesh(mesh); + } + } + // Included meshes + for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) { + var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]); + if (mesh) { + gl.addIncludedOnlyMesh(mesh); + } + } + return gl; + }; + /** + * Effect Name of the layer. + */ + GlowLayer.EffectName = "GlowLayer"; + /** + * The default blur kernel size used for the glow. + */ + GlowLayer.DefaultBlurKernelSize = 32; + /** + * The default texture size ratio used for the glow. + */ + GlowLayer.DefaultTextureRatio = 0.5; + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], GlowLayer.prototype, "blurKernelSize", null); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], GlowLayer.prototype, "intensity", null); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])("options") + ], GlowLayer.prototype, "_options", void 0); + return GlowLayer; +}(_effectLayer__WEBPACK_IMPORTED_MODULE_9__["EffectLayer"])); + +_Misc_typeStore__WEBPACK_IMPORTED_MODULE_12__["_TypeStore"].RegisteredTypes["BABYLON.GlowLayer"] = GlowLayer; + + +/***/ }), + +/***/ "./Layers/highlightLayer.ts": +/*!**********************************!*\ + !*** ./Layers/highlightLayer.ts ***! + \**********************************/ +/*! exports provided: HighlightLayer */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HighlightLayer", function() { return HighlightLayer; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Misc/tools */ "./Misc/tools.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Meshes_buffer__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Meshes/buffer */ "./Meshes/buffer.ts"); +/* harmony import */ var _Materials_material__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Materials/material */ "./Materials/material.ts"); +/* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Materials/Textures/texture */ "./Materials/Textures/texture.ts"); +/* harmony import */ var _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Materials/Textures/renderTargetTexture */ "./Materials/Textures/renderTargetTexture.ts"); +/* harmony import */ var _PostProcesses_postProcess__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../PostProcesses/postProcess */ "./PostProcesses/postProcess.ts"); +/* harmony import */ var _PostProcesses_passPostProcess__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../PostProcesses/passPostProcess */ "./PostProcesses/passPostProcess.ts"); +/* harmony import */ var _PostProcesses_blurPostProcess__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../PostProcesses/blurPostProcess */ "./PostProcesses/blurPostProcess.ts"); +/* harmony import */ var _effectLayer__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./effectLayer */ "./Layers/effectLayer.ts"); +/* harmony import */ var _abstractScene__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../abstractScene */ "./abstractScene.ts"); +/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts"); +/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts"); +/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../Misc/typeStore */ "./Misc/typeStore.ts"); +/* harmony import */ var _Shaders_glowMapMerge_fragment__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../Shaders/glowMapMerge.fragment */ "./Shaders/glowMapMerge.fragment.ts"); +/* harmony import */ var _Shaders_glowMapMerge_vertex__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../Shaders/glowMapMerge.vertex */ "./Shaders/glowMapMerge.vertex.ts"); +/* harmony import */ var _Shaders_glowBlurPostProcess_fragment__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../Shaders/glowBlurPostProcess.fragment */ "./Shaders/glowBlurPostProcess.fragment.ts"); + + + + + + + + + + + + + + + + + + + + +_abstractScene__WEBPACK_IMPORTED_MODULE_13__["AbstractScene"].prototype.getHighlightLayerByName = function (name) { + for (var index = 0; index < this.effectLayers.length; index++) { + if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) { + return this.effectLayers[index]; + } + } + return null; +}; +/** + * Special Glow Blur post process only blurring the alpha channel + * It enforces keeping the most luminous color in the color channel. + */ +var GlowBlurPostProcess = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](GlowBlurPostProcess, _super); + function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) { + if (samplingMode === void 0) { samplingMode = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_7__["Texture"].BILINEAR_SAMPLINGMODE; } + var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this; + _this.direction = direction; + _this.kernel = kernel; + _this.onApplyObservable.add(function (effect) { + effect.setFloat2("screenSize", _this.width, _this.height); + effect.setVector2("direction", _this.direction); + effect.setFloat("blurWidth", _this.kernel); + }); + return _this; + } + return GlowBlurPostProcess; +}(_PostProcesses_postProcess__WEBPACK_IMPORTED_MODULE_9__["PostProcess"])); +/** + * The highlight layer Helps adding a glow effect around a mesh. + * + * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove + * glowy meshes to your scene. + * + * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!! + */ +var HighlightLayer = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](HighlightLayer, _super); + /** + * Instantiates a new highlight Layer and references it to the scene.. + * @param name The name of the layer + * @param scene The scene to use the layer in + * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information) + */ + function HighlightLayer(name, scene, options) { + var _this = _super.call(this, name, scene) || this; + _this.name = name; + /** + * Specifies whether or not the inner glow is ACTIVE in the layer. + */ + _this.innerGlow = true; + /** + * Specifies whether or not the outer glow is ACTIVE in the layer. + */ + _this.outerGlow = true; + /** + * An event triggered when the highlight layer is being blurred. + */ + _this.onBeforeBlurObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); + /** + * An event triggered when the highlight layer has been blurred. + */ + _this.onAfterBlurObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); + _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++; + _this._meshes = {}; + _this._excludedMeshes = {}; + _this.neutralColor = HighlightLayer.NeutralColor; + // Warn on stencil + if (!_this._engine.isStencilEnable) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_15__["Logger"].Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new Engine(canvas, antialias, { stencil: true }"); + } + // Adapt options + _this._options = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: _Engines_constants__WEBPACK_IMPORTED_MODULE_14__["Constants"].ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options); + // Initialize the layer + _this._init({ + alphaBlendingMode: _this._options.alphaBlendingMode, + camera: _this._options.camera, + mainTextureFixedSize: _this._options.mainTextureFixedSize, + mainTextureRatio: _this._options.mainTextureRatio, + renderingGroupId: _this._options.renderingGroupId + }); + // Do not render as long as no meshes have been added + _this._shouldRender = false; + return _this; + } + Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", { + /** + * Gets the horizontal size of the blur. + */ + get: function () { + return this._horizontalBlurPostprocess.kernel; + }, + /** + * Specifies the horizontal size of the blur. + */ + set: function (value) { + this._horizontalBlurPostprocess.kernel = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", { + /** + * Gets the vertical size of the blur. + */ + get: function () { + return this._verticalBlurPostprocess.kernel; + }, + /** + * Specifies the vertical size of the blur. + */ + set: function (value) { + this._verticalBlurPostprocess.kernel = value; + }, + enumerable: true, + configurable: true + }); + /** + * Get the effect name of the layer. + * @return The effect name + */ + HighlightLayer.prototype.getEffectName = function () { + return HighlightLayer.EffectName; + }; + /** + * Create the merge effect. This is the shader use to blit the information back + * to the main canvas at the end of the scene rendering. + */ + HighlightLayer.prototype._createMergeEffect = function () { + // Effect + return this._engine.createEffect("glowMapMerge", [_Meshes_buffer__WEBPACK_IMPORTED_MODULE_5__["VertexBuffer"].PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined); + }; + /** + * Creates the render target textures and post processes used in the highlight layer. + */ + HighlightLayer.prototype._createTextureAndPostProcesses = function () { + var _this = this; + var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio; + var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio; + blurTextureWidth = this._engine.needPOTTextures ? _Misc_tools__WEBPACK_IMPORTED_MODULE_3__["Tools"].GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth; + blurTextureHeight = this._engine.needPOTTextures ? _Misc_tools__WEBPACK_IMPORTED_MODULE_3__["Tools"].GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight; + var textureType = 0; + if (this._engine.getCaps().textureHalfFloatRender) { + textureType = _Engines_constants__WEBPACK_IMPORTED_MODULE_14__["Constants"].TEXTURETYPE_HALF_FLOAT; + } + else { + textureType = _Engines_constants__WEBPACK_IMPORTED_MODULE_14__["Constants"].TEXTURETYPE_UNSIGNED_INT; + } + this._blurTexture = new _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_8__["RenderTargetTexture"]("HighlightLayerBlurRTT", { + width: blurTextureWidth, + height: blurTextureHeight + }, this._scene, false, true, textureType); + this._blurTexture.wrapU = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_7__["Texture"].CLAMP_ADDRESSMODE; + this._blurTexture.wrapV = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_7__["Texture"].CLAMP_ADDRESSMODE; + this._blurTexture.anisotropicFilteringLevel = 16; + this._blurTexture.updateSamplingMode(_Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_7__["Texture"].TRILINEAR_SAMPLINGMODE); + this._blurTexture.renderParticles = false; + this._blurTexture.ignoreCameraViewport = true; + this._textures = [this._blurTexture]; + if (this._options.alphaBlendingMode === _Engines_constants__WEBPACK_IMPORTED_MODULE_14__["Constants"].ALPHA_COMBINE) { + this._downSamplePostprocess = new _PostProcesses_passPostProcess__WEBPACK_IMPORTED_MODULE_10__["PassPostProcess"]("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_7__["Texture"].BILINEAR_SAMPLINGMODE, this._scene.getEngine()); + this._downSamplePostprocess.onApplyObservable.add(function (effect) { + effect.setTexture("textureSampler", _this._mainTexture); + }); + this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector2"](1.0, 0), this._options.blurHorizontalSize, 1, null, _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_7__["Texture"].BILINEAR_SAMPLINGMODE, this._scene.getEngine()); + this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) { + effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight); + }); + this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector2"](0, 1.0), this._options.blurVerticalSize, 1, null, _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_7__["Texture"].BILINEAR_SAMPLINGMODE, this._scene.getEngine()); + this._verticalBlurPostprocess.onApplyObservable.add(function (effect) { + effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight); + }); + this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess]; + } + else { + this._horizontalBlurPostprocess = new _PostProcesses_blurPostProcess__WEBPACK_IMPORTED_MODULE_11__["BlurPostProcess"]("HighlightLayerHBP", new _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector2"](1.0, 0), this._options.blurHorizontalSize / 2, { + width: blurTextureWidth, + height: blurTextureHeight + }, null, _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_7__["Texture"].BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType); + this._horizontalBlurPostprocess.width = blurTextureWidth; + this._horizontalBlurPostprocess.height = blurTextureHeight; + this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) { + effect.setTexture("textureSampler", _this._mainTexture); + }); + this._verticalBlurPostprocess = new _PostProcesses_blurPostProcess__WEBPACK_IMPORTED_MODULE_11__["BlurPostProcess"]("HighlightLayerVBP", new _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector2"](0, 1.0), this._options.blurVerticalSize / 2, { + width: blurTextureWidth, + height: blurTextureHeight + }, null, _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_7__["Texture"].BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType); + this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess]; + } + this._mainTexture.onAfterUnbindObservable.add(function () { + _this.onBeforeBlurObservable.notifyObservers(_this); + var internalTexture = _this._blurTexture.getInternalTexture(); + if (internalTexture) { + _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true); + } + _this.onAfterBlurObservable.notifyObservers(_this); + }); + // Prevent autoClear. + this._postProcesses.map(function (pp) { pp.autoClear = false; }); + }; + /** + * Returns wether or nood the layer needs stencil enabled during the mesh rendering. + */ + HighlightLayer.prototype.needStencil = function () { + return true; + }; + /** + * Checks for the readiness of the element composing the layer. + * @param subMesh the mesh to check for + * @param useInstances specify wether or not to use instances to render the mesh + * @param emissiveTexture the associated emissive texture used to generate the glow + * @return true if ready otherwise, false + */ + HighlightLayer.prototype.isReady = function (subMesh, useInstances) { + var material = subMesh.getMaterial(); + var mesh = subMesh.getRenderingMesh(); + if (!material || !mesh || !this._meshes) { + return false; + } + var emissiveTexture = null; + var highlightLayerMesh = this._meshes[mesh.uniqueId]; + if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) { + emissiveTexture = material.emissiveTexture; + } + return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture); + }; + /** + * Implementation specific of rendering the generating effect on the main canvas. + * @param effect The effect used to render through + */ + HighlightLayer.prototype._internalRender = function (effect) { + // Texture + effect.setTexture("textureSampler", this._blurTexture); + // Cache + var engine = this._engine; + engine.cacheStencilState(); + // Stencil operations + engine.setStencilOperationPass(_Engines_constants__WEBPACK_IMPORTED_MODULE_14__["Constants"].REPLACE); + engine.setStencilOperationFail(_Engines_constants__WEBPACK_IMPORTED_MODULE_14__["Constants"].KEEP); + engine.setStencilOperationDepthFail(_Engines_constants__WEBPACK_IMPORTED_MODULE_14__["Constants"].KEEP); + // Draw order + engine.setStencilMask(0x00); + engine.setStencilBuffer(true); + engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference); + // 2 passes inner outer + if (this.outerGlow) { + effect.setFloat("offset", 0); + engine.setStencilFunction(_Engines_constants__WEBPACK_IMPORTED_MODULE_14__["Constants"].NOTEQUAL); + engine.drawElementsType(_Materials_material__WEBPACK_IMPORTED_MODULE_6__["Material"].TriangleFillMode, 0, 6); + } + if (this.innerGlow) { + effect.setFloat("offset", 1); + engine.setStencilFunction(_Engines_constants__WEBPACK_IMPORTED_MODULE_14__["Constants"].EQUAL); + engine.drawElementsType(_Materials_material__WEBPACK_IMPORTED_MODULE_6__["Material"].TriangleFillMode, 0, 6); + } + // Restore Cache + engine.restoreStencilState(); + }; + /** + * Returns true if the layer contains information to display, otherwise false. + */ + HighlightLayer.prototype.shouldRender = function () { + if (_super.prototype.shouldRender.call(this)) { + return this._meshes ? true : false; + } + return false; + }; + /** + * Returns true if the mesh should render, otherwise false. + * @param mesh The mesh to render + * @returns true if it should render otherwise false + */ + HighlightLayer.prototype._shouldRenderMesh = function (mesh) { + // Excluded Mesh + if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) { + return false; + } + if (!_super.prototype.hasMesh.call(this, mesh)) { + return false; + } + return true; + }; + /** + * Sets the required values for both the emissive texture and and the main color. + */ + HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) { + var highlightLayerMesh = this._meshes[mesh.uniqueId]; + if (highlightLayerMesh) { + this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0); + } + else { + this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a); + } + if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) { + this._emissiveTextureAndColor.texture = material.emissiveTexture; + this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0); + } + else { + this._emissiveTextureAndColor.texture = null; + } + }; + /** + * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer. + * @param mesh The mesh to exclude from the highlight layer + */ + HighlightLayer.prototype.addExcludedMesh = function (mesh) { + if (!this._excludedMeshes) { + return; + } + var meshExcluded = this._excludedMeshes[mesh.uniqueId]; + if (!meshExcluded) { + this._excludedMeshes[mesh.uniqueId] = { + mesh: mesh, + beforeBind: mesh.onBeforeBindObservable.add(function (mesh) { + mesh.getEngine().setStencilBuffer(false); + }), + afterRender: mesh.onAfterRenderObservable.add(function (mesh) { + mesh.getEngine().setStencilBuffer(true); + }), + }; + } + }; + /** + * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer. + * @param mesh The mesh to highlight + */ + HighlightLayer.prototype.removeExcludedMesh = function (mesh) { + if (!this._excludedMeshes) { + return; + } + var meshExcluded = this._excludedMeshes[mesh.uniqueId]; + if (meshExcluded) { + if (meshExcluded.beforeBind) { + mesh.onBeforeBindObservable.remove(meshExcluded.beforeBind); + } + if (meshExcluded.afterRender) { + mesh.onAfterRenderObservable.remove(meshExcluded.afterRender); + } + } + this._excludedMeshes[mesh.uniqueId] = null; + }; + /** + * Determine if a given mesh will be highlighted by the current HighlightLayer + * @param mesh mesh to test + * @returns true if the mesh will be highlighted by the current HighlightLayer + */ + HighlightLayer.prototype.hasMesh = function (mesh) { + if (!this._meshes) { + return false; + } + if (!_super.prototype.hasMesh.call(this, mesh)) { + return false; + } + return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null; + }; + /** + * Add a mesh in the highlight layer in order to make it glow with the chosen color. + * @param mesh The mesh to highlight + * @param color The color of the highlight + * @param glowEmissiveOnly Extract the glow from the emissive texture + */ + HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) { + var _this = this; + if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; } + if (!this._meshes) { + return; + } + var meshHighlight = this._meshes[mesh.uniqueId]; + if (meshHighlight) { + meshHighlight.color = color; + } + else { + this._meshes[mesh.uniqueId] = { + mesh: mesh, + color: color, + // Lambda required for capture due to Observable this context + observerHighlight: mesh.onBeforeBindObservable.add(function (mesh) { + if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) { + _this._defaultStencilReference(mesh); + } + else { + mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference); + } + }), + observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference), + glowEmissiveOnly: glowEmissiveOnly + }; + mesh.onDisposeObservable.add(function () { + _this._disposeMesh(mesh); + }); + } + this._shouldRender = true; + }; + /** + * Remove a mesh from the highlight layer in order to make it stop glowing. + * @param mesh The mesh to highlight + */ + HighlightLayer.prototype.removeMesh = function (mesh) { + if (!this._meshes) { + return; + } + var meshHighlight = this._meshes[mesh.uniqueId]; + if (meshHighlight) { + if (meshHighlight.observerHighlight) { + mesh.onBeforeBindObservable.remove(meshHighlight.observerHighlight); + } + if (meshHighlight.observerDefault) { + mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault); + } + delete this._meshes[mesh.uniqueId]; + } + this._shouldRender = false; + for (var meshHighlightToCheck in this._meshes) { + if (this._meshes[meshHighlightToCheck]) { + this._shouldRender = true; + break; + } + } + }; + /** + * Force the stencil to the normal expected value for none glowing parts + */ + HighlightLayer.prototype._defaultStencilReference = function (mesh) { + mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference); + }; + /** + * Free any resources and references associated to a mesh. + * Internal use + * @param mesh The mesh to free. + * @hidden + */ + HighlightLayer.prototype._disposeMesh = function (mesh) { + this.removeMesh(mesh); + this.removeExcludedMesh(mesh); + }; + /** + * Dispose the highlight layer and free resources. + */ + HighlightLayer.prototype.dispose = function () { + if (this._meshes) { + // Clean mesh references + for (var id in this._meshes) { + var meshHighlight = this._meshes[id]; + if (meshHighlight && meshHighlight.mesh) { + if (meshHighlight.observerHighlight) { + meshHighlight.mesh.onBeforeBindObservable.remove(meshHighlight.observerHighlight); + } + if (meshHighlight.observerDefault) { + meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault); + } + } + } + this._meshes = null; + } + if (this._excludedMeshes) { + for (var id in this._excludedMeshes) { + var meshHighlight = this._excludedMeshes[id]; + if (meshHighlight) { + if (meshHighlight.beforeBind) { + meshHighlight.mesh.onBeforeBindObservable.remove(meshHighlight.beforeBind); + } + if (meshHighlight.afterRender) { + meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender); + } + } + } + this._excludedMeshes = null; + } + _super.prototype.dispose.call(this); + }; + /** + * Gets the class name of the effect layer + * @returns the string with the class name of the effect layer + */ + HighlightLayer.prototype.getClassName = function () { + return "HighlightLayer"; + }; + /** + * Serializes this Highlight layer + * @returns a serialized Highlight layer object + */ + HighlightLayer.prototype.serialize = function () { + var serializationObject = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(this); + serializationObject.customType = "BABYLON.HighlightLayer"; + // Highlighted meshes + serializationObject.meshes = []; + if (this._meshes) { + for (var m in this._meshes) { + var mesh = this._meshes[m]; + if (mesh) { + serializationObject.meshes.push({ + glowEmissiveOnly: mesh.glowEmissiveOnly, + color: mesh.color.asArray(), + meshId: mesh.mesh.id + }); + } + } + } + // Excluded meshes + serializationObject.excludedMeshes = []; + if (this._excludedMeshes) { + for (var e in this._excludedMeshes) { + var excludedMesh = this._excludedMeshes[e]; + if (excludedMesh) { + serializationObject.excludedMeshes.push(excludedMesh.mesh.id); + } + } + } + return serializationObject; + }; + /** + * Creates a Highlight layer from parsed Highlight layer data + * @param parsedHightlightLayer defines the Highlight layer data + * @param scene defines the current scene + * @param rootUrl defines the root URL containing the Highlight layer information + * @returns a parsed Highlight layer + */ + HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) { + var hl = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl); + var index; + // Excluded meshes + for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) { + var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]); + if (mesh) { + hl.addExcludedMesh(mesh); + } + } + // Included meshes + for (index = 0; index < parsedHightlightLayer.meshes.length; index++) { + var highlightedMesh = parsedHightlightLayer.meshes[index]; + var mesh = scene.getMeshByID(highlightedMesh.meshId); + if (mesh) { + hl.addMesh(mesh, _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Color3"].FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly); + } + } + return hl; + }; + /** + * Effect Name of the highlight layer. + */ + HighlightLayer.EffectName = "HighlightLayer"; + /** + * The neutral color used during the preparation of the glow effect. + * This is black by default as the blend operation is a blend operation. + */ + HighlightLayer.NeutralColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Color4"](0, 0, 0, 0); + /** + * Stencil value used for glowing meshes. + */ + HighlightLayer.GlowingMeshStencilReference = 0x02; + /** + * Stencil value used for the other meshes in the scene. + */ + HighlightLayer.NormalMeshStencilReference = 0x01; + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], HighlightLayer.prototype, "innerGlow", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], HighlightLayer.prototype, "outerGlow", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], HighlightLayer.prototype, "blurHorizontalSize", null); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], HighlightLayer.prototype, "blurVerticalSize", null); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])("options") + ], HighlightLayer.prototype, "_options", void 0); + return HighlightLayer; +}(_effectLayer__WEBPACK_IMPORTED_MODULE_12__["EffectLayer"])); + +_Misc_typeStore__WEBPACK_IMPORTED_MODULE_16__["_TypeStore"].RegisteredTypes["BABYLON.HighlightLayer"] = HighlightLayer; + + +/***/ }), + +/***/ "./Layers/index.ts": +/*!*************************!*\ + !*** ./Layers/index.ts ***! + \*************************/ +/*! exports provided: EffectLayer, EffectLayerSceneComponent, GlowLayer, HighlightLayer, Layer, LayerSceneComponent */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _effectLayer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./effectLayer */ "./Layers/effectLayer.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EffectLayer", function() { return _effectLayer__WEBPACK_IMPORTED_MODULE_0__["EffectLayer"]; }); + +/* harmony import */ var _effectLayerSceneComponent__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./effectLayerSceneComponent */ "./Layers/effectLayerSceneComponent.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EffectLayerSceneComponent", function() { return _effectLayerSceneComponent__WEBPACK_IMPORTED_MODULE_1__["EffectLayerSceneComponent"]; }); + +/* harmony import */ var _glowLayer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./glowLayer */ "./Layers/glowLayer.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GlowLayer", function() { return _glowLayer__WEBPACK_IMPORTED_MODULE_2__["GlowLayer"]; }); + +/* harmony import */ var _highlightLayer__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./highlightLayer */ "./Layers/highlightLayer.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HighlightLayer", function() { return _highlightLayer__WEBPACK_IMPORTED_MODULE_3__["HighlightLayer"]; }); + +/* harmony import */ var _layer__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./layer */ "./Layers/layer.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Layer", function() { return _layer__WEBPACK_IMPORTED_MODULE_4__["Layer"]; }); + +/* harmony import */ var _layerSceneComponent__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./layerSceneComponent */ "./Layers/layerSceneComponent.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LayerSceneComponent", function() { return _layerSceneComponent__WEBPACK_IMPORTED_MODULE_5__["LayerSceneComponent"]; }); + + + + + + + + + +/***/ }), + +/***/ "./Layers/layer.ts": +/*!*************************!*\ + !*** ./Layers/layer.ts ***! + \*************************/ +/*! exports provided: Layer */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Layer", function() { return Layer; }); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Engines_engineStore__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Engines/engineStore */ "./Engines/engineStore.ts"); +/* harmony import */ var _Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Meshes/buffer */ "./Meshes/buffer.ts"); +/* harmony import */ var _Materials_material__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Materials/material */ "./Materials/material.ts"); +/* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Materials/Textures/texture */ "./Materials/Textures/texture.ts"); +/* harmony import */ var _sceneComponent__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../sceneComponent */ "./sceneComponent.ts"); +/* harmony import */ var _layerSceneComponent__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./layerSceneComponent */ "./Layers/layerSceneComponent.ts"); +/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts"); +/* harmony import */ var _Shaders_layer_fragment__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Shaders/layer.fragment */ "./Shaders/layer.fragment.ts"); +/* harmony import */ var _Shaders_layer_vertex__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../Shaders/layer.vertex */ "./Shaders/layer.vertex.ts"); + + + + + + + + + + + +/** + * This represents a full screen 2d layer. + * This can be useful to display a picture in the background of your scene for instance. + * @see https://www.babylonjs-playground.com/#08A2BS#1 + */ +var Layer = /** @class */ (function () { + /** + * Instantiates a new layer. + * This represents a full screen 2d layer. + * This can be useful to display a picture in the background of your scene for instance. + * @see https://www.babylonjs-playground.com/#08A2BS#1 + * @param name Define the name of the layer in the scene + * @param imgUrl Define the url of the texture to display in the layer + * @param scene Define the scene the layer belongs to + * @param isBackground Defines whether the layer is displayed in front or behind the scene + * @param color Defines a color for the layer + */ + function Layer( + /** + * Define the name of the layer. + */ + name, imgUrl, scene, isBackground, color) { + this.name = name; + /** + * Define the scale of the layer in order to zoom in out of the texture. + */ + this.scale = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector2"](1, 1); + /** + * Define an offset for the layer in order to shift the texture. + */ + this.offset = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector2"](0, 0); + /** + * Define the alpha blending mode used in the layer in case the texture or color has an alpha. + */ + this.alphaBlendingMode = _Engines_constants__WEBPACK_IMPORTED_MODULE_8__["Constants"].ALPHA_COMBINE; + /** + * Define a mask to restrict the layer to only some of the scene cameras. + */ + this.layerMask = 0x0FFFFFFF; + /** + * Define the list of render target the layer is visible into. + */ + this.renderTargetTextures = []; + /** + * Define if the layer is only used in renderTarget or if it also + * renders in the main frame buffer of the canvas. + */ + this.renderOnlyInRenderTargetTextures = false; + this._vertexBuffers = {}; + /** + * An event triggered when the layer is disposed. + */ + this.onDisposeObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](); + /** + * An event triggered before rendering the scene + */ + this.onBeforeRenderObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](); + /** + * An event triggered after rendering the scene + */ + this.onAfterRenderObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](); + this.texture = imgUrl ? new _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_5__["Texture"](imgUrl, scene, true) : null; + this.isBackground = isBackground === undefined ? true : isBackground; + this.color = color === undefined ? new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Color4"](1, 1, 1, 1) : color; + this._scene = (scene || _Engines_engineStore__WEBPACK_IMPORTED_MODULE_2__["EngineStore"].LastCreatedScene); + var layerComponent = this._scene._getComponent(_sceneComponent__WEBPACK_IMPORTED_MODULE_6__["SceneComponentConstants"].NAME_LAYER); + if (!layerComponent) { + layerComponent = new _layerSceneComponent__WEBPACK_IMPORTED_MODULE_7__["LayerSceneComponent"](this._scene); + this._scene._addComponent(layerComponent); + } + this._scene.layers.push(this); + var engine = this._scene.getEngine(); + // VBO + var vertices = []; + vertices.push(1, 1); + vertices.push(-1, 1); + vertices.push(-1, -1); + vertices.push(1, -1); + var vertexBuffer = new _Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__["VertexBuffer"](engine, vertices, _Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__["VertexBuffer"].PositionKind, false, false, 2); + this._vertexBuffers[_Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__["VertexBuffer"].PositionKind] = vertexBuffer; + this._createIndexBuffer(); + // Effects + this._effect = engine.createEffect("layer", [_Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__["VertexBuffer"].PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], ""); + this._alphaTestEffect = engine.createEffect("layer", [_Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__["VertexBuffer"].PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST"); + } + Object.defineProperty(Layer.prototype, "onDispose", { + /** + * Back compatibility with callback before the onDisposeObservable existed. + * The set callback will be triggered when the layer has been disposed. + */ + set: function (callback) { + if (this._onDisposeObserver) { + this.onDisposeObservable.remove(this._onDisposeObserver); + } + this._onDisposeObserver = this.onDisposeObservable.add(callback); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Layer.prototype, "onBeforeRender", { + /** + * Back compatibility with callback before the onBeforeRenderObservable existed. + * The set callback will be triggered just before rendering the layer. + */ + set: function (callback) { + if (this._onBeforeRenderObserver) { + this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver); + } + this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Layer.prototype, "onAfterRender", { + /** + * Back compatibility with callback before the onAfterRenderObservable existed. + * The set callback will be triggered just after rendering the layer. + */ + set: function (callback) { + if (this._onAfterRenderObserver) { + this.onAfterRenderObservable.remove(this._onAfterRenderObserver); + } + this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback); + }, + enumerable: true, + configurable: true + }); + Layer.prototype._createIndexBuffer = function () { + var engine = this._scene.getEngine(); + // Indices + var indices = []; + indices.push(0); + indices.push(1); + indices.push(2); + indices.push(0); + indices.push(2); + indices.push(3); + this._indexBuffer = engine.createIndexBuffer(indices); + }; + /** @hidden */ + Layer.prototype._rebuild = function () { + var vb = this._vertexBuffers[_Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__["VertexBuffer"].PositionKind]; + if (vb) { + vb._rebuild(); + } + this._createIndexBuffer(); + }; + /** + * Renders the layer in the scene. + */ + Layer.prototype.render = function () { + var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect; + // Check + if (!currentEffect.isReady() || !this.texture || !this.texture.isReady()) { + return; + } + var engine = this._scene.getEngine(); + this.onBeforeRenderObservable.notifyObservers(this); + // Render + engine.enableEffect(currentEffect); + engine.setState(false); + // Texture + currentEffect.setTexture("textureSampler", this.texture); + currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix()); + // Color + currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a); + // Scale / offset + currentEffect.setVector2("offset", this.offset); + currentEffect.setVector2("scale", this.scale); + // VBOs + engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect); + // Draw order + if (!this.alphaTest) { + engine.setAlphaMode(this.alphaBlendingMode); + engine.drawElementsType(_Materials_material__WEBPACK_IMPORTED_MODULE_4__["Material"].TriangleFillMode, 0, 6); + engine.setAlphaMode(_Engines_constants__WEBPACK_IMPORTED_MODULE_8__["Constants"].ALPHA_DISABLE); + } + else { + engine.drawElementsType(_Materials_material__WEBPACK_IMPORTED_MODULE_4__["Material"].TriangleFillMode, 0, 6); + } + this.onAfterRenderObservable.notifyObservers(this); + }; + /** + * Disposes and releases the associated ressources. + */ + Layer.prototype.dispose = function () { + var vertexBuffer = this._vertexBuffers[_Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__["VertexBuffer"].PositionKind]; + if (vertexBuffer) { + vertexBuffer.dispose(); + this._vertexBuffers[_Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__["VertexBuffer"].PositionKind] = null; + } + if (this._indexBuffer) { + this._scene.getEngine()._releaseBuffer(this._indexBuffer); + this._indexBuffer = null; + } + if (this.texture) { + this.texture.dispose(); + this.texture = null; + } + // Clean RTT list + this.renderTargetTextures = []; + // Remove from scene + var index = this._scene.layers.indexOf(this); + this._scene.layers.splice(index, 1); + // Callback + this.onDisposeObservable.notifyObservers(this); + this.onDisposeObservable.clear(); + this.onAfterRenderObservable.clear(); + this.onBeforeRenderObservable.clear(); + }; + return Layer; +}()); + + + +/***/ }), + +/***/ "./Layers/layerSceneComponent.ts": +/*!***************************************!*\ + !*** ./Layers/layerSceneComponent.ts ***! + \***************************************/ +/*! exports provided: LayerSceneComponent */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LayerSceneComponent", function() { return LayerSceneComponent; }); +/* harmony import */ var _sceneComponent__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../sceneComponent */ "./sceneComponent.ts"); + +/** + * Defines the layer scene component responsible to manage any layers + * in a given scene. + */ +var LayerSceneComponent = /** @class */ (function () { + /** + * Creates a new instance of the component for the given scene + * @param scene Defines the scene to register the component in + */ + function LayerSceneComponent(scene) { + /** + * The component name helpfull to identify the component in the list of scene components. + */ + this.name = _sceneComponent__WEBPACK_IMPORTED_MODULE_0__["SceneComponentConstants"].NAME_LAYER; + this.scene = scene; + this._engine = scene.getEngine(); + scene.layers = new Array(); + } + /** + * Registers the component in a given scene + */ + LayerSceneComponent.prototype.register = function () { + this.scene._beforeCameraDrawStage.registerStep(_sceneComponent__WEBPACK_IMPORTED_MODULE_0__["SceneComponentConstants"].STEP_BEFORECAMERADRAW_LAYER, this, this._drawCameraBackground); + this.scene._afterCameraDrawStage.registerStep(_sceneComponent__WEBPACK_IMPORTED_MODULE_0__["SceneComponentConstants"].STEP_AFTERCAMERADRAW_LAYER, this, this._drawCameraForeground); + this.scene._beforeRenderTargetDrawStage.registerStep(_sceneComponent__WEBPACK_IMPORTED_MODULE_0__["SceneComponentConstants"].STEP_BEFORERENDERTARGETDRAW_LAYER, this, this._drawRenderTargetBackground); + this.scene._afterRenderTargetDrawStage.registerStep(_sceneComponent__WEBPACK_IMPORTED_MODULE_0__["SceneComponentConstants"].STEP_AFTERRENDERTARGETDRAW_LAYER, this, this._drawRenderTargetForeground); + }; + /** + * Rebuilds the elements related to this component in case of + * context lost for instance. + */ + LayerSceneComponent.prototype.rebuild = function () { + var layers = this.scene.layers; + for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) { + var layer = layers_1[_i]; + layer._rebuild(); + } + }; + /** + * Disposes the component and the associated ressources. + */ + LayerSceneComponent.prototype.dispose = function () { + var layers = this.scene.layers; + while (layers.length) { + layers[0].dispose(); + } + }; + LayerSceneComponent.prototype._draw = function (predicate) { + var layers = this.scene.layers; + if (layers.length) { + this._engine.setDepthBuffer(false); + for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) { + var layer = layers_2[_i]; + if (predicate(layer)) { + layer.render(); + } + } + this._engine.setDepthBuffer(true); + } + }; + LayerSceneComponent.prototype._drawCameraPredicate = function (layer, isBackground, cameraLayerMask) { + return !layer.renderOnlyInRenderTargetTextures && + layer.isBackground === isBackground && + ((layer.layerMask & cameraLayerMask) !== 0); + }; + LayerSceneComponent.prototype._drawCameraBackground = function (camera) { + var _this = this; + this._draw(function (layer) { + return _this._drawCameraPredicate(layer, true, camera.layerMask); + }); + }; + LayerSceneComponent.prototype._drawCameraForeground = function (camera) { + var _this = this; + this._draw(function (layer) { + return _this._drawCameraPredicate(layer, false, camera.layerMask); + }); + }; + LayerSceneComponent.prototype._drawRenderTargetPredicate = function (layer, isBackground, cameraLayerMask, renderTargetTexture) { + return (layer.renderTargetTextures.length > 0) && + layer.isBackground === isBackground && + (layer.renderTargetTextures.indexOf(renderTargetTexture) > -1) && + ((layer.layerMask & cameraLayerMask) !== 0); + }; + LayerSceneComponent.prototype._drawRenderTargetBackground = function (renderTarget) { + var _this = this; + this._draw(function (layer) { + return _this._drawRenderTargetPredicate(layer, true, _this.scene.activeCamera.layerMask, renderTarget); + }); + }; + LayerSceneComponent.prototype._drawRenderTargetForeground = function (renderTarget) { + var _this = this; + this._draw(function (layer) { + return _this._drawRenderTargetPredicate(layer, false, _this.scene.activeCamera.layerMask, renderTarget); + }); + }; + /** + * Adds all the elements from the container to the scene + * @param container the container holding the elements + */ + LayerSceneComponent.prototype.addFromContainer = function (container) { + var _this = this; + if (!container.layers) { + return; + } + container.layers.forEach(function (layer) { + _this.scene.layers.push(layer); + }); + }; + /** + * Removes all the elements in the container from the scene + * @param container contains the elements to remove + * @param dispose if the removed element should be disposed (default: false) + */ + LayerSceneComponent.prototype.removeFromContainer = function (container, dispose) { + var _this = this; + if (dispose === void 0) { dispose = false; } + if (!container.layers) { + return; + } + container.layers.forEach(function (layer) { + var index = _this.scene.layers.indexOf(layer); + if (index !== -1) { + _this.scene.layers.splice(index, 1); + } + if (dispose) { + layer.dispose(); + } + }); + }; + return LayerSceneComponent; +}()); + + + +/***/ }), + +/***/ "./Legacy/legacy.ts": +/*!**************************!*\ + !*** ./Legacy/legacy.ts ***! + \**************************/ +/*! exports provided: Debug, AbstractScene, KeepAssets, AssetContainer, Node, Scene, SceneComponentConstants, Stage, Action, ActionEvent, ActionManager, Condition, ValueCondition, PredicateCondition, StateCondition, SwitchBooleanAction, SetStateAction, SetValueAction, IncrementValueAction, PlayAnimationAction, StopAnimationAction, DoNothingAction, CombineAction, ExecuteCodeAction, SetParentAction, PlaySoundAction, StopSoundAction, InterpolateValueAction, Animatable, _IAnimationState, Animation, TargetedAnimation, AnimationGroup, AnimationPropertiesOverride, EasingFunction, CircleEase, BackEase, BounceEase, CubicEase, ElasticEase, ExponentialEase, PowerEase, QuadraticEase, QuarticEase, QuinticEase, SineEase, BezierCurveEase, RuntimeAnimation, AnimationEvent, AnimationKeyInterpolation, AnimationRange, Analyser, AudioEngine, AudioSceneComponent, Sound, SoundTrack, WeightedSound, Bone, BoneIKController, BoneLookController, Skeleton, CameraInputTypes, CameraInputsManager, Camera, TargetCamera, FreeCamera, FreeCameraInputsManager, TouchCamera, ArcRotateCamera, ArcRotateCameraInputsManager, DeviceOrientationCamera, FlyCamera, FlyCameraInputsManager, FollowCamera, ArcFollowCamera, GamepadCamera, UniversalCamera, VirtualJoysticksCamera, Collider, DefaultCollisionCoordinator, PickingInfo, IntersectionInfo, _MeshCollisionData, BoundingBox, BoundingInfo, BoundingSphere, Ray, AxesViewer, BoneAxesViewer, DebugLayer, PhysicsViewer, RayHelper, SkeletonViewer, Constants, InstancingAttributeInfo, DepthTextureCreationOptions, EngineCapabilities, Engine, EngineStore, NullEngineOptions, NullEngine, WebGLPipelineContext, WebGL2ShaderProcessor, NativeEngineOptions, NativeEngine, KeyboardEventTypes, KeyboardInfo, KeyboardInfoPre, PointerEventTypes, PointerInfoBase, PointerInfoPre, PointerInfo, ClipboardEventTypes, ClipboardInfo, StickValues, Gamepad, GenericPad, GamepadManager, GamepadSystemSceneComponent, Xbox360Button, Xbox360Dpad, Xbox360Pad, AxisDragGizmo, AxisScaleGizmo, BoundingBoxGizmo, Gizmo, GizmoManager, PlaneRotationGizmo, PositionGizmo, RotationGizmo, ScaleGizmo, LightGizmo, EnvironmentHelper, PhotoDome, _forceSceneHelpersToBundle, VideoDome, EngineInstrumentation, SceneInstrumentation, _TimeToken, EffectLayer, EffectLayerSceneComponent, GlowLayer, HighlightLayer, Layer, LayerSceneComponent, LensFlare, LensFlareSystem, LensFlareSystemSceneComponent, Light, ShadowLight, DirectionalLight, HemisphericLight, PointLight, SpotLight, DefaultLoadingScreen, SceneLoaderProgressEvent, SceneLoader, SceneLoaderFlags, ColorCurves, EffectFallbacks, EffectCreationOptions, Effect, FresnelParameters, ImageProcessingConfigurationDefines, ImageProcessingConfiguration, Material, MaterialDefines, MaterialHelper, MultiMaterial, PushMaterial, ShaderMaterial, StandardMaterialDefines, StandardMaterial, BaseTexture, CubeTexture, DynamicTexture, EquiRectangularCubeTexture, HDRCubeTexture, InternalTexture, MirrorTexture, MultiRenderTarget, RawTexture, RenderTargetTexture, Texture, UniformBuffer, MaterialFlags, Scalar, ToGammaSpace, ToLinearSpace, Epsilon, Color3, Color4, Vector2, Vector3, Vector4, Size, Quaternion, Matrix, Plane, Viewport, Frustum, Space, Axis, BezierCurve, Orientation, Angle, Arc2, Path2, Path3D, Curve3, PositionNormalVertex, PositionNormalTextureVertex, Tmp, SphericalHarmonics, SphericalPolynomial, AbstractMesh, Buffer, VertexBuffer, CSG, Geometry, GroundMesh, TrailMesh, InstancedMesh, LinesMesh, InstancedLinesMesh, _CreationDataStorage, _InstancesBatch, Mesh, VertexData, MeshBuilder, SimplificationSettings, SimplificationQueue, SimplificationType, SimplicationQueueSceneComponent, Polygon, PolygonMeshBuilder, BaseSubMesh, SubMesh, MeshLODLevel, TransformNode, BoxBuilder, SphereBuilder, CylinderBuilder, TorusBuilder, LinesBuilder, PlaneBuilder, GroundBuilder, DataBuffer, WebGLDataBuffer, MorphTarget, MorphTargetManager, Database, BaseParticleSystem, GPUParticleSystem, Particle, ParticleHelper, ParticleSystem, _IDoNeedToBeInTheBuild, ParticleSystemSet, SolidParticle, ModelShape, DepthSortedParticle, SolidParticleSystem, SubEmitterType, SubEmitter, PhysicsEngine, PhysicsEngineSceneComponent, PhysicsHelper, PhysicsRadialExplosionEventOptions, PhysicsUpdraftEventOptions, PhysicsVortexEventOptions, PhysicsRadialImpulseFalloff, PhysicsUpdraftMode, PhysicsImpostor, PhysicsJoint, DistanceJoint, MotorEnabledJoint, HingeJoint, Hinge2Joint, AnaglyphPostProcess, BlackAndWhitePostProcess, BloomEffect, BloomMergePostProcess, BlurPostProcess, ChromaticAberrationPostProcess, CircleOfConfusionPostProcess, ColorCorrectionPostProcess, ConvolutionPostProcess, DepthOfFieldBlurPostProcess, DepthOfFieldEffectBlurLevel, DepthOfFieldEffect, DepthOfFieldMergePostProcessOptions, DepthOfFieldMergePostProcess, DisplayPassPostProcess, ExtractHighlightsPostProcess, FilterPostProcess, FxaaPostProcess, GrainPostProcess, HighlightsPostProcess, ImageProcessingPostProcess, MotionBlurPostProcess, PassPostProcess, PassCubePostProcess, PostProcess, PostProcessManager, RefractionPostProcess, SharpenPostProcess, StereoscopicInterlacePostProcess, TonemappingOperator, TonemapPostProcess, VolumetricLightScatteringPostProcess, VRDistortionCorrectionPostProcess, VRMultiviewToSingleviewPostProcess, ReflectionProbe, BoundingBoxRenderer, DepthRenderer, DepthRendererSceneComponent, EdgesRenderer, LineEdgesRenderer, GeometryBufferRenderer, GeometryBufferRendererSceneComponent, OutlineRenderer, RenderingGroup, RenderingGroupInfo, RenderingManager, UtilityLayerRenderer, Sprite, SpriteManager, SpriteSceneComponent, _AlphaState, _DepthCullingState, _StencilState, AndOrNotEvaluator, AssetTaskState, AbstractAssetTask, AssetsProgressEvent, MeshAssetTask, TextFileAssetTask, BinaryFileAssetTask, ImageAssetTask, TextureAssetTask, CubeTextureAssetTask, HDRCubeTextureAssetTask, EquiRectangularCubeTextureAssetTask, AssetsManager, DDSTools, expandToProperty, serialize, serializeAsTexture, serializeAsColor3, serializeAsFresnelParameters, serializeAsVector2, serializeAsVector3, serializeAsMeshReference, serializeAsColorCurves, serializeAsColor4, serializeAsImageProcessingConfiguration, serializeAsQuaternion, serializeAsMatrix, serializeAsCameraReference, SerializationHelper, Deferred, EnvironmentTextureTools, MeshExploder, FilesInput, KhronosTextureContainer, EventState, Observer, MultiObserver, Observable, PerformanceMonitor, RollingAverage, PromisePolyfill, SceneOptimization, TextureOptimization, HardwareScalingOptimization, ShadowsOptimization, PostProcessesOptimization, LensFlaresOptimization, CustomOptimization, ParticlesOptimization, RenderTargetsOptimization, MergeMeshesOptimization, SceneOptimizerOptions, SceneOptimizer, SceneSerializer, SmartArray, SmartArrayNoDuplicate, StringDictionary, Tags, TextureTools, TGATools, ColorGradient, Color3Gradient, FactorGradient, LoadFileError, RetryStrategy, Tools, PerfCounter, className, AsyncLoop, VideoRecorder, JoystickAxis, VirtualJoystick, WorkerPool, Logger, _TypeStore, FilesInputStore, DeepCopier, PivotTools, PrecisionDate, ScreenshotTools, WebRequest, InspectableType, BRDFTextureTools, AutoRotationBehavior, BouncingBehavior, FramingBehavior, AttachToBoxBehavior, FadeInOutBehavior, MultiPointerScaleBehavior, PointerDragBehavior, SixDofDragBehavior, ArcRotateCameraGamepadInput, ArcRotateCameraKeyboardMoveInput, ArcRotateCameraMouseWheelInput, ArcRotateCameraPointersInput, ArcRotateCameraVRDeviceOrientationInput, FlyCameraKeyboardInput, FlyCameraMouseInput, FollowCameraKeyboardMoveInput, FollowCameraMouseWheelInput, FollowCameraPointersInput, FreeCameraDeviceOrientationInput, FreeCameraGamepadInput, FreeCameraKeyboardMoveInput, FreeCameraMouseInput, FreeCameraTouchInput, FreeCameraVirtualJoystickInput, AnaglyphArcRotateCamera, AnaglyphFreeCamera, AnaglyphGamepadCamera, AnaglyphUniversalCamera, StereoscopicArcRotateCamera, StereoscopicFreeCamera, StereoscopicGamepadCamera, StereoscopicUniversalCamera, VRCameraMetrics, VRDeviceOrientationArcRotateCamera, VRDeviceOrientationFreeCamera, VRDeviceOrientationGamepadCamera, OnAfterEnteringVRObservableEvent, VRExperienceHelper, WebVRFreeCamera, WebXRCamera, WebXREnterExitUIButton, WebXREnterExitUIOptions, WebXREnterExitUI, WebXRState, WebXRExperienceHelper, WebXRController, WebXRInput, WebXRManagedOutputCanvas, WebXRSessionManager, Octree, OctreeBlock, OctreeSceneComponent, _OcclusionDataStorage, _forceTransformFeedbackToBundle, DaydreamController, GearVRController, GenericController, OculusTouchController, PoseEnabledControllerType, PoseEnabledControllerHelper, PoseEnabledController, ViveController, WebVRController, WindowsMotionController, ShadowGenerator, ShadowGeneratorSceneComponent, _BabylonLoaderRegistered, BackgroundMaterial, PBRMaterialDefines, PBRBaseMaterial, PBRBaseSimpleMaterial, PBRMaterial, PBRMetallicRoughnessMaterial, PBRSpecularGlossinessMaterial, ColorGradingTexture, RawCubeTexture, RawTexture3D, RefractionTexture, VideoTexture, HtmlElementTexture, NodeMaterialBlockTargets, NodeMaterialBlockConnectionPointTypes, NodeMaterialConnectionPoint, NodeMaterialBlock, NodeMaterialDefines, NodeMaterial, NodeMaterialWellKnownValues, DracoCompression, TiledBoxBuilder, DiscBuilder, RibbonBuilder, HemisphereBuilder, TorusKnotBuilder, PolygonBuilder, ShapeBuilder, LatheBuilder, TiledPlaneBuilder, TubeBuilder, PolyhedronBuilder, IcoSphereBuilder, DecalBuilder, BoxParticleEmitter, ConeParticleEmitter, CylinderParticleEmitter, CylinderDirectedParticleEmitter, HemisphericParticleEmitter, PointParticleEmitter, SphereParticleEmitter, SphereDirectedParticleEmitter, CannonJSPlugin, AmmoJSPlugin, OimoJSPlugin, PostProcessRenderEffect, PostProcessRenderPipeline, PostProcessRenderPipelineManager, PostProcessRenderPipelineManagerSceneComponent, CubeMapToSphericalPolynomialTools, HDRTools, PanoramaToCubeMapTools, _DDSTextureLoader, _ENVTextureLoader, _KTXTextureLoader, _TGATextureLoader, CustomProceduralTexture, NoiseProceduralTexture, ProceduralTexture, ProceduralTextureSceneComponent, MultiplyBlock, AddBlock, ClampBlock, Vector2TransformBlock, Vector3TransformBlock, Vector4TransformBlock, MatrixMultiplicationBlock, NodeMaterialOptimizer, DefaultRenderingPipeline, LensRenderingPipeline, SSAO2RenderingPipeline, SSAORenderingPipeline, StandardRenderingPipeline, VertexOutputBlock, BonesBlock, InstancesBlock, MorphTargetsBlock, FragmentOutputBlock, AlphaTestBlock, RGBAMergerBlock, RGBMergerBlock, RGBASplitterBlock, RGBSplitterBlock, TextureBlock, ImageProcessingBlock, FogBlock */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* WEBPACK VAR INJECTION */(function(global) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Debug", function() { return Debug; }); +/* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../index */ "./index.ts"); +/* harmony import */ var _Debug_index__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Debug/index */ "./Debug/index.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AbstractScene", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AbstractScene"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KeepAssets", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["KeepAssets"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AssetContainer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AssetContainer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Node", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Node"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Scene", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Scene"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SceneComponentConstants", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SceneComponentConstants"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Stage", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Stage"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Action", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Action"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ActionEvent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ActionEvent"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ActionManager", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ActionManager"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Condition", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Condition"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ValueCondition", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ValueCondition"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PredicateCondition", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PredicateCondition"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StateCondition", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["StateCondition"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SwitchBooleanAction", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SwitchBooleanAction"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SetStateAction", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SetStateAction"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SetValueAction", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SetValueAction"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "IncrementValueAction", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["IncrementValueAction"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PlayAnimationAction", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PlayAnimationAction"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StopAnimationAction", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["StopAnimationAction"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DoNothingAction", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DoNothingAction"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CombineAction", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CombineAction"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ExecuteCodeAction", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ExecuteCodeAction"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SetParentAction", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SetParentAction"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PlaySoundAction", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PlaySoundAction"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StopSoundAction", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["StopSoundAction"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InterpolateValueAction", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["InterpolateValueAction"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Animatable", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Animatable"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_IAnimationState", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["_IAnimationState"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Animation", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Animation"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TargetedAnimation", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TargetedAnimation"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnimationGroup", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AnimationGroup"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnimationPropertiesOverride", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AnimationPropertiesOverride"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EasingFunction", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["EasingFunction"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CircleEase", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CircleEase"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BackEase", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BackEase"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BounceEase", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BounceEase"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CubicEase", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CubicEase"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ElasticEase", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ElasticEase"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ExponentialEase", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ExponentialEase"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PowerEase", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PowerEase"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "QuadraticEase", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["QuadraticEase"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "QuarticEase", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["QuarticEase"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "QuinticEase", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["QuinticEase"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SineEase", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SineEase"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BezierCurveEase", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BezierCurveEase"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RuntimeAnimation", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RuntimeAnimation"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnimationEvent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AnimationEvent"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnimationKeyInterpolation", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AnimationKeyInterpolation"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnimationRange", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AnimationRange"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Analyser", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Analyser"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AudioEngine", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AudioEngine"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AudioSceneComponent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AudioSceneComponent"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Sound", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Sound"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SoundTrack", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SoundTrack"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WeightedSound", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WeightedSound"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Bone", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Bone"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoneIKController", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BoneIKController"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoneLookController", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BoneLookController"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Skeleton", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Skeleton"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CameraInputTypes", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CameraInputTypes"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CameraInputsManager", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CameraInputsManager"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Camera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Camera"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TargetCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TargetCamera"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FreeCamera"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraInputsManager", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FreeCameraInputsManager"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TouchCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TouchCamera"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ArcRotateCamera"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraInputsManager", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ArcRotateCameraInputsManager"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DeviceOrientationCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DeviceOrientationCamera"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FlyCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FlyCamera"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FlyCameraInputsManager", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FlyCameraInputsManager"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FollowCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FollowCamera"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcFollowCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ArcFollowCamera"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GamepadCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["GamepadCamera"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UniversalCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["UniversalCamera"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VirtualJoysticksCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VirtualJoysticksCamera"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Collider", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Collider"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DefaultCollisionCoordinator", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DefaultCollisionCoordinator"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PickingInfo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PickingInfo"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "IntersectionInfo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["IntersectionInfo"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_MeshCollisionData", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["_MeshCollisionData"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoundingBox", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BoundingBox"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoundingInfo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BoundingInfo"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoundingSphere", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BoundingSphere"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Ray", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Ray"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AxesViewer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AxesViewer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoneAxesViewer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BoneAxesViewer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DebugLayer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DebugLayer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PhysicsViewer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PhysicsViewer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RayHelper", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RayHelper"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SkeletonViewer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SkeletonViewer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Constants", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Constants"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InstancingAttributeInfo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["InstancingAttributeInfo"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DepthTextureCreationOptions", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DepthTextureCreationOptions"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EngineCapabilities", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["EngineCapabilities"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Engine", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Engine"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EngineStore", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["EngineStore"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NullEngineOptions", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["NullEngineOptions"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NullEngine", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["NullEngine"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebGLPipelineContext", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebGLPipelineContext"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebGL2ShaderProcessor", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebGL2ShaderProcessor"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NativeEngineOptions", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["NativeEngineOptions"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NativeEngine", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["NativeEngine"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KeyboardEventTypes", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["KeyboardEventTypes"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KeyboardInfo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["KeyboardInfo"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KeyboardInfoPre", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["KeyboardInfoPre"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointerEventTypes", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointerInfoBase", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PointerInfoBase"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointerInfoPre", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PointerInfoPre"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointerInfo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PointerInfo"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ClipboardEventTypes", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ClipboardEventTypes"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ClipboardInfo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ClipboardInfo"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StickValues", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["StickValues"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Gamepad", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Gamepad"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GenericPad", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["GenericPad"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GamepadManager", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["GamepadManager"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GamepadSystemSceneComponent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["GamepadSystemSceneComponent"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Xbox360Button", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Xbox360Button"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Xbox360Dpad", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Xbox360Dpad"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Xbox360Pad", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Xbox360Pad"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AxisDragGizmo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AxisDragGizmo"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AxisScaleGizmo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AxisScaleGizmo"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoundingBoxGizmo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BoundingBoxGizmo"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Gizmo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Gizmo"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GizmoManager", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["GizmoManager"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PlaneRotationGizmo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PlaneRotationGizmo"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PositionGizmo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PositionGizmo"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RotationGizmo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RotationGizmo"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ScaleGizmo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ScaleGizmo"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LightGizmo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["LightGizmo"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EnvironmentHelper", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["EnvironmentHelper"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PhotoDome", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PhotoDome"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_forceSceneHelpersToBundle", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["_forceSceneHelpersToBundle"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VideoDome", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VideoDome"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EngineInstrumentation", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["EngineInstrumentation"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SceneInstrumentation", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SceneInstrumentation"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_TimeToken", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["_TimeToken"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EffectLayer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["EffectLayer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EffectLayerSceneComponent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["EffectLayerSceneComponent"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GlowLayer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["GlowLayer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HighlightLayer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["HighlightLayer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Layer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Layer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LayerSceneComponent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["LayerSceneComponent"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LensFlare", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["LensFlare"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LensFlareSystem", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["LensFlareSystem"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LensFlareSystemSceneComponent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["LensFlareSystemSceneComponent"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Light", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Light"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ShadowLight", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ShadowLight"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DirectionalLight", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DirectionalLight"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HemisphericLight", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["HemisphericLight"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointLight", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PointLight"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SpotLight", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SpotLight"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DefaultLoadingScreen", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DefaultLoadingScreen"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SceneLoaderProgressEvent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SceneLoaderProgressEvent"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SceneLoader", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SceneLoader"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SceneLoaderFlags", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SceneLoaderFlags"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ColorCurves", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ColorCurves"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EffectFallbacks", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["EffectFallbacks"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EffectCreationOptions", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["EffectCreationOptions"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Effect", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Effect"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FresnelParameters", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FresnelParameters"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ImageProcessingConfigurationDefines", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ImageProcessingConfigurationDefines"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ImageProcessingConfiguration", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ImageProcessingConfiguration"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Material", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Material"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MaterialDefines", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MaterialDefines"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MaterialHelper", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MaterialHelper"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MultiMaterial", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MultiMaterial"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PushMaterial", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PushMaterial"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ShaderMaterial", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ShaderMaterial"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StandardMaterialDefines", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["StandardMaterialDefines"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StandardMaterial", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["StandardMaterial"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BaseTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BaseTexture"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CubeTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CubeTexture"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DynamicTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DynamicTexture"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EquiRectangularCubeTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["EquiRectangularCubeTexture"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HDRCubeTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["HDRCubeTexture"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InternalTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["InternalTexture"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MirrorTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MirrorTexture"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MultiRenderTarget", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MultiRenderTarget"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RawTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RawTexture"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RenderTargetTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RenderTargetTexture"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Texture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Texture"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UniformBuffer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["UniformBuffer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MaterialFlags", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MaterialFlags"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Scalar", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Scalar"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ToGammaSpace", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ToGammaSpace"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ToLinearSpace", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ToLinearSpace"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Epsilon", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Epsilon"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Color3", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Color3"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Color4", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Color4"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Vector2", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Vector2"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Vector3", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Vector3"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Vector4", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Vector4"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Size", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Size"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Quaternion", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Quaternion"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Matrix", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Matrix"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Plane", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Plane"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Viewport", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Viewport"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Frustum", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Frustum"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Space", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Space"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Axis", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Axis"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BezierCurve", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BezierCurve"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Orientation", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Orientation"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Angle", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Angle"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Arc2", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Arc2"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Path2", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Path2"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Path3D", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Path3D"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Curve3", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Curve3"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PositionNormalVertex", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PositionNormalVertex"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PositionNormalTextureVertex", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PositionNormalTextureVertex"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Tmp", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Tmp"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SphericalHarmonics", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SphericalHarmonics"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SphericalPolynomial", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SphericalPolynomial"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AbstractMesh", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AbstractMesh"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Buffer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Buffer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VertexBuffer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CSG", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CSG"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Geometry", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Geometry"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GroundMesh", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["GroundMesh"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TrailMesh", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TrailMesh"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InstancedMesh", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["InstancedMesh"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LinesMesh", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["LinesMesh"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InstancedLinesMesh", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["InstancedLinesMesh"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_CreationDataStorage", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["_CreationDataStorage"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_InstancesBatch", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["_InstancesBatch"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Mesh", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Mesh"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VertexData", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VertexData"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MeshBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MeshBuilder"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SimplificationSettings", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SimplificationSettings"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SimplificationQueue", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SimplificationQueue"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SimplificationType", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SimplificationType"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SimplicationQueueSceneComponent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SimplicationQueueSceneComponent"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Polygon", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Polygon"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PolygonMeshBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PolygonMeshBuilder"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BaseSubMesh", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BaseSubMesh"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubMesh", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SubMesh"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MeshLODLevel", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MeshLODLevel"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TransformNode", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TransformNode"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoxBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BoxBuilder"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SphereBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SphereBuilder"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CylinderBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CylinderBuilder"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TorusBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TorusBuilder"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LinesBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["LinesBuilder"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PlaneBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PlaneBuilder"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GroundBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["GroundBuilder"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DataBuffer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DataBuffer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebGLDataBuffer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebGLDataBuffer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MorphTarget", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MorphTarget"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MorphTargetManager", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MorphTargetManager"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Database", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Database"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BaseParticleSystem", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BaseParticleSystem"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GPUParticleSystem", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["GPUParticleSystem"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Particle", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Particle"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ParticleHelper", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ParticleHelper"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ParticleSystem", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ParticleSystem"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_IDoNeedToBeInTheBuild", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["_IDoNeedToBeInTheBuild"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ParticleSystemSet", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ParticleSystemSet"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SolidParticle", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SolidParticle"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ModelShape", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ModelShape"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DepthSortedParticle", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DepthSortedParticle"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SolidParticleSystem", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SolidParticleSystem"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubEmitterType", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SubEmitterType"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubEmitter", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SubEmitter"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PhysicsEngine", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PhysicsEngine"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PhysicsEngineSceneComponent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PhysicsEngineSceneComponent"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PhysicsHelper", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PhysicsHelper"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PhysicsRadialExplosionEventOptions", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PhysicsRadialExplosionEventOptions"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PhysicsUpdraftEventOptions", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PhysicsUpdraftEventOptions"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PhysicsVortexEventOptions", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PhysicsVortexEventOptions"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PhysicsRadialImpulseFalloff", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PhysicsRadialImpulseFalloff"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PhysicsUpdraftMode", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PhysicsUpdraftMode"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PhysicsImpostor", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PhysicsImpostor"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PhysicsJoint", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PhysicsJoint"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DistanceJoint", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DistanceJoint"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MotorEnabledJoint", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MotorEnabledJoint"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HingeJoint", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["HingeJoint"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Hinge2Joint", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Hinge2Joint"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnaglyphPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AnaglyphPostProcess"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BlackAndWhitePostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BlackAndWhitePostProcess"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BloomEffect", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BloomEffect"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BloomMergePostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BloomMergePostProcess"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BlurPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BlurPostProcess"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ChromaticAberrationPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ChromaticAberrationPostProcess"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CircleOfConfusionPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CircleOfConfusionPostProcess"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ColorCorrectionPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ColorCorrectionPostProcess"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ConvolutionPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ConvolutionPostProcess"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DepthOfFieldBlurPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DepthOfFieldBlurPostProcess"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DepthOfFieldEffectBlurLevel", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DepthOfFieldEffectBlurLevel"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DepthOfFieldEffect", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DepthOfFieldEffect"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DepthOfFieldMergePostProcessOptions", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DepthOfFieldMergePostProcessOptions"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DepthOfFieldMergePostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DepthOfFieldMergePostProcess"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DisplayPassPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DisplayPassPostProcess"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ExtractHighlightsPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ExtractHighlightsPostProcess"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FilterPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FilterPostProcess"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FxaaPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FxaaPostProcess"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GrainPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["GrainPostProcess"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HighlightsPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["HighlightsPostProcess"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ImageProcessingPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ImageProcessingPostProcess"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MotionBlurPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MotionBlurPostProcess"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PassPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PassPostProcess"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PassCubePostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PassCubePostProcess"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PostProcess"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PostProcessManager", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PostProcessManager"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RefractionPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RefractionPostProcess"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SharpenPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SharpenPostProcess"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StereoscopicInterlacePostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["StereoscopicInterlacePostProcess"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TonemappingOperator", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TonemappingOperator"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TonemapPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TonemapPostProcess"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VolumetricLightScatteringPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VolumetricLightScatteringPostProcess"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRDistortionCorrectionPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VRDistortionCorrectionPostProcess"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRMultiviewToSingleviewPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VRMultiviewToSingleviewPostProcess"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReflectionProbe", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ReflectionProbe"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoundingBoxRenderer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BoundingBoxRenderer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DepthRenderer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DepthRenderer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DepthRendererSceneComponent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DepthRendererSceneComponent"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EdgesRenderer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["EdgesRenderer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LineEdgesRenderer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["LineEdgesRenderer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GeometryBufferRenderer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["GeometryBufferRenderer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GeometryBufferRendererSceneComponent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["GeometryBufferRendererSceneComponent"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OutlineRenderer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["OutlineRenderer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RenderingGroup", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RenderingGroup"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RenderingGroupInfo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RenderingGroupInfo"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RenderingManager", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RenderingManager"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UtilityLayerRenderer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["UtilityLayerRenderer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Sprite", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Sprite"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SpriteManager", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SpriteManager"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SpriteSceneComponent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SpriteSceneComponent"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_AlphaState", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["_AlphaState"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_DepthCullingState", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["_DepthCullingState"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_StencilState", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["_StencilState"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AndOrNotEvaluator", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AndOrNotEvaluator"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AssetTaskState", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AssetTaskState"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AbstractAssetTask", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AbstractAssetTask"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AssetsProgressEvent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AssetsProgressEvent"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MeshAssetTask", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MeshAssetTask"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TextFileAssetTask", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TextFileAssetTask"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BinaryFileAssetTask", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BinaryFileAssetTask"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ImageAssetTask", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ImageAssetTask"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TextureAssetTask", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TextureAssetTask"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CubeTextureAssetTask", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CubeTextureAssetTask"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HDRCubeTextureAssetTask", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["HDRCubeTextureAssetTask"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EquiRectangularCubeTextureAssetTask", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["EquiRectangularCubeTextureAssetTask"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AssetsManager", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AssetsManager"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DDSTools", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DDSTools"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "expandToProperty", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["expandToProperty"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "serialize", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["serialize"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "serializeAsTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["serializeAsTexture"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "serializeAsColor3", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["serializeAsColor3"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "serializeAsFresnelParameters", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["serializeAsFresnelParameters"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "serializeAsVector2", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["serializeAsVector2"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "serializeAsVector3", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["serializeAsVector3"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "serializeAsMeshReference", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["serializeAsMeshReference"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "serializeAsColorCurves", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["serializeAsColorCurves"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "serializeAsColor4", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["serializeAsColor4"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "serializeAsImageProcessingConfiguration", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["serializeAsImageProcessingConfiguration"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "serializeAsQuaternion", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["serializeAsQuaternion"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "serializeAsMatrix", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["serializeAsMatrix"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "serializeAsCameraReference", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["serializeAsCameraReference"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SerializationHelper", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SerializationHelper"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Deferred", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Deferred"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EnvironmentTextureTools", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["EnvironmentTextureTools"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MeshExploder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MeshExploder"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FilesInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FilesInput"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KhronosTextureContainer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["KhronosTextureContainer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EventState", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["EventState"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Observer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Observer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MultiObserver", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MultiObserver"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Observable", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Observable"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PerformanceMonitor", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PerformanceMonitor"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RollingAverage", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RollingAverage"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PromisePolyfill", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PromisePolyfill"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SceneOptimization", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SceneOptimization"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TextureOptimization", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TextureOptimization"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HardwareScalingOptimization", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["HardwareScalingOptimization"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ShadowsOptimization", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ShadowsOptimization"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PostProcessesOptimization", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PostProcessesOptimization"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LensFlaresOptimization", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["LensFlaresOptimization"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CustomOptimization", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CustomOptimization"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ParticlesOptimization", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ParticlesOptimization"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RenderTargetsOptimization", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RenderTargetsOptimization"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MergeMeshesOptimization", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MergeMeshesOptimization"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SceneOptimizerOptions", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SceneOptimizerOptions"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SceneOptimizer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SceneOptimizer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SceneSerializer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SceneSerializer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SmartArray", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SmartArray"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SmartArrayNoDuplicate", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SmartArrayNoDuplicate"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StringDictionary", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["StringDictionary"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Tags", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Tags"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TextureTools", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TextureTools"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TGATools", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TGATools"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ColorGradient", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ColorGradient"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Color3Gradient", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Color3Gradient"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FactorGradient", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FactorGradient"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LoadFileError", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["LoadFileError"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RetryStrategy", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RetryStrategy"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Tools", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Tools"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PerfCounter", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PerfCounter"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "className", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["className"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AsyncLoop", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AsyncLoop"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VideoRecorder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VideoRecorder"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "JoystickAxis", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["JoystickAxis"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VirtualJoystick", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VirtualJoystick"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WorkerPool", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WorkerPool"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Logger", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Logger"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_TypeStore", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["_TypeStore"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FilesInputStore", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FilesInputStore"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DeepCopier", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DeepCopier"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PivotTools", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PivotTools"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PrecisionDate", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PrecisionDate"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ScreenshotTools", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ScreenshotTools"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebRequest", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebRequest"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InspectableType", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["InspectableType"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BRDFTextureTools", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BRDFTextureTools"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AutoRotationBehavior", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AutoRotationBehavior"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BouncingBehavior", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BouncingBehavior"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FramingBehavior", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FramingBehavior"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AttachToBoxBehavior", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AttachToBoxBehavior"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FadeInOutBehavior", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FadeInOutBehavior"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MultiPointerScaleBehavior", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MultiPointerScaleBehavior"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointerDragBehavior", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PointerDragBehavior"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SixDofDragBehavior", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SixDofDragBehavior"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraGamepadInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ArcRotateCameraGamepadInput"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraKeyboardMoveInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ArcRotateCameraKeyboardMoveInput"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraMouseWheelInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ArcRotateCameraMouseWheelInput"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraPointersInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ArcRotateCameraPointersInput"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraVRDeviceOrientationInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ArcRotateCameraVRDeviceOrientationInput"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FlyCameraKeyboardInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FlyCameraKeyboardInput"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FlyCameraMouseInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FlyCameraMouseInput"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FollowCameraKeyboardMoveInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FollowCameraKeyboardMoveInput"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FollowCameraMouseWheelInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FollowCameraMouseWheelInput"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FollowCameraPointersInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FollowCameraPointersInput"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraDeviceOrientationInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FreeCameraDeviceOrientationInput"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraGamepadInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FreeCameraGamepadInput"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraKeyboardMoveInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FreeCameraKeyboardMoveInput"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraMouseInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FreeCameraMouseInput"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraTouchInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FreeCameraTouchInput"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraVirtualJoystickInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FreeCameraVirtualJoystickInput"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnaglyphArcRotateCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AnaglyphArcRotateCamera"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnaglyphFreeCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AnaglyphFreeCamera"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnaglyphGamepadCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AnaglyphGamepadCamera"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnaglyphUniversalCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AnaglyphUniversalCamera"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StereoscopicArcRotateCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["StereoscopicArcRotateCamera"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StereoscopicFreeCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["StereoscopicFreeCamera"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StereoscopicGamepadCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["StereoscopicGamepadCamera"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StereoscopicUniversalCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["StereoscopicUniversalCamera"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRCameraMetrics", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VRCameraMetrics"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRDeviceOrientationArcRotateCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VRDeviceOrientationArcRotateCamera"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRDeviceOrientationFreeCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VRDeviceOrientationFreeCamera"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRDeviceOrientationGamepadCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VRDeviceOrientationGamepadCamera"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OnAfterEnteringVRObservableEvent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["OnAfterEnteringVRObservableEvent"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRExperienceHelper", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VRExperienceHelper"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebVRFreeCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebVRFreeCamera"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXRCamera"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXREnterExitUIButton", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXREnterExitUIButton"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXREnterExitUIOptions", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXREnterExitUIOptions"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXREnterExitUI", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXREnterExitUI"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRState", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXRState"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRExperienceHelper", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXRExperienceHelper"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRController", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXRController"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXRInput"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRManagedOutputCanvas", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXRManagedOutputCanvas"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRSessionManager", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXRSessionManager"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Octree", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Octree"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OctreeBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["OctreeBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OctreeSceneComponent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["OctreeSceneComponent"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_OcclusionDataStorage", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["_OcclusionDataStorage"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_forceTransformFeedbackToBundle", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["_forceTransformFeedbackToBundle"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DaydreamController", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DaydreamController"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GearVRController", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["GearVRController"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GenericController", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["GenericController"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OculusTouchController", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["OculusTouchController"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PoseEnabledControllerType", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PoseEnabledControllerType"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PoseEnabledControllerHelper", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PoseEnabledControllerHelper"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PoseEnabledController", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PoseEnabledController"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ViveController", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ViveController"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebVRController", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebVRController"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WindowsMotionController", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WindowsMotionController"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ShadowGenerator", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ShadowGenerator"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ShadowGeneratorSceneComponent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ShadowGeneratorSceneComponent"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_BabylonLoaderRegistered", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["_BabylonLoaderRegistered"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BackgroundMaterial", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BackgroundMaterial"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRMaterialDefines", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PBRMaterialDefines"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRBaseMaterial", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PBRBaseMaterial"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRBaseSimpleMaterial", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PBRBaseSimpleMaterial"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRMaterial", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PBRMaterial"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRMetallicRoughnessMaterial", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PBRMetallicRoughnessMaterial"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRSpecularGlossinessMaterial", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PBRSpecularGlossinessMaterial"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ColorGradingTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ColorGradingTexture"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RawCubeTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RawCubeTexture"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RawTexture3D", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RawTexture3D"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RefractionTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RefractionTexture"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VideoTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VideoTexture"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HtmlElementTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["HtmlElementTexture"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialBlockTargets", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockTargets"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialBlockConnectionPointTypes", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialConnectionPoint", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialConnectionPoint"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialDefines", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialDefines"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterial", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["NodeMaterial"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialWellKnownValues", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialWellKnownValues"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DracoCompression", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DracoCompression"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TiledBoxBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TiledBoxBuilder"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DiscBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DiscBuilder"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RibbonBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RibbonBuilder"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HemisphereBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["HemisphereBuilder"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TorusKnotBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TorusKnotBuilder"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PolygonBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PolygonBuilder"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ShapeBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ShapeBuilder"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LatheBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["LatheBuilder"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TiledPlaneBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TiledPlaneBuilder"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TubeBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TubeBuilder"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PolyhedronBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PolyhedronBuilder"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "IcoSphereBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["IcoSphereBuilder"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DecalBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DecalBuilder"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoxParticleEmitter", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BoxParticleEmitter"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ConeParticleEmitter", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ConeParticleEmitter"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CylinderParticleEmitter", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CylinderParticleEmitter"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CylinderDirectedParticleEmitter", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CylinderDirectedParticleEmitter"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HemisphericParticleEmitter", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["HemisphericParticleEmitter"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointParticleEmitter", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PointParticleEmitter"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SphereParticleEmitter", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SphereParticleEmitter"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SphereDirectedParticleEmitter", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SphereDirectedParticleEmitter"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CannonJSPlugin", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CannonJSPlugin"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AmmoJSPlugin", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AmmoJSPlugin"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OimoJSPlugin", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["OimoJSPlugin"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PostProcessRenderEffect", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PostProcessRenderEffect"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PostProcessRenderPipeline", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PostProcessRenderPipeline"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PostProcessRenderPipelineManager", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PostProcessRenderPipelineManager"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PostProcessRenderPipelineManagerSceneComponent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PostProcessRenderPipelineManagerSceneComponent"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CubeMapToSphericalPolynomialTools", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CubeMapToSphericalPolynomialTools"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HDRTools", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["HDRTools"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PanoramaToCubeMapTools", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PanoramaToCubeMapTools"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_DDSTextureLoader", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["_DDSTextureLoader"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_ENVTextureLoader", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["_ENVTextureLoader"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_KTXTextureLoader", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["_KTXTextureLoader"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_TGATextureLoader", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["_TGATextureLoader"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CustomProceduralTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CustomProceduralTexture"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NoiseProceduralTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["NoiseProceduralTexture"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ProceduralTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ProceduralTexture"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ProceduralTextureSceneComponent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ProceduralTextureSceneComponent"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MultiplyBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MultiplyBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AddBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AddBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ClampBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ClampBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Vector2TransformBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Vector2TransformBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Vector3TransformBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Vector3TransformBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Vector4TransformBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Vector4TransformBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MatrixMultiplicationBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MatrixMultiplicationBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialOptimizer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialOptimizer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DefaultRenderingPipeline", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DefaultRenderingPipeline"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LensRenderingPipeline", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["LensRenderingPipeline"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SSAO2RenderingPipeline", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SSAO2RenderingPipeline"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SSAORenderingPipeline", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SSAORenderingPipeline"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StandardRenderingPipeline", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["StandardRenderingPipeline"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VertexOutputBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VertexOutputBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BonesBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BonesBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InstancesBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["InstancesBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MorphTargetsBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MorphTargetsBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FragmentOutputBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FragmentOutputBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AlphaTestBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AlphaTestBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RGBAMergerBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RGBAMergerBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RGBMergerBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RGBMergerBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RGBASplitterBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RGBASplitterBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RGBSplitterBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RGBSplitterBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TextureBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TextureBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ImageProcessingBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ImageProcessingBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FogBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FogBlock"]; }); + + + +/** + * Legacy support, defining window.BABYLON (global variable). + * + * This is the entry point for the UMD module. + * The entry point for a future ESM package should be index.ts + */ +var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : undefined); +if (typeof globalObject !== "undefined") { + globalObject.BABYLON = BABYLON; + globalObject.BABYLON = globalObject.BABYLON || {}; + var BABYLON = globalObject.BABYLON; + BABYLON.Debug = BABYLON.Debug || {}; + var keys = []; + for (var key in _Debug_index__WEBPACK_IMPORTED_MODULE_1__) { + BABYLON.Debug[key] = _Debug_index__WEBPACK_IMPORTED_MODULE_1__[key]; + keys.push(key); + } + for (var key in _index__WEBPACK_IMPORTED_MODULE_0__) { + BABYLON[key] = _index__WEBPACK_IMPORTED_MODULE_0__[key]; + } +} + +var Debug = { + AxesViewer: _Debug_index__WEBPACK_IMPORTED_MODULE_1__["AxesViewer"], + BoneAxesViewer: _Debug_index__WEBPACK_IMPORTED_MODULE_1__["BoneAxesViewer"], + PhysicsViewer: _Debug_index__WEBPACK_IMPORTED_MODULE_1__["PhysicsViewer"], + SkeletonViewer: _Debug_index__WEBPACK_IMPORTED_MODULE_1__["SkeletonViewer"], +}; + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../node_modules/webpack/buildin/global.js */ "../node_modules/webpack/buildin/global.js"))) + +/***/ }), + +/***/ "./LensFlares/index.ts": +/*!*****************************!*\ + !*** ./LensFlares/index.ts ***! + \*****************************/ +/*! exports provided: LensFlare, LensFlareSystem, LensFlareSystemSceneComponent */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _lensFlare__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./lensFlare */ "./LensFlares/lensFlare.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LensFlare", function() { return _lensFlare__WEBPACK_IMPORTED_MODULE_0__["LensFlare"]; }); + +/* harmony import */ var _lensFlareSystem__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./lensFlareSystem */ "./LensFlares/lensFlareSystem.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LensFlareSystem", function() { return _lensFlareSystem__WEBPACK_IMPORTED_MODULE_1__["LensFlareSystem"]; }); + +/* harmony import */ var _lensFlareSystemSceneComponent__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./lensFlareSystemSceneComponent */ "./LensFlares/lensFlareSystemSceneComponent.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LensFlareSystemSceneComponent", function() { return _lensFlareSystemSceneComponent__WEBPACK_IMPORTED_MODULE_2__["LensFlareSystemSceneComponent"]; }); + + + + + + +/***/ }), + +/***/ "./LensFlares/lensFlare.ts": +/*!*********************************!*\ + !*** ./LensFlares/lensFlare.ts ***! + \*********************************/ +/*! exports provided: LensFlare */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LensFlare", function() { return LensFlare; }); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Materials/Textures/texture */ "./Materials/Textures/texture.ts"); +/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts"); + + + +/** + * This represents one of the lens effect in a `lensFlareSystem`. + * It controls one of the indiviual texture used in the effect. + * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares + */ +var LensFlare = /** @class */ (function () { + /** + * Instantiates a new Lens Flare. + * This represents one of the lens effect in a `lensFlareSystem`. + * It controls one of the indiviual texture used in the effect. + * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares + * @param size Define the size of the lens flare in the system (a floating value between 0 and 1) + * @param position Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind. + * @param color Define the lens color + * @param imgUrl Define the lens texture url + * @param system Define the `lensFlareSystem` this flare is part of + */ + function LensFlare( + /** + * Define the size of the lens flare in the system (a floating value between 0 and 1) + */ + size, + /** + * Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind. + */ + position, color, imgUrl, system) { + this.size = size; + this.position = position; + /** + * Define the alpha mode to render this particular lens. + */ + this.alphaMode = _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].ALPHA_ONEONE; + this.color = color || new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Color3"](1, 1, 1); + this.texture = imgUrl ? new _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_1__["Texture"](imgUrl, system.getScene(), true) : null; + this._system = system; + system.lensFlares.push(this); + } + /** + * Creates a new Lens Flare. + * This represents one of the lens effect in a `lensFlareSystem`. + * It controls one of the indiviual texture used in the effect. + * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares + * @param size Define the size of the lens flare (a floating value between 0 and 1) + * @param position Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind. + * @param color Define the lens color + * @param imgUrl Define the lens texture url + * @param system Define the `lensFlareSystem` this flare is part of + * @returns The newly created Lens Flare + */ + LensFlare.AddFlare = function (size, position, color, imgUrl, system) { + return new LensFlare(size, position, color, imgUrl, system); + }; + /** + * Dispose and release the lens flare with its associated resources. + */ + LensFlare.prototype.dispose = function () { + if (this.texture) { + this.texture.dispose(); + } + // Remove from scene + var index = this._system.lensFlares.indexOf(this); + this._system.lensFlares.splice(index, 1); + }; + return LensFlare; +}()); + + + +/***/ }), + +/***/ "./LensFlares/lensFlareSystem.ts": +/*!***************************************!*\ + !*** ./LensFlares/lensFlareSystem.ts ***! + \***************************************/ +/*! exports provided: LensFlareSystem */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LensFlareSystem", function() { return LensFlareSystem; }); +/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/tools */ "./Misc/tools.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Maths_math_scalar__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math.scalar */ "./Maths/math.scalar.ts"); +/* harmony import */ var _Engines_engineStore__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Engines/engineStore */ "./Engines/engineStore.ts"); +/* harmony import */ var _Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Meshes/buffer */ "./Meshes/buffer.ts"); +/* harmony import */ var _Culling_ray__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Culling/ray */ "./Culling/ray.ts"); +/* harmony import */ var _Materials_material__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Materials/material */ "./Materials/material.ts"); +/* harmony import */ var _lensFlare__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./lensFlare */ "./LensFlares/lensFlare.ts"); +/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts"); +/* harmony import */ var _Shaders_lensFlare_fragment__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Shaders/lensFlare.fragment */ "./Shaders/lensFlare.fragment.ts"); +/* harmony import */ var _Shaders_lensFlare_vertex__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../Shaders/lensFlare.vertex */ "./Shaders/lensFlare.vertex.ts"); +/* harmony import */ var _Misc_devTools__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../Misc/devTools */ "./Misc/devTools.ts"); + + + + + + + + + + + + +/** + * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses. + * It is usually composed of several `lensFlare`. + * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares + */ +var LensFlareSystem = /** @class */ (function () { + /** + * Instantiates a lens flare system. + * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses. + * It is usually composed of several `lensFlare`. + * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares + * @param name Define the name of the lens flare system in the scene + * @param emitter Define the source (the emitter) of the lens flares (it can be a camera, a light or a mesh). + * @param scene Define the scene the lens flare system belongs to + */ + function LensFlareSystem( + /** + * Define the name of the lens flare system + */ + name, emitter, scene) { + this.name = name; + /** + * List of lens flares used in this system. + */ + this.lensFlares = new Array(); + /** + * Define a limit from the border the lens flare can be visible. + */ + this.borderLimit = 300; + /** + * Define a viewport border we do not want to see the lens flare in. + */ + this.viewportBorder = 0; + /** + * Restricts the rendering of the effect to only the camera rendering this layer mask. + */ + this.layerMask = 0x0FFFFFFF; + this._vertexBuffers = {}; + this._isEnabled = true; + this._scene = scene || _Engines_engineStore__WEBPACK_IMPORTED_MODULE_3__["EngineStore"].LastCreatedScene; + LensFlareSystem._SceneComponentInitialization(this._scene); + this._emitter = emitter; + this.id = name; + scene.lensFlareSystems.push(this); + this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); }; + var engine = scene.getEngine(); + // VBO + var vertices = []; + vertices.push(1, 1); + vertices.push(-1, 1); + vertices.push(-1, -1); + vertices.push(1, -1); + this._vertexBuffers[_Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"].PositionKind] = new _Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"](engine, vertices, _Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"].PositionKind, false, false, 2); + // Indices + var indices = []; + indices.push(0); + indices.push(1); + indices.push(2); + indices.push(0); + indices.push(2); + indices.push(3); + this._indexBuffer = engine.createIndexBuffer(indices); + // Effects + this._effect = engine.createEffect("lensFlare", [_Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"].PositionKind], ["color", "viewportMatrix"], ["textureSampler"], ""); + } + Object.defineProperty(LensFlareSystem.prototype, "isEnabled", { + /** + * Define if the lens flare system is enabled. + */ + get: function () { + return this._isEnabled; + }, + set: function (value) { + this._isEnabled = value; + }, + enumerable: true, + configurable: true + }); + /** + * Get the scene the effects belongs to. + * @returns the scene holding the lens flare system + */ + LensFlareSystem.prototype.getScene = function () { + return this._scene; + }; + /** + * Get the emitter of the lens flare system. + * It defines the source of the lens flares (it can be a camera, a light or a mesh). + * @returns the emitter of the lens flare system + */ + LensFlareSystem.prototype.getEmitter = function () { + return this._emitter; + }; + /** + * Set the emitter of the lens flare system. + * It defines the source of the lens flares (it can be a camera, a light or a mesh). + * @param newEmitter Define the new emitter of the system + */ + LensFlareSystem.prototype.setEmitter = function (newEmitter) { + this._emitter = newEmitter; + }; + /** + * Get the lens flare system emitter position. + * The emitter defines the source of the lens flares (it can be a camera, a light or a mesh). + * @returns the position + */ + LensFlareSystem.prototype.getEmitterPosition = function () { + return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position; + }; + /** + * @hidden + */ + LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) { + var position = this.getEmitterPosition(); + position = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Project(position, _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Identity(), this._scene.getTransformMatrix(), globalViewport); + this._positionX = position.x; + this._positionY = position.y; + position = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix()); + if (this.viewportBorder > 0) { + globalViewport.x -= this.viewportBorder; + globalViewport.y -= this.viewportBorder; + globalViewport.width += this.viewportBorder * 2; + globalViewport.height += this.viewportBorder * 2; + position.x += this.viewportBorder; + position.y += this.viewportBorder; + this._positionX += this.viewportBorder; + this._positionY += this.viewportBorder; + } + if (position.z > 0) { + if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) { + if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height)) { + return true; + } + } + return true; + } + return false; + }; + /** @hidden */ + LensFlareSystem.prototype._isVisible = function () { + if (!this._isEnabled || !this._scene.activeCamera) { + return false; + } + var emitterPosition = this.getEmitterPosition(); + var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition); + var distance = direction.length(); + direction.normalize(); + var ray = new _Culling_ray__WEBPACK_IMPORTED_MODULE_5__["Ray"](this._scene.activeCamera.globalPosition, direction); + var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true); + return !pickInfo || !pickInfo.hit || pickInfo.distance > distance; + }; + /** + * @hidden + */ + LensFlareSystem.prototype.render = function () { + if (!this._effect.isReady() || !this._scene.activeCamera) { + return false; + } + var engine = this._scene.getEngine(); + var viewport = this._scene.activeCamera.viewport; + var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true)); + // Position + if (!this.computeEffectivePosition(globalViewport)) { + return false; + } + // Visibility + if (!this._isVisible()) { + return false; + } + // Intensity + var awayX; + var awayY; + if (this._positionX < this.borderLimit + globalViewport.x) { + awayX = this.borderLimit + globalViewport.x - this._positionX; + } + else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) { + awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit; + } + else { + awayX = 0; + } + if (this._positionY < this.borderLimit + globalViewport.y) { + awayY = this.borderLimit + globalViewport.y - this._positionY; + } + else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) { + awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit; + } + else { + awayY = 0; + } + var away = (awayX > awayY) ? awayX : awayY; + away -= this.viewportBorder; + if (away > this.borderLimit) { + away = this.borderLimit; + } + var intensity = 1.0 - _Maths_math_scalar__WEBPACK_IMPORTED_MODULE_2__["Scalar"].Clamp(away / this.borderLimit, 0, 1); + if (intensity < 0) { + return false; + } + if (intensity > 1.0) { + intensity = 1.0; + } + if (this.viewportBorder > 0) { + globalViewport.x += this.viewportBorder; + globalViewport.y += this.viewportBorder; + globalViewport.width -= this.viewportBorder * 2; + globalViewport.height -= this.viewportBorder * 2; + this._positionX -= this.viewportBorder; + this._positionY -= this.viewportBorder; + } + // Position + var centerX = globalViewport.x + globalViewport.width / 2; + var centerY = globalViewport.y + globalViewport.height / 2; + var distX = centerX - this._positionX; + var distY = centerY - this._positionY; + // Effects + engine.enableEffect(this._effect); + engine.setState(false); + engine.setDepthBuffer(false); + // VBOs + engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect); + // Flares + for (var index = 0; index < this.lensFlares.length; index++) { + var flare = this.lensFlares[index]; + engine.setAlphaMode(flare.alphaMode); + var x = centerX - (distX * flare.position); + var y = centerY - (distY * flare.position); + var cw = flare.size; + var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true); + var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0; + var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2)); + var viewportMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1); + this._effect.setMatrix("viewportMatrix", viewportMatrix); + // Texture + this._effect.setTexture("textureSampler", flare.texture); + // Color + this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0); + // Draw order + engine.drawElementsType(_Materials_material__WEBPACK_IMPORTED_MODULE_6__["Material"].TriangleFillMode, 0, 6); + } + engine.setDepthBuffer(true); + engine.setAlphaMode(_Engines_constants__WEBPACK_IMPORTED_MODULE_8__["Constants"].ALPHA_DISABLE); + return true; + }; + /** + * Dispose and release the lens flare with its associated resources. + */ + LensFlareSystem.prototype.dispose = function () { + var vertexBuffer = this._vertexBuffers[_Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"].PositionKind]; + if (vertexBuffer) { + vertexBuffer.dispose(); + this._vertexBuffers[_Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"].PositionKind] = null; + } + if (this._indexBuffer) { + this._scene.getEngine()._releaseBuffer(this._indexBuffer); + this._indexBuffer = null; + } + while (this.lensFlares.length) { + this.lensFlares[0].dispose(); + } + // Remove from scene + var index = this._scene.lensFlareSystems.indexOf(this); + this._scene.lensFlareSystems.splice(index, 1); + }; + /** + * Parse a lens flare system from a JSON repressentation + * @param parsedLensFlareSystem Define the JSON to parse + * @param scene Define the scene the parsed system should be instantiated in + * @param rootUrl Define the rootUrl of the load sequence to easily find a load relative dependencies such as textures + * @returns the parsed system + */ + LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) { + var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId); + var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId; + var lensFlareSystem = new LensFlareSystem(name, emitter, scene); + lensFlareSystem.id = parsedLensFlareSystem.id || name; + lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit; + for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) { + var parsedFlare = parsedLensFlareSystem.flares[index]; + _lensFlare__WEBPACK_IMPORTED_MODULE_7__["LensFlare"].AddFlare(parsedFlare.size, parsedFlare.position, _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Color3"].FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem); + } + return lensFlareSystem; + }; + /** + * Serialize the current Lens Flare System into a JSON representation. + * @returns the serialized JSON + */ + LensFlareSystem.prototype.serialize = function () { + var serializationObject = {}; + serializationObject.id = this.id; + serializationObject.name = this.name; + serializationObject.emitterId = this.getEmitter().id; + serializationObject.borderLimit = this.borderLimit; + serializationObject.flares = []; + for (var index = 0; index < this.lensFlares.length; index++) { + var flare = this.lensFlares[index]; + serializationObject.flares.push({ + size: flare.size, + position: flare.position, + color: flare.color.asArray(), + textureName: _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].GetFilename(flare.texture ? flare.texture.name : "") + }); + } + return serializationObject; + }; + /** @hidden */ + LensFlareSystem._SceneComponentInitialization = function (_) { + throw _Misc_devTools__WEBPACK_IMPORTED_MODULE_11__["_DevTools"].WarnImport("LensFlareSystemSceneComponent"); + }; + return LensFlareSystem; +}()); + + + +/***/ }), + +/***/ "./LensFlares/lensFlareSystemSceneComponent.ts": +/*!*****************************************************!*\ + !*** ./LensFlares/lensFlareSystemSceneComponent.ts ***! + \*****************************************************/ +/*! exports provided: LensFlareSystemSceneComponent */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LensFlareSystemSceneComponent", function() { return LensFlareSystemSceneComponent; }); +/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/tools */ "./Misc/tools.ts"); +/* harmony import */ var _sceneComponent__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../sceneComponent */ "./sceneComponent.ts"); +/* harmony import */ var _abstractScene__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../abstractScene */ "./abstractScene.ts"); +/* harmony import */ var _lensFlareSystem__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./lensFlareSystem */ "./LensFlares/lensFlareSystem.ts"); + + + + +// Adds the parser to the scene parsers. +_abstractScene__WEBPACK_IMPORTED_MODULE_2__["AbstractScene"].AddParser(_sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) { + // Lens flares + if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) { + if (!container.lensFlareSystems) { + container.lensFlareSystems = new Array(); + } + for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) { + var parsedLensFlareSystem = parsedData.lensFlareSystems[index]; + var lf = _lensFlareSystem__WEBPACK_IMPORTED_MODULE_3__["LensFlareSystem"].Parse(parsedLensFlareSystem, scene, rootUrl); + container.lensFlareSystems.push(lf); + } + } +}); +_abstractScene__WEBPACK_IMPORTED_MODULE_2__["AbstractScene"].prototype.getLensFlareSystemByName = function (name) { + for (var index = 0; index < this.lensFlareSystems.length; index++) { + if (this.lensFlareSystems[index].name === name) { + return this.lensFlareSystems[index]; + } + } + return null; +}; +_abstractScene__WEBPACK_IMPORTED_MODULE_2__["AbstractScene"].prototype.getLensFlareSystemByID = function (id) { + for (var index = 0; index < this.lensFlareSystems.length; index++) { + if (this.lensFlareSystems[index].id === id) { + return this.lensFlareSystems[index]; + } + } + return null; +}; +_abstractScene__WEBPACK_IMPORTED_MODULE_2__["AbstractScene"].prototype.removeLensFlareSystem = function (toRemove) { + var index = this.lensFlareSystems.indexOf(toRemove); + if (index !== -1) { + this.lensFlareSystems.splice(index, 1); + } + return index; +}; +_abstractScene__WEBPACK_IMPORTED_MODULE_2__["AbstractScene"].prototype.addLensFlareSystem = function (newLensFlareSystem) { + this.lensFlareSystems.push(newLensFlareSystem); +}; +/** + * Defines the lens flare scene component responsible to manage any lens flares + * in a given scene. + */ +var LensFlareSystemSceneComponent = /** @class */ (function () { + /** + * Creates a new instance of the component for the given scene + * @param scene Defines the scene to register the component in + */ + function LensFlareSystemSceneComponent(scene) { + /** + * The component name helpfull to identify the component in the list of scene components. + */ + this.name = _sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].NAME_LENSFLARESYSTEM; + this.scene = scene; + scene.lensFlareSystems = new Array(); + } + /** + * Registers the component in a given scene + */ + LensFlareSystemSceneComponent.prototype.register = function () { + this.scene._afterCameraDrawStage.registerStep(_sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw); + }; + /** + * Rebuilds the elements related to this component in case of + * context lost for instance. + */ + LensFlareSystemSceneComponent.prototype.rebuild = function () { + // Nothing to do for lens flare + }; + /** + * Adds all the elements from the container to the scene + * @param container the container holding the elements + */ + LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) { + var _this = this; + if (!container.lensFlareSystems) { + return; + } + container.lensFlareSystems.forEach(function (o) { + _this.scene.addLensFlareSystem(o); + }); + }; + /** + * Removes all the elements in the container from the scene + * @param container contains the elements to remove + * @param dispose if the removed element should be disposed (default: false) + */ + LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container, dispose) { + var _this = this; + if (!container.lensFlareSystems) { + return; + } + container.lensFlareSystems.forEach(function (o) { + _this.scene.removeLensFlareSystem(o); + if (dispose) { + o.dispose(); + } + }); + }; + /** + * Serializes the component data to the specified json object + * @param serializationObject The object to serialize to + */ + LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) { + // Lens flares + serializationObject.lensFlareSystems = []; + var lensFlareSystems = this.scene.lensFlareSystems; + for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) { + var lensFlareSystem = lensFlareSystems_1[_i]; + serializationObject.lensFlareSystems.push(lensFlareSystem.serialize()); + } + }; + /** + * Disposes the component and the associated ressources. + */ + LensFlareSystemSceneComponent.prototype.dispose = function () { + var lensFlareSystems = this.scene.lensFlareSystems; + while (lensFlareSystems.length) { + lensFlareSystems[0].dispose(); + } + }; + LensFlareSystemSceneComponent.prototype._draw = function (camera) { + // Lens flares + if (this.scene.lensFlaresEnabled) { + var lensFlareSystems = this.scene.lensFlareSystems; + _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0); + for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) { + var lensFlareSystem = lensFlareSystems_2[_i]; + if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) { + lensFlareSystem.render(); + } + } + _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0); + } + }; + return LensFlareSystemSceneComponent; +}()); + +_lensFlareSystem__WEBPACK_IMPORTED_MODULE_3__["LensFlareSystem"]._SceneComponentInitialization = function (scene) { + var component = scene._getComponent(_sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].NAME_LENSFLARESYSTEM); + if (!component) { + component = new LensFlareSystemSceneComponent(scene); + scene._addComponent(component); + } +}; + + +/***/ }), + +/***/ "./Lights/Shadows/index.ts": +/*!*********************************!*\ + !*** ./Lights/Shadows/index.ts ***! + \*********************************/ +/*! exports provided: ShadowGenerator, ShadowGeneratorSceneComponent */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _shadowGenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./shadowGenerator */ "./Lights/Shadows/shadowGenerator.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ShadowGenerator", function() { return _shadowGenerator__WEBPACK_IMPORTED_MODULE_0__["ShadowGenerator"]; }); + +/* harmony import */ var _shadowGeneratorSceneComponent__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./shadowGeneratorSceneComponent */ "./Lights/Shadows/shadowGeneratorSceneComponent.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ShadowGeneratorSceneComponent", function() { return _shadowGeneratorSceneComponent__WEBPACK_IMPORTED_MODULE_1__["ShadowGeneratorSceneComponent"]; }); + + + + + +/***/ }), + +/***/ "./Lights/Shadows/shadowGenerator.ts": +/*!*******************************************!*\ + !*** ./Lights/Shadows/shadowGenerator.ts ***! + \*******************************************/ +/*! exports provided: ShadowGenerator */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ShadowGenerator", function() { return ShadowGenerator; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Meshes_buffer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Meshes/buffer */ "./Meshes/buffer.ts"); +/* harmony import */ var _Lights_light__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Lights/light */ "./Lights/light.ts"); +/* harmony import */ var _Materials_material__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Materials/material */ "./Materials/material.ts"); +/* harmony import */ var _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Materials/materialHelper */ "./Materials/materialHelper.ts"); +/* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../Materials/Textures/texture */ "./Materials/Textures/texture.ts"); +/* harmony import */ var _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../Materials/Textures/renderTargetTexture */ "./Materials/Textures/renderTargetTexture.ts"); +/* harmony import */ var _PostProcesses_postProcess__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../PostProcesses/postProcess */ "./PostProcesses/postProcess.ts"); +/* harmony import */ var _PostProcesses_blurPostProcess__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../../PostProcesses/blurPostProcess */ "./PostProcesses/blurPostProcess.ts"); +/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../../Engines/constants */ "./Engines/constants.ts"); +/* harmony import */ var _Shaders_shadowMap_fragment__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../../Shaders/shadowMap.fragment */ "./Shaders/shadowMap.fragment.ts"); +/* harmony import */ var _Shaders_shadowMap_vertex__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../../Shaders/shadowMap.vertex */ "./Shaders/shadowMap.vertex.ts"); +/* harmony import */ var _Shaders_depthBoxBlur_fragment__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../../Shaders/depthBoxBlur.fragment */ "./Shaders/depthBoxBlur.fragment.ts"); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _Misc_devTools__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../../Misc/devTools */ "./Misc/devTools.ts"); + + + + + + + + + + + + + + + + +/** + * Default implementation IShadowGenerator. + * This is the main object responsible of generating shadows in the framework. + * Documentation: https://doc.babylonjs.com/babylon101/shadows + */ +var ShadowGenerator = /** @class */ (function () { + /** + * Creates a ShadowGenerator object. + * A ShadowGenerator is the required tool to use the shadows. + * Each light casting shadows needs to use its own ShadowGenerator. + * Documentation : https://doc.babylonjs.com/babylon101/shadows + * @param mapSize The size of the texture what stores the shadows. Example : 1024. + * @param light The light object generating the shadows. + * @param usefulFloatFirst By default the generator will try to use half float textures but if you need precision (for self shadowing for instance), you can use this option to enforce full float texture. + */ + function ShadowGenerator(mapSize, light, usefulFloatFirst) { + /** + * Observable triggered before the shadow is rendered. Can be used to update internal effect state + */ + this.onBeforeShadowMapRenderObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_14__["Observable"](); + /** + * Observable triggered after the shadow is rendered. Can be used to restore internal effect state + */ + this.onAfterShadowMapRenderObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_14__["Observable"](); + /** + * Observable triggered before a mesh is rendered in the shadow map. + * Can be used to update internal effect state (that you can get from the onBeforeShadowMapRenderObservable) + */ + this.onBeforeShadowMapRenderMeshObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_14__["Observable"](); + /** + * Observable triggered after a mesh is rendered in the shadow map. + * Can be used to update internal effect state (that you can get from the onAfterShadowMapRenderObservable) + */ + this.onAfterShadowMapRenderMeshObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_14__["Observable"](); + this._bias = 0.00005; + this._normalBias = 0; + this._blurBoxOffset = 1; + this._blurScale = 2; + this._blurKernel = 1; + this._useKernelBlur = false; + this._filter = ShadowGenerator.FILTER_NONE; + this._filteringQuality = ShadowGenerator.QUALITY_HIGH; + this._contactHardeningLightSizeUVRatio = 0.1; + this._darkness = 0; + this._transparencyShadow = false; + /** + * Controls the extent to which the shadows fade out at the edge of the frustum + * Used only by directionals and spots + */ + this.frustumEdgeFalloff = 0; + /** + * If true the shadow map is generated by rendering the back face of the mesh instead of the front face. + * This can help with self-shadowing as the geometry making up the back of objects is slightly offset. + * It might on the other hand introduce peter panning. + */ + this.forceBackFacesOnly = false; + this._lightDirection = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); + this._viewMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Zero(); + this._projectionMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Zero(); + this._transformMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Zero(); + this._cachedPosition = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"](Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); + this._cachedDirection = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"](Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); + this._currentFaceIndex = 0; + this._currentFaceIndexCache = 0; + this._defaultTextureMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Identity(); + this._mapSize = mapSize; + this._light = light; + this._scene = light.getScene(); + light._shadowGenerator = this; + ShadowGenerator._SceneComponentInitialization(this._scene); + // Texture type fallback from float to int if not supported. + var caps = this._scene.getEngine().getCaps(); + if (!usefulFloatFirst) { + if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) { + this._textureType = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].TEXTURETYPE_HALF_FLOAT; + } + else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) { + this._textureType = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].TEXTURETYPE_FLOAT; + } + else { + this._textureType = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].TEXTURETYPE_UNSIGNED_INT; + } + } + else { + if (caps.textureFloatRender && caps.textureFloatLinearFiltering) { + this._textureType = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].TEXTURETYPE_FLOAT; + } + else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) { + this._textureType = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].TEXTURETYPE_HALF_FLOAT; + } + else { + this._textureType = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].TEXTURETYPE_UNSIGNED_INT; + } + } + this._initializeGenerator(); + this._applyFilterValues(); + } + Object.defineProperty(ShadowGenerator.prototype, "bias", { + /** + * Gets the bias: offset applied on the depth preventing acnea (in light direction). + */ + get: function () { + return this._bias; + }, + /** + * Sets the bias: offset applied on the depth preventing acnea (in light direction). + */ + set: function (bias) { + this._bias = bias; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ShadowGenerator.prototype, "normalBias", { + /** + * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle). + */ + get: function () { + return this._normalBias; + }, + /** + * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle). + */ + set: function (normalBias) { + this._normalBias = normalBias; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", { + /** + * Gets the blur box offset: offset applied during the blur pass. + * Only useful if useKernelBlur = false + */ + get: function () { + return this._blurBoxOffset; + }, + /** + * Sets the blur box offset: offset applied during the blur pass. + * Only useful if useKernelBlur = false + */ + set: function (value) { + if (this._blurBoxOffset === value) { + return; + } + this._blurBoxOffset = value; + this._disposeBlurPostProcesses(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ShadowGenerator.prototype, "blurScale", { + /** + * Gets the blur scale: scale of the blurred texture compared to the main shadow map. + * 2 means half of the size. + */ + get: function () { + return this._blurScale; + }, + /** + * Sets the blur scale: scale of the blurred texture compared to the main shadow map. + * 2 means half of the size. + */ + set: function (value) { + if (this._blurScale === value) { + return; + } + this._blurScale = value; + this._disposeBlurPostProcesses(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ShadowGenerator.prototype, "blurKernel", { + /** + * Gets the blur kernel: kernel size of the blur pass. + * Only useful if useKernelBlur = true + */ + get: function () { + return this._blurKernel; + }, + /** + * Sets the blur kernel: kernel size of the blur pass. + * Only useful if useKernelBlur = true + */ + set: function (value) { + if (this._blurKernel === value) { + return; + } + this._blurKernel = value; + this._disposeBlurPostProcesses(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", { + /** + * Gets whether the blur pass is a kernel blur (if true) or box blur. + * Only useful in filtered mode (useBlurExponentialShadowMap...) + */ + get: function () { + return this._useKernelBlur; + }, + /** + * Sets whether the blur pass is a kernel blur (if true) or box blur. + * Only useful in filtered mode (useBlurExponentialShadowMap...) + */ + set: function (value) { + if (this._useKernelBlur === value) { + return; + } + this._useKernelBlur = value; + this._disposeBlurPostProcesses(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ShadowGenerator.prototype, "depthScale", { + /** + * Gets the depth scale used in ESM mode. + */ + get: function () { + return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale(); + }, + /** + * Sets the depth scale used in ESM mode. + * This can override the scale stored on the light. + */ + set: function (value) { + this._depthScale = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ShadowGenerator.prototype, "filter", { + /** + * Gets the current mode of the shadow generator (normal, PCF, ESM...). + * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE + */ + get: function () { + return this._filter; + }, + /** + * Sets the current mode of the shadow generator (normal, PCF, ESM...). + * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE + */ + set: function (value) { + // Blurring the cubemap is going to be too expensive. Reverting to unblurred version + if (this._light.needCube()) { + if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) { + this.useExponentialShadowMap = true; + return; + } + else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) { + this.useCloseExponentialShadowMap = true; + return; + } + // PCF on cubemap would also be expensive + else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) { + this.usePoissonSampling = true; + return; + } + } + // Weblg1 fallback for PCF. + if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) { + if (this._scene.getEngine().webGLVersion === 1) { + this.usePoissonSampling = true; + return; + } + } + if (this._filter === value) { + return; + } + this._filter = value; + this._disposeBlurPostProcesses(); + this._applyFilterValues(); + this._light._markMeshesAsLightDirty(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", { + /** + * Gets if the current filter is set to Poisson Sampling. + */ + get: function () { + return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING; + }, + /** + * Sets the current filter to Poisson Sampling. + */ + set: function (value) { + if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) { + return; + } + this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", { + /** + * Gets if the current filter is set to ESM. + */ + get: function () { + return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP; + }, + /** + * Sets the current filter is to ESM. + */ + set: function (value) { + if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) { + return; + } + this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", { + /** + * Gets if the current filter is set to filtered ESM. + */ + get: function () { + return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP; + }, + /** + * Gets if the current filter is set to filtered ESM. + */ + set: function (value) { + if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) { + return; + } + this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", { + /** + * Gets if the current filter is set to "close ESM" (using the inverse of the + * exponential to prevent steep falloff artifacts). + */ + get: function () { + return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP; + }, + /** + * Sets the current filter to "close ESM" (using the inverse of the + * exponential to prevent steep falloff artifacts). + */ + set: function (value) { + if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) { + return; + } + this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", { + /** + * Gets if the current filter is set to filtered "close ESM" (using the inverse of the + * exponential to prevent steep falloff artifacts). + */ + get: function () { + return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP; + }, + /** + * Sets the current filter to filtered "close ESM" (using the inverse of the + * exponential to prevent steep falloff artifacts). + */ + set: function (value) { + if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) { + return; + } + this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", { + /** + * Gets if the current filter is set to "PCF" (percentage closer filtering). + */ + get: function () { + return this.filter === ShadowGenerator.FILTER_PCF; + }, + /** + * Sets the current filter to "PCF" (percentage closer filtering). + */ + set: function (value) { + if (!value && this.filter !== ShadowGenerator.FILTER_PCF) { + return; + } + this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", { + /** + * Gets the PCF or PCSS Quality. + * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true. + */ + get: function () { + return this._filteringQuality; + }, + /** + * Sets the PCF or PCSS Quality. + * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true. + */ + set: function (filteringQuality) { + if (this._filteringQuality === filteringQuality) { + return; + } + this._filteringQuality = filteringQuality; + this._disposeBlurPostProcesses(); + this._applyFilterValues(); + this._light._markMeshesAsLightDirty(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", { + /** + * Gets if the current filter is set to "PCSS" (contact hardening). + */ + get: function () { + return this.filter === ShadowGenerator.FILTER_PCSS; + }, + /** + * Sets the current filter to "PCSS" (contact hardening). + */ + set: function (value) { + if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) { + return; + } + this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", { + /** + * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size. + * Using a ratio helps keeping shape stability independently of the map size. + * + * It does not account for the light projection as it was having too much + * instability during the light setup or during light position changes. + * + * Only valid if useContactHardeningShadow is true. + */ + get: function () { + return this._contactHardeningLightSizeUVRatio; + }, + /** + * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size. + * Using a ratio helps keeping shape stability independently of the map size. + * + * It does not account for the light projection as it was having too much + * instability during the light setup or during light position changes. + * + * Only valid if useContactHardeningShadow is true. + */ + set: function (contactHardeningLightSizeUVRatio) { + this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ShadowGenerator.prototype, "darkness", { + /** Gets or sets the actual darkness of a shadow */ + get: function () { + return this._darkness; + }, + set: function (value) { + this.setDarkness(value); + }, + enumerable: true, + configurable: true + }); + /** + * Returns the darkness value (float). This can only decrease the actual darkness of a shadow. + * 0 means strongest and 1 would means no shadow. + * @returns the darkness. + */ + ShadowGenerator.prototype.getDarkness = function () { + return this._darkness; + }; + /** + * Sets the darkness value (float). This can only decrease the actual darkness of a shadow. + * @param darkness The darkness value 0 means strongest and 1 would means no shadow. + * @returns the shadow generator allowing fluent coding. + */ + ShadowGenerator.prototype.setDarkness = function (darkness) { + if (darkness >= 1.0) { + this._darkness = 1.0; + } + else if (darkness <= 0.0) { + this._darkness = 0.0; + } + else { + this._darkness = darkness; + } + return this; + }; + Object.defineProperty(ShadowGenerator.prototype, "transparencyShadow", { + /** Gets or sets the ability to have transparent shadow */ + get: function () { + return this._transparencyShadow; + }, + set: function (value) { + this.setTransparencyShadow(value); + }, + enumerable: true, + configurable: true + }); + /** + * Sets the ability to have transparent shadow (boolean). + * @param transparent True if transparent else False + * @returns the shadow generator allowing fluent coding + */ + ShadowGenerator.prototype.setTransparencyShadow = function (transparent) { + this._transparencyShadow = transparent; + return this; + }; + /** + * Gets the main RTT containing the shadow map (usually storing depth from the light point of view). + * @returns The render target texture if present otherwise, null + */ + ShadowGenerator.prototype.getShadowMap = function () { + return this._shadowMap; + }; + /** + * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself). + * @returns The render target texture if the shadow map is present otherwise, null + */ + ShadowGenerator.prototype.getShadowMapForRendering = function () { + if (this._shadowMap2) { + return this._shadowMap2; + } + return this._shadowMap; + }; + /** + * Gets the class name of that object + * @returns "ShadowGenerator" + */ + ShadowGenerator.prototype.getClassName = function () { + return "ShadowGenerator"; + }; + /** + * Helper function to add a mesh and its descendants to the list of shadow casters. + * @param mesh Mesh to add + * @param includeDescendants boolean indicating if the descendants should be added. Default to true + * @returns the Shadow Generator itself + */ + ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) { + var _a; + if (includeDescendants === void 0) { includeDescendants = true; } + if (!this._shadowMap) { + return this; + } + if (!this._shadowMap.renderList) { + this._shadowMap.renderList = []; + } + this._shadowMap.renderList.push(mesh); + if (includeDescendants) { + (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes()); + } + return this; + }; + /** + * Helper function to remove a mesh and its descendants from the list of shadow casters + * @param mesh Mesh to remove + * @param includeDescendants boolean indicating if the descendants should be removed. Default to true + * @returns the Shadow Generator itself + */ + ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) { + if (includeDescendants === void 0) { includeDescendants = true; } + if (!this._shadowMap || !this._shadowMap.renderList) { + return this; + } + var index = this._shadowMap.renderList.indexOf(mesh); + if (index !== -1) { + this._shadowMap.renderList.splice(index, 1); + } + if (includeDescendants) { + for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) { + var child = _a[_i]; + this.removeShadowCaster(child); + } + } + return this; + }; + /** + * Returns the associated light object. + * @returns the light generating the shadow + */ + ShadowGenerator.prototype.getLight = function () { + return this._light; + }; + ShadowGenerator.prototype._initializeGenerator = function () { + this._light._markMeshesAsLightDirty(); + this._initializeShadowMap(); + }; + ShadowGenerator.prototype._initializeShadowMap = function () { + var _this = this; + // Render target + var engine = this._scene.getEngine(); + if (engine.webGLVersion > 1) { + this._shadowMap = new _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_7__["RenderTargetTexture"](this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false); + this._shadowMap.createDepthStencilTexture(_Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].LESS, true); + } + else { + this._shadowMap = new _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_7__["RenderTargetTexture"](this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube()); + } + this._shadowMap.wrapU = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__["Texture"].CLAMP_ADDRESSMODE; + this._shadowMap.wrapV = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__["Texture"].CLAMP_ADDRESSMODE; + this._shadowMap.anisotropicFilteringLevel = 1; + this._shadowMap.updateSamplingMode(_Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__["Texture"].BILINEAR_SAMPLINGMODE); + this._shadowMap.renderParticles = false; + this._shadowMap.ignoreCameraViewport = true; + // Record Face Index before render. + this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) { + _this._currentFaceIndex = faceIndex; + if (_this._filter === ShadowGenerator.FILTER_PCF) { + engine.setColorWrite(false); + } + }); + // Custom render function. + this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this); + // Blur if required afer render. + this._shadowMap.onAfterUnbindObservable.add(function () { + if (_this._filter === ShadowGenerator.FILTER_PCF) { + engine.setColorWrite(true); + } + if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) { + return; + } + var shadowMap = _this.getShadowMapForRendering(); + if (shadowMap) { + _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true); + } + }); + // Clear according to the chosen filter. + var clearZero = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Color4"](0, 0, 0, 0); + var clearOne = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Color4"](1.0, 1.0, 1.0, 1.0); + this._shadowMap.onClearObservable.add(function (engine) { + if (_this._filter === ShadowGenerator.FILTER_PCF) { + engine.clear(clearOne, false, true, false); + } + else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) { + engine.clear(clearZero, true, true, false); + } + else { + engine.clear(clearOne, true, true, false); + } + }); + }; + ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () { + var _this = this; + var engine = this._scene.getEngine(); + var targetSize = this._mapSize / this.blurScale; + if (!this.useKernelBlur || this.blurScale !== 1.0) { + this._shadowMap2 = new _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_7__["RenderTargetTexture"](this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType); + this._shadowMap2.wrapU = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__["Texture"].CLAMP_ADDRESSMODE; + this._shadowMap2.wrapV = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__["Texture"].CLAMP_ADDRESSMODE; + this._shadowMap2.updateSamplingMode(_Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__["Texture"].BILINEAR_SAMPLINGMODE); + } + if (this.useKernelBlur) { + this._kernelBlurXPostprocess = new _PostProcesses_blurPostProcess__WEBPACK_IMPORTED_MODULE_9__["BlurPostProcess"](this._light.name + "KernelBlurX", new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector2"](1, 0), this.blurKernel, 1.0, null, _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__["Texture"].BILINEAR_SAMPLINGMODE, engine, false, this._textureType); + this._kernelBlurXPostprocess.width = targetSize; + this._kernelBlurXPostprocess.height = targetSize; + this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) { + effect.setTexture("textureSampler", _this._shadowMap); + }); + this._kernelBlurYPostprocess = new _PostProcesses_blurPostProcess__WEBPACK_IMPORTED_MODULE_9__["BlurPostProcess"](this._light.name + "KernelBlurY", new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector2"](0, 1), this.blurKernel, 1.0, null, _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__["Texture"].BILINEAR_SAMPLINGMODE, engine, false, this._textureType); + this._kernelBlurXPostprocess.autoClear = false; + this._kernelBlurYPostprocess.autoClear = false; + if (this._textureType === _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].TEXTURETYPE_UNSIGNED_INT) { + this._kernelBlurXPostprocess.packedFloat = true; + this._kernelBlurYPostprocess.packedFloat = true; + } + this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess]; + } + else { + this._boxBlurPostprocess = new _PostProcesses_postProcess__WEBPACK_IMPORTED_MODULE_8__["PostProcess"](this._light.name + "DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0, null, _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__["Texture"].BILINEAR_SAMPLINGMODE, engine, false, "#define OFFSET " + this._blurBoxOffset, this._textureType); + this._boxBlurPostprocess.onApplyObservable.add(function (effect) { + effect.setFloat2("screenSize", targetSize, targetSize); + effect.setTexture("textureSampler", _this._shadowMap); + }); + this._boxBlurPostprocess.autoClear = false; + this._blurPostProcesses = [this._boxBlurPostprocess]; + } + }; + ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) { + var index; + var engine = this._scene.getEngine(); + if (depthOnlySubMeshes.length) { + engine.setColorWrite(false); + for (index = 0; index < depthOnlySubMeshes.length; index++) { + this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]); + } + engine.setColorWrite(true); + } + for (index = 0; index < opaqueSubMeshes.length; index++) { + this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]); + } + for (index = 0; index < alphaTestSubMeshes.length; index++) { + this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]); + } + if (this._transparencyShadow) { + for (index = 0; index < transparentSubMeshes.length; index++) { + this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]); + } + } + }; + ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) { + var _this = this; + var mesh = subMesh.getRenderingMesh(); + var scene = this._scene; + var engine = scene.getEngine(); + var material = subMesh.getMaterial(); + mesh._internalAbstractMeshDataInfo._isActiveIntermediate = false; + if (!material || subMesh.verticesCount === 0) { + return; + } + // Culling + engine.setState(material.backFaceCulling); + // Managing instances + var batch = mesh._getInstancesRenderList(subMesh._id); + if (batch.mustReturn) { + return; + } + var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined); + if (this.isReady(subMesh, hardwareInstancedRendering)) { + engine.enableEffect(this._effect); + mesh._bind(subMesh, this._effect, _Materials_material__WEBPACK_IMPORTED_MODULE_4__["Material"].TriangleFillMode); + this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale); + this._effect.setMatrix("viewProjection", this.getTransformMatrix()); + if (this.getLight().getTypeID() === _Lights_light__WEBPACK_IMPORTED_MODULE_3__["Light"].LIGHTTYPEID_DIRECTIONALLIGHT) { + this._effect.setVector3("lightData", this._cachedDirection); + } + else { + this._effect.setVector3("lightData", this._cachedPosition); + } + if (scene.activeCamera) { + this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera)); + } + // Alpha test + if (material && material.needAlphaTesting()) { + var alphaTexture = material.getAlphaTestTexture(); + if (alphaTexture) { + this._effect.setTexture("diffuseSampler", alphaTexture); + this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix); + } + } + // Bones + if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) { + var skeleton = mesh.skeleton; + if (skeleton.isUsingTextureForMatrices) { + var boneTexture = skeleton.getTransformMatrixTexture(); + if (!boneTexture) { + return; + } + this._effect.setTexture("boneSampler", boneTexture); + this._effect.setFloat("boneTextureWidth", 4.0 * (skeleton.bones.length + 1)); + } + else { + this._effect.setMatrices("mBones", skeleton.getTransformMatrices((mesh))); + } + } + // Morph targets + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_5__["MaterialHelper"].BindMorphTargetParameters(mesh, this._effect); + if (this.forceBackFacesOnly) { + engine.setState(true, 0, false, true); + } + // Observables + this.onBeforeShadowMapRenderMeshObservable.notifyObservers(mesh); + this.onBeforeShadowMapRenderObservable.notifyObservers(this._effect); + // Draw + mesh._processRendering(subMesh, this._effect, _Materials_material__WEBPACK_IMPORTED_MODULE_4__["Material"].TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); }); + if (this.forceBackFacesOnly) { + engine.setState(true, 0, false, false); + } + // Observables + this.onAfterShadowMapRenderObservable.notifyObservers(this._effect); + this.onAfterShadowMapRenderMeshObservable.notifyObservers(mesh); + } + else { + // Need to reset refresh rate of the shadowMap + if (this._shadowMap) { + this._shadowMap.resetRefreshCounter(); + } + } + }; + ShadowGenerator.prototype._applyFilterValues = function () { + if (!this._shadowMap) { + return; + } + if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) { + this._shadowMap.updateSamplingMode(_Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__["Texture"].NEAREST_SAMPLINGMODE); + } + else { + this._shadowMap.updateSamplingMode(_Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__["Texture"].BILINEAR_SAMPLINGMODE); + } + }; + /** + * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects. + * @param onCompiled Callback triggered at the and of the effects compilation + * @param options Sets of optional options forcing the compilation with different modes + */ + ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) { + var _this = this; + var localOptions = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({ useInstances: false }, options); + var shadowMap = this.getShadowMap(); + if (!shadowMap) { + if (onCompiled) { + onCompiled(this); + } + return; + } + var renderList = shadowMap.renderList; + if (!renderList) { + if (onCompiled) { + onCompiled(this); + } + return; + } + var subMeshes = new Array(); + for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) { + var mesh = renderList_1[_i]; + subMeshes.push.apply(subMeshes, mesh.subMeshes); + } + if (subMeshes.length === 0) { + if (onCompiled) { + onCompiled(this); + } + return; + } + var currentIndex = 0; + var checkReady = function () { + if (!_this._scene || !_this._scene.getEngine()) { + return; + } + while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) { + currentIndex++; + if (currentIndex >= subMeshes.length) { + if (onCompiled) { + onCompiled(_this); + } + return; + } + } + setTimeout(checkReady, 16); + }; + checkReady(); + }; + /** + * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects. + * @param options Sets of optional options forcing the compilation with different modes + * @returns A promise that resolves when the compilation completes + */ + ShadowGenerator.prototype.forceCompilationAsync = function (options) { + var _this = this; + return new Promise(function (resolve) { + _this.forceCompilation(function () { + resolve(); + }, options); + }); + }; + /** + * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready). + * @param subMesh The submesh we want to render in the shadow map + * @param useInstances Defines wether will draw in the map using instances + * @returns true if ready otherwise, false + */ + ShadowGenerator.prototype.isReady = function (subMesh, useInstances) { + var defines = []; + if (this._textureType !== _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].TEXTURETYPE_UNSIGNED_INT) { + defines.push("#define FLOAT"); + } + if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) { + defines.push("#define ESM"); + } + else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) { + defines.push("#define DEPTHTEXTURE"); + } + var attribs = [_Meshes_buffer__WEBPACK_IMPORTED_MODULE_2__["VertexBuffer"].PositionKind]; + var mesh = subMesh.getMesh(); + var material = subMesh.getMaterial(); + // Normal bias. + if (this.normalBias && mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_2__["VertexBuffer"].NormalKind)) { + attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_2__["VertexBuffer"].NormalKind); + defines.push("#define NORMAL"); + if (mesh.nonUniformScaling) { + defines.push("#define NONUNIFORMSCALING"); + } + if (this.getLight().getTypeID() === _Lights_light__WEBPACK_IMPORTED_MODULE_3__["Light"].LIGHTTYPEID_DIRECTIONALLIGHT) { + defines.push("#define DIRECTIONINLIGHTDATA"); + } + } + // Alpha test + if (material && material.needAlphaTesting()) { + var alphaTexture = material.getAlphaTestTexture(); + if (alphaTexture) { + defines.push("#define ALPHATEST"); + if (mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_2__["VertexBuffer"].UVKind)) { + attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_2__["VertexBuffer"].UVKind); + defines.push("#define UV1"); + } + if (mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_2__["VertexBuffer"].UV2Kind)) { + if (alphaTexture.coordinatesIndex === 1) { + attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_2__["VertexBuffer"].UV2Kind); + defines.push("#define UV2"); + } + } + } + } + // Bones + if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) { + attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_2__["VertexBuffer"].MatricesIndicesKind); + attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_2__["VertexBuffer"].MatricesWeightsKind); + if (mesh.numBoneInfluencers > 4) { + attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_2__["VertexBuffer"].MatricesIndicesExtraKind); + attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_2__["VertexBuffer"].MatricesWeightsExtraKind); + } + var skeleton = mesh.skeleton; + defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers); + if (skeleton.isUsingTextureForMatrices) { + defines.push("#define BONETEXTURE"); + } + else { + defines.push("#define BonesPerMesh " + (skeleton.bones.length + 1)); + } + } + else { + defines.push("#define NUM_BONE_INFLUENCERS 0"); + } + // Morph targets + var manager = mesh.morphTargetManager; + var morphInfluencers = 0; + if (manager) { + if (manager.numInfluencers > 0) { + defines.push("#define MORPHTARGETS"); + morphInfluencers = manager.numInfluencers; + defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers); + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_5__["MaterialHelper"].PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers }); + } + } + // Instances + if (useInstances) { + defines.push("#define INSTANCES"); + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_5__["MaterialHelper"].PushAttributesForInstances(attribs); + } + if (this.customShaderOptions) { + if (this.customShaderOptions.defines) { + for (var _i = 0, _a = this.customShaderOptions.defines; _i < _a.length; _i++) { + var define = _a[_i]; + if (defines.indexOf(define) === -1) { + defines.push(define); + } + } + } + } + // Get correct effect + var join = defines.join("\n"); + if (this._cachedDefines !== join) { + this._cachedDefines = join; + var shaderName = "shadowMap"; + var uniforms = ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences", "boneTextureWidth"]; + var samplers = ["diffuseSampler", "boneSampler"]; + // Custom shader? + if (this.customShaderOptions) { + shaderName = this.customShaderOptions.shaderName; + if (this.customShaderOptions.attributes) { + for (var _b = 0, _c = this.customShaderOptions.attributes; _b < _c.length; _b++) { + var attrib = _c[_b]; + if (attribs.indexOf(attrib) === -1) { + attribs.push(attrib); + } + } + } + if (this.customShaderOptions.uniforms) { + for (var _d = 0, _e = this.customShaderOptions.uniforms; _d < _e.length; _d++) { + var uniform = _e[_d]; + if (uniforms.indexOf(uniform) === -1) { + uniforms.push(uniform); + } + } + } + if (this.customShaderOptions.samplers) { + for (var _f = 0, _g = this.customShaderOptions.samplers; _f < _g.length; _f++) { + var sampler = _g[_f]; + if (samplers.indexOf(sampler) === -1) { + samplers.push(sampler); + } + } + } + } + this._effect = this._scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers }); + } + if (!this._effect.isReady()) { + return false; + } + if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) { + if (!this._blurPostProcesses || !this._blurPostProcesses.length) { + this._initializeBlurRTTAndPostProcesses(); + } + } + if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) { + return false; + } + if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) { + return false; + } + if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) { + return false; + } + return true; + }; + /** + * Prepare all the defines in a material relying on a shadow map at the specified light index. + * @param defines Defines of the material we want to update + * @param lightIndex Index of the light in the enabled light list of the material + */ + ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) { + var scene = this._scene; + var light = this._light; + if (!scene.shadowsEnabled || !light.shadowEnabled) { + return; + } + defines["SHADOW" + lightIndex] = true; + if (this.useContactHardeningShadow) { + defines["SHADOWPCSS" + lightIndex] = true; + if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) { + defines["SHADOWLOWQUALITY" + lightIndex] = true; + } + else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) { + defines["SHADOWMEDIUMQUALITY" + lightIndex] = true; + } + // else default to high. + } + if (this.usePercentageCloserFiltering) { + defines["SHADOWPCF" + lightIndex] = true; + if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) { + defines["SHADOWLOWQUALITY" + lightIndex] = true; + } + else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) { + defines["SHADOWMEDIUMQUALITY" + lightIndex] = true; + } + // else default to high. + } + else if (this.usePoissonSampling) { + defines["SHADOWPOISSON" + lightIndex] = true; + } + else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) { + defines["SHADOWESM" + lightIndex] = true; + } + else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) { + defines["SHADOWCLOSEESM" + lightIndex] = true; + } + if (light.needCube()) { + defines["SHADOWCUBE" + lightIndex] = true; + } + }; + /** + * Binds the shadow related information inside of an effect (information like near, far, darkness... + * defined in the generator but impacting the effect). + * @param lightIndex Index of the light in the enabled light list of the material owning the effect + * @param effect The effect we are binfing the information for + */ + ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) { + var light = this._light; + var scene = this._scene; + if (!scene.shadowsEnabled || !light.shadowEnabled) { + return; + } + var camera = scene.activeCamera; + if (!camera) { + return; + } + var shadowMap = this.getShadowMap(); + if (!shadowMap) { + return; + } + if (!light.needCube()) { + effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix()); + } + // Only PCF uses depth stencil texture. + if (this._filter === ShadowGenerator.FILTER_PCF) { + effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering()); + light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex); + } + else if (this._filter === ShadowGenerator.FILTER_PCSS) { + effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering()); + effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering()); + light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex); + } + else { + effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering()); + light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex); + } + light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex); + }; + /** + * Gets the transformation matrix used to project the meshes into the map from the light point of view. + * (eq to shadow prjection matrix * light transform matrix) + * @returns The transform matrix used to create the shadow map + */ + ShadowGenerator.prototype.getTransformMatrix = function () { + var scene = this._scene; + if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) { + return this._transformMatrix; + } + this._currentRenderID = scene.getRenderId(); + this._currentFaceIndexCache = this._currentFaceIndex; + var lightPosition = this._light.position; + if (this._light.computeTransformedInformation()) { + lightPosition = this._light.transformedPosition; + } + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection); + if (Math.abs(_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Dot(this._lightDirection, _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Up())) === 1.0) { + this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light + } + if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) { + this._cachedPosition.copyFrom(lightPosition); + this._cachedDirection.copyFrom(this._lightDirection); + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Up(), this._viewMatrix); + var shadowMap = this.getShadowMap(); + if (shadowMap) { + var renderList = shadowMap.renderList; + if (renderList) { + this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList); + } + } + this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix); + } + return this._transformMatrix; + }; + /** + * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between + * Cube and 2D textures for instance. + */ + ShadowGenerator.prototype.recreateShadowMap = function () { + var shadowMap = this._shadowMap; + if (!shadowMap) { + return; + } + // Track render list. + var renderList = shadowMap.renderList; + // Clean up existing data. + this._disposeRTTandPostProcesses(); + // Reinitializes. + this._initializeGenerator(); + // Reaffect the filter to ensure a correct fallback if necessary. + this.filter = this.filter; + // Reaffect the filter. + this._applyFilterValues(); + // Reaffect Render List. + this._shadowMap.renderList = renderList; + }; + ShadowGenerator.prototype._disposeBlurPostProcesses = function () { + if (this._shadowMap2) { + this._shadowMap2.dispose(); + this._shadowMap2 = null; + } + if (this._boxBlurPostprocess) { + this._boxBlurPostprocess.dispose(); + this._boxBlurPostprocess = null; + } + if (this._kernelBlurXPostprocess) { + this._kernelBlurXPostprocess.dispose(); + this._kernelBlurXPostprocess = null; + } + if (this._kernelBlurYPostprocess) { + this._kernelBlurYPostprocess.dispose(); + this._kernelBlurYPostprocess = null; + } + this._blurPostProcesses = []; + }; + ShadowGenerator.prototype._disposeRTTandPostProcesses = function () { + if (this._shadowMap) { + this._shadowMap.dispose(); + this._shadowMap = null; + } + this._disposeBlurPostProcesses(); + }; + /** + * Disposes the ShadowGenerator. + * Returns nothing. + */ + ShadowGenerator.prototype.dispose = function () { + this._disposeRTTandPostProcesses(); + if (this._light) { + this._light._shadowGenerator = null; + this._light._markMeshesAsLightDirty(); + } + this.onBeforeShadowMapRenderMeshObservable.clear(); + this.onBeforeShadowMapRenderObservable.clear(); + this.onAfterShadowMapRenderMeshObservable.clear(); + this.onAfterShadowMapRenderObservable.clear(); + }; + /** + * Serializes the shadow generator setup to a json object. + * @returns The serialized JSON object + */ + ShadowGenerator.prototype.serialize = function () { + var serializationObject = {}; + var shadowMap = this.getShadowMap(); + if (!shadowMap) { + return serializationObject; + } + serializationObject.lightId = this._light.id; + serializationObject.mapSize = shadowMap.getRenderSize(); + serializationObject.useExponentialShadowMap = this.useExponentialShadowMap; + serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap; + serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap; + serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap; + serializationObject.usePoissonSampling = this.usePoissonSampling; + serializationObject.forceBackFacesOnly = this.forceBackFacesOnly; + serializationObject.depthScale = this.depthScale; + serializationObject.darkness = this.getDarkness(); + serializationObject.blurBoxOffset = this.blurBoxOffset; + serializationObject.blurKernel = this.blurKernel; + serializationObject.blurScale = this.blurScale; + serializationObject.useKernelBlur = this.useKernelBlur; + serializationObject.transparencyShadow = this._transparencyShadow; + serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff; + serializationObject.bias = this.bias; + serializationObject.normalBias = this.normalBias; + serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering; + serializationObject.useContactHardeningShadow = this.useContactHardeningShadow; + serializationObject.filteringQuality = this.filteringQuality; + serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio; + serializationObject.renderList = []; + if (shadowMap.renderList) { + for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) { + var mesh = shadowMap.renderList[meshIndex]; + serializationObject.renderList.push(mesh.id); + } + } + return serializationObject; + }; + /** + * Parses a serialized ShadowGenerator and returns a new ShadowGenerator. + * @param parsedShadowGenerator The JSON object to parse + * @param scene The scene to create the shadow map for + * @returns The parsed shadow generator + */ + ShadowGenerator.Parse = function (parsedShadowGenerator, scene) { + var light = scene.getLightByID(parsedShadowGenerator.lightId); + var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light); + var shadowMap = shadowGenerator.getShadowMap(); + for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) { + var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]); + meshes.forEach(function (mesh) { + if (!shadowMap) { + return; + } + if (!shadowMap.renderList) { + shadowMap.renderList = []; + } + shadowMap.renderList.push(mesh); + }); + } + if (parsedShadowGenerator.usePoissonSampling) { + shadowGenerator.usePoissonSampling = true; + } + else if (parsedShadowGenerator.useExponentialShadowMap) { + shadowGenerator.useExponentialShadowMap = true; + } + else if (parsedShadowGenerator.useBlurExponentialShadowMap) { + shadowGenerator.useBlurExponentialShadowMap = true; + } + else if (parsedShadowGenerator.useCloseExponentialShadowMap) { + shadowGenerator.useCloseExponentialShadowMap = true; + } + else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) { + shadowGenerator.useBlurCloseExponentialShadowMap = true; + } + else if (parsedShadowGenerator.usePercentageCloserFiltering) { + shadowGenerator.usePercentageCloserFiltering = true; + } + else if (parsedShadowGenerator.useContactHardeningShadow) { + shadowGenerator.useContactHardeningShadow = true; + } + if (parsedShadowGenerator.filteringQuality) { + shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality; + } + if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) { + shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio; + } + // Backward compat + else if (parsedShadowGenerator.useVarianceShadowMap) { + shadowGenerator.useExponentialShadowMap = true; + } + else if (parsedShadowGenerator.useBlurVarianceShadowMap) { + shadowGenerator.useBlurExponentialShadowMap = true; + } + if (parsedShadowGenerator.depthScale) { + shadowGenerator.depthScale = parsedShadowGenerator.depthScale; + } + if (parsedShadowGenerator.blurScale) { + shadowGenerator.blurScale = parsedShadowGenerator.blurScale; + } + if (parsedShadowGenerator.blurBoxOffset) { + shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset; + } + if (parsedShadowGenerator.useKernelBlur) { + shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur; + } + if (parsedShadowGenerator.blurKernel) { + shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel; + } + if (parsedShadowGenerator.bias !== undefined) { + shadowGenerator.bias = parsedShadowGenerator.bias; + } + if (parsedShadowGenerator.normalBias !== undefined) { + shadowGenerator.normalBias = parsedShadowGenerator.normalBias; + } + if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) { + shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff; + } + if (parsedShadowGenerator.darkness) { + shadowGenerator.setDarkness(parsedShadowGenerator.darkness); + } + if (parsedShadowGenerator.transparencyShadow) { + shadowGenerator.setTransparencyShadow(true); + } + shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly; + return shadowGenerator; + }; + /** + * Shadow generator mode None: no filtering applied. + */ + ShadowGenerator.FILTER_NONE = 0; + /** + * Shadow generator mode ESM: Exponential Shadow Mapping. + * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf) + */ + ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1; + /** + * Shadow generator mode Poisson Sampling: Percentage Closer Filtering. + * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength) + */ + ShadowGenerator.FILTER_POISSONSAMPLING = 2; + /** + * Shadow generator mode ESM: Blurred Exponential Shadow Mapping. + * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf) + */ + ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3; + /** + * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing + * edge artifacts on steep falloff. + * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf) + */ + ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4; + /** + * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing + * edge artifacts on steep falloff. + * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf) + */ + ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5; + /** + * Shadow generator mode PCF: Percentage Closer Filtering + * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1 + * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html) + */ + ShadowGenerator.FILTER_PCF = 6; + /** + * Shadow generator mode PCSS: Percentage Closering Soft Shadow. + * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1 + * Contact Hardening + */ + ShadowGenerator.FILTER_PCSS = 7; + /** + * Reserved for PCF and PCSS + * Highest Quality. + * + * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts. + * + * Execute PCSS with 32 taps blocker search and 64 taps PCF. + */ + ShadowGenerator.QUALITY_HIGH = 0; + /** + * Reserved for PCF and PCSS + * Good tradeoff for quality/perf cross devices + * + * Execute PCF on a 3*3 kernel. + * + * Execute PCSS with 16 taps blocker search and 32 taps PCF. + */ + ShadowGenerator.QUALITY_MEDIUM = 1; + /** + * Reserved for PCF and PCSS + * The lowest quality but the fastest. + * + * Execute PCF on a 1*1 kernel. + * + * Execute PCSS with 16 taps blocker search and 16 taps PCF. + */ + ShadowGenerator.QUALITY_LOW = 2; + /** @hidden */ + ShadowGenerator._SceneComponentInitialization = function (_) { + throw _Misc_devTools__WEBPACK_IMPORTED_MODULE_15__["_DevTools"].WarnImport("ShadowGeneratorSceneComponent"); + }; + return ShadowGenerator; +}()); + + + +/***/ }), + +/***/ "./Lights/Shadows/shadowGeneratorSceneComponent.ts": +/*!*********************************************************!*\ + !*** ./Lights/Shadows/shadowGeneratorSceneComponent.ts ***! + \*********************************************************/ +/*! exports provided: ShadowGeneratorSceneComponent */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ShadowGeneratorSceneComponent", function() { return ShadowGeneratorSceneComponent; }); +/* harmony import */ var _shadowGenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./shadowGenerator */ "./Lights/Shadows/shadowGenerator.ts"); +/* harmony import */ var _sceneComponent__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../sceneComponent */ "./sceneComponent.ts"); +/* harmony import */ var _abstractScene__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../abstractScene */ "./abstractScene.ts"); + + + +// Adds the parser to the scene parsers. +_abstractScene__WEBPACK_IMPORTED_MODULE_2__["AbstractScene"].AddParser(_sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].NAME_SHADOWGENERATOR, function (parsedData, scene) { + // Shadows + if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) { + for (var index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) { + var parsedShadowGenerator = parsedData.shadowGenerators[index]; + _shadowGenerator__WEBPACK_IMPORTED_MODULE_0__["ShadowGenerator"].Parse(parsedShadowGenerator, scene); + // SG would be available on their associated lights + } + } +}); +/** + * Defines the shadow generator component responsible to manage any shadow generators + * in a given scene. + */ +var ShadowGeneratorSceneComponent = /** @class */ (function () { + /** + * Creates a new instance of the component for the given scene + * @param scene Defines the scene to register the component in + */ + function ShadowGeneratorSceneComponent(scene) { + /** + * The component name helpfull to identify the component in the list of scene components. + */ + this.name = _sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].NAME_SHADOWGENERATOR; + this.scene = scene; + } + /** + * Registers the component in a given scene + */ + ShadowGeneratorSceneComponent.prototype.register = function () { + this.scene._gatherRenderTargetsStage.registerStep(_sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets); + }; + /** + * Rebuilds the elements related to this component in case of + * context lost for instance. + */ + ShadowGeneratorSceneComponent.prototype.rebuild = function () { + // Nothing To Do Here. + }; + /** + * Serializes the component data to the specified json object + * @param serializationObject The object to serialize to + */ + ShadowGeneratorSceneComponent.prototype.serialize = function (serializationObject) { + // Shadows + serializationObject.shadowGenerators = []; + var lights = this.scene.lights; + for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) { + var light = lights_1[_i]; + var shadowGenerator = light.getShadowGenerator(); + if (shadowGenerator) { + serializationObject.shadowGenerators.push(shadowGenerator.serialize()); + } + } + }; + /** + * Adds all the elements from the container to the scene + * @param container the container holding the elements + */ + ShadowGeneratorSceneComponent.prototype.addFromContainer = function (container) { + // Nothing To Do Here. (directly attached to a light) + }; + /** + * Removes all the elements in the container from the scene + * @param container contains the elements to remove + * @param dispose if the removed element should be disposed (default: false) + */ + ShadowGeneratorSceneComponent.prototype.removeFromContainer = function (container, dispose) { + // Nothing To Do Here. (directly attached to a light) + }; + /** + * Rebuilds the elements related to this component in case of + * context lost for instance. + */ + ShadowGeneratorSceneComponent.prototype.dispose = function () { + // Nothing To Do Here. + }; + ShadowGeneratorSceneComponent.prototype._gatherRenderTargets = function (renderTargets) { + // Shadows + var scene = this.scene; + if (this.scene.shadowsEnabled) { + for (var lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) { + var light = scene.lights[lightIndex]; + var shadowGenerator = light.getShadowGenerator(); + if (light.isEnabled() && light.shadowEnabled && shadowGenerator) { + var shadowMap = (shadowGenerator.getShadowMap()); + if (scene.textures.indexOf(shadowMap) !== -1) { + renderTargets.push(shadowMap); + } + } + } + } + }; + return ShadowGeneratorSceneComponent; +}()); + +_shadowGenerator__WEBPACK_IMPORTED_MODULE_0__["ShadowGenerator"]._SceneComponentInitialization = function (scene) { + var component = scene._getComponent(_sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].NAME_SHADOWGENERATOR); + if (!component) { + component = new ShadowGeneratorSceneComponent(scene); + scene._addComponent(component); + } +}; + + +/***/ }), + +/***/ "./Lights/directionalLight.ts": +/*!************************************!*\ + !*** ./Lights/directionalLight.ts ***! + \************************************/ +/*! exports provided: DirectionalLight */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DirectionalLight", function() { return DirectionalLight; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../node */ "./node.ts"); +/* harmony import */ var _light__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./light */ "./Lights/light.ts"); +/* harmony import */ var _shadowLight__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./shadowLight */ "./Lights/shadowLight.ts"); + + + + + + +_node__WEBPACK_IMPORTED_MODULE_3__["Node"].AddNodeConstructor("Light_Type_1", function (name, scene) { + return function () { return new DirectionalLight(name, _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(), scene); }; +}); +/** + * A directional light is defined by a direction (what a surprise!). + * The light is emitted from everywhere in the specified direction, and has an infinite range. + * An example of a directional light is when a distance planet is lit by the apparently parallel lines of light from its sun. Light in a downward direction will light the top of an object. + * Documentation: https://doc.babylonjs.com/babylon101/lights + */ +var DirectionalLight = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](DirectionalLight, _super); + /** + * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3). + * The directional light is emitted from everywhere in the given direction. + * It can cast shadows. + * Documentation : https://doc.babylonjs.com/babylon101/lights + * @param name The friendly name of the light + * @param direction The direction of the light + * @param scene The scene the light belongs to + */ + function DirectionalLight(name, direction, scene) { + var _this = _super.call(this, name, scene) || this; + _this._shadowFrustumSize = 0; + _this._shadowOrthoScale = 0.1; + /** + * Automatically compute the projection matrix to best fit (including all the casters) + * on each frame. + */ + _this.autoUpdateExtends = true; + // Cache + _this._orthoLeft = Number.MAX_VALUE; + _this._orthoRight = Number.MIN_VALUE; + _this._orthoTop = Number.MIN_VALUE; + _this._orthoBottom = Number.MAX_VALUE; + _this.position = direction.scale(-1.0); + _this.direction = direction; + return _this; + } + Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", { + /** + * Fix frustum size for the shadow generation. This is disabled if the value is 0. + */ + get: function () { + return this._shadowFrustumSize; + }, + /** + * Specifies a fix frustum size for the shadow generation. + */ + set: function (value) { + this._shadowFrustumSize = value; + this.forceProjectionMatrixCompute(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", { + /** + * Gets the shadow projection scale against the optimal computed one. + * 0.1 by default which means that the projection window is increase by 10% from the optimal size. + * This does not impact in fixed frustum size (shadowFrustumSize being set) + */ + get: function () { + return this._shadowOrthoScale; + }, + /** + * Sets the shadow projection scale against the optimal computed one. + * 0.1 by default which means that the projection window is increase by 10% from the optimal size. + * This does not impact in fixed frustum size (shadowFrustumSize being set) + */ + set: function (value) { + this._shadowOrthoScale = value; + this.forceProjectionMatrixCompute(); + }, + enumerable: true, + configurable: true + }); + /** + * Returns the string "DirectionalLight". + * @return The class name + */ + DirectionalLight.prototype.getClassName = function () { + return "DirectionalLight"; + }; + /** + * Returns the integer 1. + * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x + */ + DirectionalLight.prototype.getTypeID = function () { + return _light__WEBPACK_IMPORTED_MODULE_4__["Light"].LIGHTTYPEID_DIRECTIONALLIGHT; + }; + /** + * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix. + * Returns the DirectionalLight Shadow projection matrix. + */ + DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) { + if (this.shadowFrustumSize > 0) { + this._setDefaultFixedFrustumShadowProjectionMatrix(matrix); + } + else { + this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList); + } + }; + /** + * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix. + * Returns the DirectionalLight Shadow projection matrix. + */ + DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix) { + var activeCamera = this.getScene().activeCamera; + if (!activeCamera) { + return; + } + _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"].OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix); + }; + /** + * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix. + * Returns the DirectionalLight Shadow projection matrix. + */ + DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) { + var activeCamera = this.getScene().activeCamera; + if (!activeCamera) { + return; + } + // Check extends + if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) { + var tempVector3 = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); + this._orthoLeft = Number.MAX_VALUE; + this._orthoRight = Number.MIN_VALUE; + this._orthoTop = Number.MIN_VALUE; + this._orthoBottom = Number.MAX_VALUE; + for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) { + var mesh = renderList[meshIndex]; + if (!mesh) { + continue; + } + var boundingInfo = mesh.getBoundingInfo(); + var boundingBox = boundingInfo.boundingBox; + for (var index = 0; index < boundingBox.vectorsWorld.length; index++) { + _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3); + if (tempVector3.x < this._orthoLeft) { + this._orthoLeft = tempVector3.x; + } + if (tempVector3.y < this._orthoBottom) { + this._orthoBottom = tempVector3.y; + } + if (tempVector3.x > this._orthoRight) { + this._orthoRight = tempVector3.x; + } + if (tempVector3.y > this._orthoTop) { + this._orthoTop = tempVector3.y; + } + } + } + } + var xOffset = this._orthoRight - this._orthoLeft; + var yOffset = this._orthoTop - this._orthoBottom; + _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"].OrthoOffCenterLHToRef(this._orthoLeft - xOffset * this.shadowOrthoScale, this._orthoRight + xOffset * this.shadowOrthoScale, this._orthoBottom - yOffset * this.shadowOrthoScale, this._orthoTop + yOffset * this.shadowOrthoScale, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix); + }; + DirectionalLight.prototype._buildUniformLayout = function () { + this._uniformBuffer.addUniform("vLightData", 4); + this._uniformBuffer.addUniform("vLightDiffuse", 4); + this._uniformBuffer.addUniform("vLightSpecular", 3); + this._uniformBuffer.addUniform("shadowsInfo", 3); + this._uniformBuffer.addUniform("depthValues", 2); + this._uniformBuffer.create(); + }; + /** + * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name. + * @param effect The effect to update + * @param lightIndex The index of the light in the effect to update + * @returns The directional light + */ + DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) { + if (this.computeTransformedInformation()) { + this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex); + return this; + } + this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex); + return this; + }; + /** + * Gets the minZ used for shadow according to both the scene and the light. + * + * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being + * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5. + * @param activeCamera The camera we are returning the min for + * @returns the depth min z + */ + DirectionalLight.prototype.getDepthMinZ = function (activeCamera) { + return 1; + }; + /** + * Gets the maxZ used for shadow according to both the scene and the light. + * + * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being + * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5. + * @param activeCamera The camera we are returning the max for + * @returns the depth max z + */ + DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) { + return 1; + }; + /** + * Prepares the list of defines specific to the light type. + * @param defines the list of defines + * @param lightIndex defines the index of the light for the effect + */ + DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) { + defines["DIRLIGHT" + lightIndex] = true; + }; + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], DirectionalLight.prototype, "shadowFrustumSize", null); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], DirectionalLight.prototype, "shadowOrthoScale", null); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], DirectionalLight.prototype, "autoUpdateExtends", void 0); + return DirectionalLight; +}(_shadowLight__WEBPACK_IMPORTED_MODULE_5__["ShadowLight"])); + + + +/***/ }), + +/***/ "./Lights/hemisphericLight.ts": +/*!************************************!*\ + !*** ./Lights/hemisphericLight.ts ***! + \************************************/ +/*! exports provided: HemisphericLight */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HemisphericLight", function() { return HemisphericLight; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../node */ "./node.ts"); +/* harmony import */ var _light__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./light */ "./Lights/light.ts"); + + + + + +_node__WEBPACK_IMPORTED_MODULE_3__["Node"].AddNodeConstructor("Light_Type_3", function (name, scene) { + return function () { return new HemisphericLight(name, _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(), scene); }; +}); +/** + * The HemisphericLight simulates the ambient environment light, + * so the passed direction is the light reflection direction, not the incoming direction. + */ +var HemisphericLight = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](HemisphericLight, _super); + /** + * Creates a HemisphericLight object in the scene according to the passed direction (Vector3). + * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction. + * The HemisphericLight can't cast shadows. + * Documentation : https://doc.babylonjs.com/babylon101/lights + * @param name The friendly name of the light + * @param direction The direction of the light reflection + * @param scene The scene the light belongs to + */ + function HemisphericLight(name, direction, scene) { + var _this = _super.call(this, name, scene) || this; + /** + * The groundColor is the light in the opposite direction to the one specified during creation. + * You can think of the diffuse and specular light as coming from the centre of the object in the given direction and the groundColor light in the opposite direction. + */ + _this.groundColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color3"](0.0, 0.0, 0.0); + _this.direction = direction || _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Up(); + return _this; + } + HemisphericLight.prototype._buildUniformLayout = function () { + this._uniformBuffer.addUniform("vLightData", 4); + this._uniformBuffer.addUniform("vLightDiffuse", 4); + this._uniformBuffer.addUniform("vLightSpecular", 3); + this._uniformBuffer.addUniform("vLightGround", 3); + this._uniformBuffer.addUniform("shadowsInfo", 3); + this._uniformBuffer.addUniform("depthValues", 2); + this._uniformBuffer.create(); + }; + /** + * Returns the string "HemisphericLight". + * @return The class name + */ + HemisphericLight.prototype.getClassName = function () { + return "HemisphericLight"; + }; + /** + * Sets the HemisphericLight direction towards the passed target (Vector3). + * Returns the updated direction. + * @param target The target the direction should point to + * @return The computed direction + */ + HemisphericLight.prototype.setDirectionToTarget = function (target) { + this.direction = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Normalize(target.subtract(_Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero())); + return this.direction; + }; + /** + * Returns the shadow generator associated to the light. + * @returns Always null for hemispheric lights because it does not support shadows. + */ + HemisphericLight.prototype.getShadowGenerator = function () { + return null; + }; + /** + * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string). + * @param effect The effect to update + * @param lightIndex The index of the light in the effect to update + * @returns The hemispheric light + */ + HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) { + var normalizeDirection = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Normalize(this.direction); + this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex); + this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex); + return this; + }; + /** + * Computes the world matrix of the node + * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch + * @param useWasUpdatedFlag defines a reserved property + * @returns the world matrix + */ + HemisphericLight.prototype.computeWorldMatrix = function () { + if (!this._worldMatrix) { + this._worldMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"].Identity(); + } + return this._worldMatrix; + }; + /** + * Returns the integer 3. + * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x + */ + HemisphericLight.prototype.getTypeID = function () { + return _light__WEBPACK_IMPORTED_MODULE_4__["Light"].LIGHTTYPEID_HEMISPHERICLIGHT; + }; + /** + * Prepares the list of defines specific to the light type. + * @param defines the list of defines + * @param lightIndex defines the index of the light for the effect + */ + HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) { + defines["HEMILIGHT" + lightIndex] = true; + }; + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])() + ], HemisphericLight.prototype, "groundColor", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsVector3"])() + ], HemisphericLight.prototype, "direction", void 0); + return HemisphericLight; +}(_light__WEBPACK_IMPORTED_MODULE_4__["Light"])); + + + +/***/ }), + +/***/ "./Lights/index.ts": +/*!*************************!*\ + !*** ./Lights/index.ts ***! + \*************************/ +/*! exports provided: Light, ShadowLight, DirectionalLight, HemisphericLight, PointLight, SpotLight, ShadowGenerator, ShadowGeneratorSceneComponent */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _light__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./light */ "./Lights/light.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Light", function() { return _light__WEBPACK_IMPORTED_MODULE_0__["Light"]; }); + +/* harmony import */ var _shadowLight__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./shadowLight */ "./Lights/shadowLight.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ShadowLight", function() { return _shadowLight__WEBPACK_IMPORTED_MODULE_1__["ShadowLight"]; }); + +/* harmony import */ var _Shadows_index__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Shadows/index */ "./Lights/Shadows/index.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ShadowGenerator", function() { return _Shadows_index__WEBPACK_IMPORTED_MODULE_2__["ShadowGenerator"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ShadowGeneratorSceneComponent", function() { return _Shadows_index__WEBPACK_IMPORTED_MODULE_2__["ShadowGeneratorSceneComponent"]; }); + +/* harmony import */ var _directionalLight__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./directionalLight */ "./Lights/directionalLight.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DirectionalLight", function() { return _directionalLight__WEBPACK_IMPORTED_MODULE_3__["DirectionalLight"]; }); + +/* harmony import */ var _hemisphericLight__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./hemisphericLight */ "./Lights/hemisphericLight.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HemisphericLight", function() { return _hemisphericLight__WEBPACK_IMPORTED_MODULE_4__["HemisphericLight"]; }); + +/* harmony import */ var _pointLight__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./pointLight */ "./Lights/pointLight.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointLight", function() { return _pointLight__WEBPACK_IMPORTED_MODULE_5__["PointLight"]; }); + +/* harmony import */ var _spotLight__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./spotLight */ "./Lights/spotLight.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SpotLight", function() { return _spotLight__WEBPACK_IMPORTED_MODULE_6__["SpotLight"]; }); + + + + + + + + + + +/***/ }), + +/***/ "./Lights/light.ts": +/*!*************************!*\ + !*** ./Lights/light.ts ***! + \*************************/ +/*! exports provided: Light */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Light", function() { return Light; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../node */ "./node.ts"); +/* harmony import */ var _Materials_uniformBuffer__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Materials/uniformBuffer */ "./Materials/uniformBuffer.ts"); +/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Misc/typeStore */ "./Misc/typeStore.ts"); + + + + + + +/** + * Base class of all the lights in Babylon. It groups all the generic information about lights. + * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour. + * All meshes allow light to pass through them unless shadow generation is activated. The default number of lights allowed is four but this can be increased. + */ +var Light = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Light, _super); + /** + * Creates a Light object in the scene. + * Documentation : https://doc.babylonjs.com/babylon101/lights + * @param name The firendly name of the light + * @param scene The scene the light belongs too + */ + function Light(name, scene) { + var _this = _super.call(this, name, scene) || this; + /** + * Diffuse gives the basic color to an object. + */ + _this.diffuse = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color3"](1.0, 1.0, 1.0); + /** + * Specular produces a highlight color on an object. + * Note: This is note affecting PBR materials. + */ + _this.specular = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color3"](1.0, 1.0, 1.0); + /** + * Defines the falloff type for this light. This lets overrriding how punctual light are + * falling off base on range or angle. + * This can be set to any values in Light.FALLOFF_x. + * + * Note: This is only useful for PBR Materials at the moment. This could be extended if required to + * other types of materials. + */ + _this.falloffType = Light.FALLOFF_DEFAULT; + /** + * Strength of the light. + * Note: By default it is define in the framework own unit. + * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in. + */ + _this.intensity = 1.0; + _this._range = Number.MAX_VALUE; + _this._inverseSquaredRange = 0; + /** + * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type + * of light. + */ + _this._photometricScale = 1.0; + _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC; + _this._radius = 0.00001; + /** + * Defines the rendering priority of the lights. It can help in case of fallback or number of lights + * exceeding the number allowed of the materials. + */ + _this.renderPriority = 0; + _this._shadowEnabled = true; + _this._excludeWithLayerMask = 0; + _this._includeOnlyWithLayerMask = 0; + _this._lightmapMode = 0; + /** + * @hidden Internal use only. + */ + _this._excludedMeshesIds = new Array(); + /** + * @hidden Internal use only. + */ + _this._includedOnlyMeshesIds = new Array(); + /** @hidden */ + _this._isLight = true; + _this.getScene().addLight(_this); + _this._uniformBuffer = new _Materials_uniformBuffer__WEBPACK_IMPORTED_MODULE_4__["UniformBuffer"](_this.getScene().getEngine()); + _this._buildUniformLayout(); + _this.includedOnlyMeshes = new Array(); + _this.excludedMeshes = new Array(); + _this._resyncMeshes(); + return _this; + } + Object.defineProperty(Light.prototype, "range", { + /** + * Defines how far from the source the light is impacting in scene units. + * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff. + */ + get: function () { + return this._range; + }, + /** + * Defines how far from the source the light is impacting in scene units. + * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff. + */ + set: function (value) { + this._range = value; + this._inverseSquaredRange = 1.0 / (this.range * this.range); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Light.prototype, "intensityMode", { + /** + * Gets the photometric scale used to interpret the intensity. + * This is only relevant with PBR Materials where the light intensity can be defined in a physical way. + */ + get: function () { + return this._intensityMode; + }, + /** + * Sets the photometric scale used to interpret the intensity. + * This is only relevant with PBR Materials where the light intensity can be defined in a physical way. + */ + set: function (value) { + this._intensityMode = value; + this._computePhotometricScale(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Light.prototype, "radius", { + /** + * Gets the light radius used by PBR Materials to simulate soft area lights. + */ + get: function () { + return this._radius; + }, + /** + * sets the light radius used by PBR Materials to simulate soft area lights. + */ + set: function (value) { + this._radius = value; + this._computePhotometricScale(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Light.prototype, "shadowEnabled", { + /** + * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching + * the current shadow generator. + */ + get: function () { + return this._shadowEnabled; + }, + /** + * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching + * the current shadow generator. + */ + set: function (value) { + if (this._shadowEnabled === value) { + return; + } + this._shadowEnabled = value; + this._markMeshesAsLightDirty(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Light.prototype, "includedOnlyMeshes", { + /** + * Gets the only meshes impacted by this light. + */ + get: function () { + return this._includedOnlyMeshes; + }, + /** + * Sets the only meshes impacted by this light. + */ + set: function (value) { + this._includedOnlyMeshes = value; + this._hookArrayForIncludedOnly(value); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Light.prototype, "excludedMeshes", { + /** + * Gets the meshes not impacted by this light. + */ + get: function () { + return this._excludedMeshes; + }, + /** + * Sets the meshes not impacted by this light. + */ + set: function (value) { + this._excludedMeshes = value; + this._hookArrayForExcluded(value); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Light.prototype, "excludeWithLayerMask", { + /** + * Gets the layer id use to find what meshes are not impacted by the light. + * Inactive if 0 + */ + get: function () { + return this._excludeWithLayerMask; + }, + /** + * Sets the layer id use to find what meshes are not impacted by the light. + * Inactive if 0 + */ + set: function (value) { + this._excludeWithLayerMask = value; + this._resyncMeshes(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", { + /** + * Gets the layer id use to find what meshes are impacted by the light. + * Inactive if 0 + */ + get: function () { + return this._includeOnlyWithLayerMask; + }, + /** + * Sets the layer id use to find what meshes are impacted by the light. + * Inactive if 0 + */ + set: function (value) { + this._includeOnlyWithLayerMask = value; + this._resyncMeshes(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Light.prototype, "lightmapMode", { + /** + * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x) + */ + get: function () { + return this._lightmapMode; + }, + /** + * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x) + */ + set: function (value) { + if (this._lightmapMode === value) { + return; + } + this._lightmapMode = value; + this._markMeshesAsLightDirty(); + }, + enumerable: true, + configurable: true + }); + /** + * Returns the string "Light". + * @returns the class name + */ + Light.prototype.getClassName = function () { + return "Light"; + }; + /** + * Converts the light information to a readable string for debug purpose. + * @param fullDetails Supports for multiple levels of logging within scene loading + * @returns the human readable light info + */ + Light.prototype.toString = function (fullDetails) { + var ret = "Name: " + this.name; + ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()]; + if (this.animations) { + for (var i = 0; i < this.animations.length; i++) { + ret += ", animation[0]: " + this.animations[i].toString(fullDetails); + } + } + if (fullDetails) { + } + return ret; + }; + /** @hidden */ + Light.prototype._syncParentEnabledState = function () { + _super.prototype._syncParentEnabledState.call(this); + this._resyncMeshes(); + }; + /** + * Set the enabled state of this node. + * @param value - the new enabled state + */ + Light.prototype.setEnabled = function (value) { + _super.prototype.setEnabled.call(this, value); + this._resyncMeshes(); + }; + /** + * Returns the Light associated shadow generator if any. + * @return the associated shadow generator. + */ + Light.prototype.getShadowGenerator = function () { + return this._shadowGenerator; + }; + /** + * Returns a Vector3, the absolute light position in the World. + * @returns the world space position of the light + */ + Light.prototype.getAbsolutePosition = function () { + return _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); + }; + /** + * Specifies if the light will affect the passed mesh. + * @param mesh The mesh to test against the light + * @return true the mesh is affected otherwise, false. + */ + Light.prototype.canAffectMesh = function (mesh) { + if (!mesh) { + return true; + } + if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) { + return false; + } + if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) { + return false; + } + if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) { + return false; + } + if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) { + return false; + } + return true; + }; + /** + * Sort function to order lights for rendering. + * @param a First Light object to compare to second. + * @param b Second Light object to compare first. + * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b. + */ + Light.CompareLightsPriority = function (a, b) { + //shadow-casting lights have priority over non-shadow-casting lights + //the renderPrioirty is a secondary sort criterion + if (a.shadowEnabled !== b.shadowEnabled) { + return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0); + } + return b.renderPriority - a.renderPriority; + }; + /** + * Releases resources associated with this node. + * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default) + * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default) + */ + Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) { + if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; } + if (this._shadowGenerator) { + this._shadowGenerator.dispose(); + this._shadowGenerator = null; + } + // Animations + this.getScene().stopAnimation(this); + // Remove from meshes + for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) { + var mesh = _a[_i]; + mesh._removeLightSource(this); + } + this._uniformBuffer.dispose(); + // Remove from scene + this.getScene().removeLight(this); + _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures); + }; + /** + * Returns the light type ID (integer). + * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x + */ + Light.prototype.getTypeID = function () { + return 0; + }; + /** + * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode. + * @returns the scaled intensity in intensity mode unit + */ + Light.prototype.getScaledIntensity = function () { + return this._photometricScale * this.intensity; + }; + /** + * Returns a new Light object, named "name", from the current one. + * @param name The name of the cloned light + * @returns the new created light + */ + Light.prototype.clone = function (name) { + var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()); + if (!constructor) { + return null; + } + return _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Clone(constructor, this); + }; + /** + * Serializes the current light into a Serialization object. + * @returns the serialized object. + */ + Light.prototype.serialize = function () { + var serializationObject = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(this); + // Type + serializationObject.type = this.getTypeID(); + // Parent + if (this.parent) { + serializationObject.parentId = this.parent.id; + } + // Inclusion / exclusions + if (this.excludedMeshes.length > 0) { + serializationObject.excludedMeshesIds = []; + this.excludedMeshes.forEach(function (mesh) { + serializationObject.excludedMeshesIds.push(mesh.id); + }); + } + if (this.includedOnlyMeshes.length > 0) { + serializationObject.includedOnlyMeshesIds = []; + this.includedOnlyMeshes.forEach(function (mesh) { + serializationObject.includedOnlyMeshesIds.push(mesh.id); + }); + } + // Animations + _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].AppendSerializedAnimations(this, serializationObject); + serializationObject.ranges = this.serializeAnimationRanges(); + return serializationObject; + }; + /** + * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3. + * This new light is named "name" and added to the passed scene. + * @param type Type according to the types available in Light.LIGHTTYPEID_x + * @param name The friendly name of the light + * @param scene The scene the new light will belong to + * @returns the constructor function + */ + Light.GetConstructorFromName = function (type, name, scene) { + var constructorFunc = _node__WEBPACK_IMPORTED_MODULE_3__["Node"].Construct("Light_Type_" + type, name, scene); + if (constructorFunc) { + return constructorFunc; + } + // Default to no light for none present once. + return null; + }; + /** + * Parses the passed "parsedLight" and returns a new instanced Light from this parsing. + * @param parsedLight The JSON representation of the light + * @param scene The scene to create the parsed light in + * @returns the created light after parsing + */ + Light.Parse = function (parsedLight, scene) { + var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene); + if (!constructor) { + return null; + } + var light = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(constructor, parsedLight, scene); + // Inclusion / exclusions + if (parsedLight.excludedMeshesIds) { + light._excludedMeshesIds = parsedLight.excludedMeshesIds; + } + if (parsedLight.includedOnlyMeshesIds) { + light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds; + } + // Parent + if (parsedLight.parentId) { + light._waitingParentId = parsedLight.parentId; + } + // Falloff + if (parsedLight.falloffType !== undefined) { + light.falloffType = parsedLight.falloffType; + } + // Lightmaps + if (parsedLight.lightmapMode !== undefined) { + light.lightmapMode = parsedLight.lightmapMode; + } + // Animations + if (parsedLight.animations) { + for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) { + var parsedAnimation = parsedLight.animations[animationIndex]; + var internalClass = _Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__["_TypeStore"].GetClass("BABYLON.Animation"); + if (internalClass) { + light.animations.push(internalClass.Parse(parsedAnimation)); + } + } + _node__WEBPACK_IMPORTED_MODULE_3__["Node"].ParseAnimationRanges(light, parsedLight, scene); + } + if (parsedLight.autoAnimate) { + scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0); + } + return light; + }; + Light.prototype._hookArrayForExcluded = function (array) { + var _this = this; + var oldPush = array.push; + array.push = function () { + var items = []; + for (var _i = 0; _i < arguments.length; _i++) { + items[_i] = arguments[_i]; + } + var result = oldPush.apply(array, items); + for (var _a = 0, items_1 = items; _a < items_1.length; _a++) { + var item = items_1[_a]; + item._resyncLighSource(_this); + } + return result; + }; + var oldSplice = array.splice; + array.splice = function (index, deleteCount) { + var deleted = oldSplice.apply(array, [index, deleteCount]); + for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) { + var item = deleted_1[_i]; + item._resyncLighSource(_this); + } + return deleted; + }; + for (var _i = 0, array_1 = array; _i < array_1.length; _i++) { + var item = array_1[_i]; + item._resyncLighSource(this); + } + }; + Light.prototype._hookArrayForIncludedOnly = function (array) { + var _this = this; + var oldPush = array.push; + array.push = function () { + var items = []; + for (var _i = 0; _i < arguments.length; _i++) { + items[_i] = arguments[_i]; + } + var result = oldPush.apply(array, items); + _this._resyncMeshes(); + return result; + }; + var oldSplice = array.splice; + array.splice = function (index, deleteCount) { + var deleted = oldSplice.apply(array, [index, deleteCount]); + _this._resyncMeshes(); + return deleted; + }; + this._resyncMeshes(); + }; + Light.prototype._resyncMeshes = function () { + for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) { + var mesh = _a[_i]; + mesh._resyncLighSource(this); + } + }; + /** + * Forces the meshes to update their light related information in their rendering used effects + * @hidden Internal Use Only + */ + Light.prototype._markMeshesAsLightDirty = function () { + for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) { + var mesh = _a[_i]; + if (mesh.lightSources.indexOf(this) !== -1) { + mesh._markSubMeshesAsLightDirty(); + } + } + }; + /** + * Recomputes the cached photometric scale if needed. + */ + Light.prototype._computePhotometricScale = function () { + this._photometricScale = this._getPhotometricScale(); + this.getScene().resetCachedMaterial(); + }; + /** + * Returns the Photometric Scale according to the light type and intensity mode. + */ + Light.prototype._getPhotometricScale = function () { + var photometricScale = 0.0; + var lightTypeID = this.getTypeID(); + //get photometric mode + var photometricMode = this.intensityMode; + if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) { + if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) { + photometricMode = Light.INTENSITYMODE_ILLUMINANCE; + } + else { + photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY; + } + } + //compute photometric scale + switch (lightTypeID) { + case Light.LIGHTTYPEID_POINTLIGHT: + case Light.LIGHTTYPEID_SPOTLIGHT: + switch (photometricMode) { + case Light.INTENSITYMODE_LUMINOUSPOWER: + photometricScale = 1.0 / (4.0 * Math.PI); + break; + case Light.INTENSITYMODE_LUMINOUSINTENSITY: + photometricScale = 1.0; + break; + case Light.INTENSITYMODE_LUMINANCE: + photometricScale = this.radius * this.radius; + break; + } + break; + case Light.LIGHTTYPEID_DIRECTIONALLIGHT: + switch (photometricMode) { + case Light.INTENSITYMODE_ILLUMINANCE: + photometricScale = 1.0; + break; + case Light.INTENSITYMODE_LUMINANCE: + // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance. + // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres). + var apexAngleRadians = this.radius; + // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function). + apexAngleRadians = Math.max(apexAngleRadians, 0.001); + var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians)); + photometricScale = solidAngle; + break; + } + break; + case Light.LIGHTTYPEID_HEMISPHERICLIGHT: + // No fall off in hemisperic light. + photometricScale = 1.0; + break; + } + return photometricScale; + }; + /** + * Reorder the light in the scene according to their defined priority. + * @hidden Internal Use Only + */ + Light.prototype._reorderLightsInScene = function () { + var scene = this.getScene(); + if (this._renderPriority != 0) { + scene.requireLightSorting = true; + } + this.getScene().sortLightsByPriority(); + }; + /** + * Falloff Default: light is falling off following the material specification: + * standard material is using standard falloff whereas pbr material can request special falloff per materials. + */ + Light.FALLOFF_DEFAULT = 0; + /** + * Falloff Physical: light is falling off following the inverse squared distance law. + */ + Light.FALLOFF_PHYSICAL = 1; + /** + * Falloff gltf: light is falling off as described in the gltf moving to PBR document + * to enhance interoperability with other engines. + */ + Light.FALLOFF_GLTF = 2; + /** + * Falloff Standard: light is falling off like in the standard material + * to enhance interoperability with other materials. + */ + Light.FALLOFF_STANDARD = 3; + //lightmapMode Consts + /** + * If every light affecting the material is in this lightmapMode, + * material.lightmapTexture adds or multiplies + * (depends on material.useLightmapAsShadowmap) + * after every other light calculations. + */ + Light.LIGHTMAP_DEFAULT = 0; + /** + * material.lightmapTexture as only diffuse lighting from this light + * adds only specular lighting from this light + * adds dynamic shadows + */ + Light.LIGHTMAP_SPECULAR = 1; + /** + * material.lightmapTexture as only lighting + * no light calculation from this light + * only adds dynamic shadows from this light + */ + Light.LIGHTMAP_SHADOWSONLY = 2; + // Intensity Mode Consts + /** + * Each light type uses the default quantity according to its type: + * point/spot lights use luminous intensity + * directional lights use illuminance + */ + Light.INTENSITYMODE_AUTOMATIC = 0; + /** + * lumen (lm) + */ + Light.INTENSITYMODE_LUMINOUSPOWER = 1; + /** + * candela (lm/sr) + */ + Light.INTENSITYMODE_LUMINOUSINTENSITY = 2; + /** + * lux (lm/m^2) + */ + Light.INTENSITYMODE_ILLUMINANCE = 3; + /** + * nit (cd/m^2) + */ + Light.INTENSITYMODE_LUMINANCE = 4; + // Light types ids const. + /** + * Light type const id of the point light. + */ + Light.LIGHTTYPEID_POINTLIGHT = 0; + /** + * Light type const id of the directional light. + */ + Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1; + /** + * Light type const id of the spot light. + */ + Light.LIGHTTYPEID_SPOTLIGHT = 2; + /** + * Light type const id of the hemispheric light. + */ + Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3; + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])() + ], Light.prototype, "diffuse", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])() + ], Light.prototype, "specular", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], Light.prototype, "falloffType", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], Light.prototype, "intensity", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], Light.prototype, "range", null); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], Light.prototype, "intensityMode", null); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], Light.prototype, "radius", null); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], Light.prototype, "_renderPriority", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_reorderLightsInScene") + ], Light.prototype, "renderPriority", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])("shadowEnabled") + ], Light.prototype, "_shadowEnabled", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])("excludeWithLayerMask") + ], Light.prototype, "_excludeWithLayerMask", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])("includeOnlyWithLayerMask") + ], Light.prototype, "_includeOnlyWithLayerMask", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])("lightmapMode") + ], Light.prototype, "_lightmapMode", void 0); + return Light; +}(_node__WEBPACK_IMPORTED_MODULE_3__["Node"])); + + + +/***/ }), + +/***/ "./Lights/pointLight.ts": +/*!******************************!*\ + !*** ./Lights/pointLight.ts ***! + \******************************/ +/*! exports provided: PointLight */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PointLight", function() { return PointLight; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../node */ "./node.ts"); +/* harmony import */ var _light__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./light */ "./Lights/light.ts"); +/* harmony import */ var _shadowLight__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./shadowLight */ "./Lights/shadowLight.ts"); + + + + + + +_node__WEBPACK_IMPORTED_MODULE_3__["Node"].AddNodeConstructor("Light_Type_0", function (name, scene) { + return function () { return new PointLight(name, _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(), scene); }; +}); +/** + * A point light is a light defined by an unique point in world space. + * The light is emitted in every direction from this point. + * A good example of a point light is a standard light bulb. + * Documentation: https://doc.babylonjs.com/babylon101/lights + */ +var PointLight = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PointLight, _super); + /** + * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene. + * A PointLight emits the light in every direction. + * It can cast shadows. + * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it : + * ```javascript + * var pointLight = new PointLight("pl", camera.position, scene); + * ``` + * Documentation : https://doc.babylonjs.com/babylon101/lights + * @param name The light friendly name + * @param position The position of the point light in the scene + * @param scene The scene the lights belongs to + */ + function PointLight(name, position, scene) { + var _this = _super.call(this, name, scene) || this; + _this._shadowAngle = Math.PI / 2; + _this.position = position; + return _this; + } + Object.defineProperty(PointLight.prototype, "shadowAngle", { + /** + * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback + * This specifies what angle the shadow will use to be created. + * + * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps. + */ + get: function () { + return this._shadowAngle; + }, + /** + * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback + * This specifies what angle the shadow will use to be created. + * + * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps. + */ + set: function (value) { + this._shadowAngle = value; + this.forceProjectionMatrixCompute(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(PointLight.prototype, "direction", { + /** + * Gets the direction if it has been set. + * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback + */ + get: function () { + return this._direction; + }, + /** + * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback + */ + set: function (value) { + var previousNeedCube = this.needCube(); + this._direction = value; + if (this.needCube() !== previousNeedCube && this._shadowGenerator) { + this._shadowGenerator.recreateShadowMap(); + } + }, + enumerable: true, + configurable: true + }); + /** + * Returns the string "PointLight" + * @returns the class name + */ + PointLight.prototype.getClassName = function () { + return "PointLight"; + }; + /** + * Returns the integer 0. + * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x + */ + PointLight.prototype.getTypeID = function () { + return _light__WEBPACK_IMPORTED_MODULE_4__["Light"].LIGHTTYPEID_POINTLIGHT; + }; + /** + * Specifies wether or not the shadowmap should be a cube texture. + * @returns true if the shadowmap needs to be a cube texture. + */ + PointLight.prototype.needCube = function () { + return !this.direction; + }; + /** + * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer). + * @param faceIndex The index of the face we are computed the direction to generate shadow + * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true + */ + PointLight.prototype.getShadowDirection = function (faceIndex) { + if (this.direction) { + return _super.prototype.getShadowDirection.call(this, faceIndex); + } + else { + switch (faceIndex) { + case 0: + return new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](1.0, 0.0, 0.0); + case 1: + return new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](-1.0, 0.0, 0.0); + case 2: + return new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](0.0, -1.0, 0.0); + case 3: + return new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](0.0, 1.0, 0.0); + case 4: + return new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](0.0, 0.0, 1.0); + case 5: + return new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](0.0, 0.0, -1.0); + } + } + return _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); + }; + /** + * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings : + * - fov = PI / 2 + * - aspect ratio : 1.0 + * - z-near and far equal to the active camera minZ and maxZ. + * Returns the PointLight. + */ + PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) { + var activeCamera = this.getScene().activeCamera; + if (!activeCamera) { + return; + } + _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"].PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix); + }; + PointLight.prototype._buildUniformLayout = function () { + this._uniformBuffer.addUniform("vLightData", 4); + this._uniformBuffer.addUniform("vLightDiffuse", 4); + this._uniformBuffer.addUniform("vLightSpecular", 3); + this._uniformBuffer.addUniform("vLightFalloff", 4); + this._uniformBuffer.addUniform("shadowsInfo", 3); + this._uniformBuffer.addUniform("depthValues", 2); + this._uniformBuffer.create(); + }; + /** + * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string). + * @param effect The effect to update + * @param lightIndex The index of the light in the effect to update + * @returns The point light + */ + PointLight.prototype.transferToEffect = function (effect, lightIndex) { + if (this.computeTransformedInformation()) { + this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex); + } + else { + this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex); + } + this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex); + return this; + }; + /** + * Prepares the list of defines specific to the light type. + * @param defines the list of defines + * @param lightIndex defines the index of the light for the effect + */ + PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) { + defines["POINTLIGHT" + lightIndex] = true; + }; + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], PointLight.prototype, "shadowAngle", null); + return PointLight; +}(_shadowLight__WEBPACK_IMPORTED_MODULE_5__["ShadowLight"])); + + + +/***/ }), + +/***/ "./Lights/shadowLight.ts": +/*!*******************************!*\ + !*** ./Lights/shadowLight.ts ***! + \*******************************/ +/*! exports provided: ShadowLight */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ShadowLight", function() { return ShadowLight; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _light__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./light */ "./Lights/light.ts"); + + + + +/** + * Base implementation IShadowLight + * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern. + */ +var ShadowLight = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ShadowLight, _super); + function ShadowLight() { + var _this = _super !== null && _super.apply(this, arguments) || this; + _this._needProjectionMatrixCompute = true; + return _this; + } + ShadowLight.prototype._setPosition = function (value) { + this._position = value; + }; + Object.defineProperty(ShadowLight.prototype, "position", { + /** + * Sets the position the shadow will be casted from. Also use as the light position for both + * point and spot lights. + */ + get: function () { + return this._position; + }, + /** + * Sets the position the shadow will be casted from. Also use as the light position for both + * point and spot lights. + */ + set: function (value) { + this._setPosition(value); + }, + enumerable: true, + configurable: true + }); + ShadowLight.prototype._setDirection = function (value) { + this._direction = value; + }; + Object.defineProperty(ShadowLight.prototype, "direction", { + /** + * In 2d mode (needCube being false), gets the direction used to cast the shadow. + * Also use as the light direction on spot and directional lights. + */ + get: function () { + return this._direction; + }, + /** + * In 2d mode (needCube being false), sets the direction used to cast the shadow. + * Also use as the light direction on spot and directional lights. + */ + set: function (value) { + this._setDirection(value); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ShadowLight.prototype, "shadowMinZ", { + /** + * Gets the shadow projection clipping minimum z value. + */ + get: function () { + return this._shadowMinZ; + }, + /** + * Sets the shadow projection clipping minimum z value. + */ + set: function (value) { + this._shadowMinZ = value; + this.forceProjectionMatrixCompute(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", { + /** + * Sets the shadow projection clipping maximum z value. + */ + get: function () { + return this._shadowMaxZ; + }, + /** + * Gets the shadow projection clipping maximum z value. + */ + set: function (value) { + this._shadowMaxZ = value; + this.forceProjectionMatrixCompute(); + }, + enumerable: true, + configurable: true + }); + /** + * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light + * @returns true if the information has been computed, false if it does not need to (no parenting) + */ + ShadowLight.prototype.computeTransformedInformation = function () { + if (this.parent && this.parent.getWorldMatrix) { + if (!this.transformedPosition) { + this.transformedPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); + } + _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition); + // In case the direction is present. + if (this.direction) { + if (!this.transformedDirection) { + this.transformedDirection = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); + } + _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection); + } + return true; + } + return false; + }; + /** + * Return the depth scale used for the shadow map. + * @returns the depth scale. + */ + ShadowLight.prototype.getDepthScale = function () { + return 50.0; + }; + /** + * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed. + * @param faceIndex The index of the face we are computed the direction to generate shadow + * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true + */ + ShadowLight.prototype.getShadowDirection = function (faceIndex) { + return this.transformedDirection ? this.transformedDirection : this.direction; + }; + /** + * Returns the ShadowLight absolute position in the World. + * @returns the position vector in world space + */ + ShadowLight.prototype.getAbsolutePosition = function () { + return this.transformedPosition ? this.transformedPosition : this.position; + }; + /** + * Sets the ShadowLight direction toward the passed target. + * @param target The point to target in local space + * @returns the updated ShadowLight direction + */ + ShadowLight.prototype.setDirectionToTarget = function (target) { + this.direction = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Normalize(target.subtract(this.position)); + return this.direction; + }; + /** + * Returns the light rotation in euler definition. + * @returns the x y z rotation in local space. + */ + ShadowLight.prototype.getRotation = function () { + this.direction.normalize(); + var xaxis = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Cross(this.direction, _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Axis"].Y); + var yaxis = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Cross(xaxis, this.direction); + return _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].RotationFromAxis(xaxis, yaxis, this.direction); + }; + /** + * Returns whether or not the shadow generation require a cube texture or a 2d texture. + * @returns true if a cube texture needs to be use + */ + ShadowLight.prototype.needCube = function () { + return false; + }; + /** + * Detects if the projection matrix requires to be recomputed this frame. + * @returns true if it requires to be recomputed otherwise, false. + */ + ShadowLight.prototype.needProjectionMatrixCompute = function () { + return this._needProjectionMatrixCompute; + }; + /** + * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed. + */ + ShadowLight.prototype.forceProjectionMatrixCompute = function () { + this._needProjectionMatrixCompute = true; + }; + /** @hidden */ + ShadowLight.prototype._initCache = function () { + _super.prototype._initCache.call(this); + this._cache.position = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); + }; + /** @hidden */ + ShadowLight.prototype._isSynchronized = function () { + if (!this._cache.position.equals(this.position)) { + return false; + } + return true; + }; + /** + * Computes the world matrix of the node + * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch + * @returns the world matrix + */ + ShadowLight.prototype.computeWorldMatrix = function (force) { + if (!force && this.isSynchronized()) { + this._currentRenderId = this.getScene().getRenderId(); + return this._worldMatrix; + } + this._updateCache(); + this._cache.position.copyFrom(this.position); + if (!this._worldMatrix) { + this._worldMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"].Identity(); + } + _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"].TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix); + if (this.parent && this.parent.getWorldMatrix) { + this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix); + this._markSyncedWithParent(); + } + // Cache the determinant + this._worldMatrixDeterminantIsDirty = true; + return this._worldMatrix; + }; + /** + * Gets the minZ used for shadow according to both the scene and the light. + * @param activeCamera The camera we are returning the min for + * @returns the depth min z + */ + ShadowLight.prototype.getDepthMinZ = function (activeCamera) { + return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ; + }; + /** + * Gets the maxZ used for shadow according to both the scene and the light. + * @param activeCamera The camera we are returning the max for + * @returns the depth max z + */ + ShadowLight.prototype.getDepthMaxZ = function (activeCamera) { + return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ; + }; + /** + * Sets the shadow projection matrix in parameter to the generated projection matrix. + * @param matrix The materix to updated with the projection information + * @param viewMatrix The transform matrix of the light + * @param renderList The list of mesh to render in the map + * @returns The current light + */ + ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) { + if (this.customProjectionMatrixBuilder) { + this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix); + } + else { + this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList); + } + return this; + }; + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsVector3"])() + ], ShadowLight.prototype, "position", null); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsVector3"])() + ], ShadowLight.prototype, "direction", null); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ShadowLight.prototype, "shadowMinZ", null); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ShadowLight.prototype, "shadowMaxZ", null); + return ShadowLight; +}(_light__WEBPACK_IMPORTED_MODULE_3__["Light"])); + + + +/***/ }), + +/***/ "./Lights/spotLight.ts": +/*!*****************************!*\ + !*** ./Lights/spotLight.ts ***! + \*****************************/ +/*! exports provided: SpotLight */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SpotLight", function() { return SpotLight; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../node */ "./node.ts"); +/* harmony import */ var _light__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./light */ "./Lights/light.ts"); +/* harmony import */ var _shadowLight__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./shadowLight */ "./Lights/shadowLight.ts"); + + + + + + +_node__WEBPACK_IMPORTED_MODULE_3__["Node"].AddNodeConstructor("Light_Type_2", function (name, scene) { + return function () { return new SpotLight(name, _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(), _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(), 0, 0, scene); }; +}); +/** + * A spot light is defined by a position, a direction, an angle, and an exponent. + * These values define a cone of light starting from the position, emitting toward the direction. + * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam, + * and the exponent defines the speed of the decay of the light with distance (reach). + * Documentation: https://doc.babylonjs.com/babylon101/lights + */ +var SpotLight = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SpotLight, _super); + /** + * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone. + * It can cast shadows. + * Documentation : https://doc.babylonjs.com/babylon101/lights + * @param name The light friendly name + * @param position The position of the spot light in the scene + * @param direction The direction of the light in the scene + * @param angle The cone angle of the light in Radians + * @param exponent The light decay speed with the distance from the emission spot + * @param scene The scene the lights belongs to + */ + function SpotLight(name, position, direction, angle, exponent, scene) { + var _this = _super.call(this, name, scene) || this; + _this._innerAngle = 0; + _this._projectionTextureMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"].Zero(); + _this._projectionTextureLightNear = 1e-6; + _this._projectionTextureLightFar = 1000.0; + _this._projectionTextureUpDirection = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Up(); + _this._projectionTextureViewLightDirty = true; + _this._projectionTextureProjectionLightDirty = true; + _this._projectionTextureDirty = true; + _this._projectionTextureViewTargetVector = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); + _this._projectionTextureViewLightMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"].Zero(); + _this._projectionTextureProjectionLightMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"].Zero(); + _this._projectionTextureScalingMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"].FromValues(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0); + _this.position = position; + _this.direction = direction; + _this.angle = angle; + _this.exponent = exponent; + return _this; + } + Object.defineProperty(SpotLight.prototype, "angle", { + /** + * Gets the cone angle of the spot light in Radians. + */ + get: function () { + return this._angle; + }, + /** + * Sets the cone angle of the spot light in Radians. + */ + set: function (value) { + this._angle = value; + this._cosHalfAngle = Math.cos(value * 0.5); + this._projectionTextureProjectionLightDirty = true; + this.forceProjectionMatrixCompute(); + this._computeAngleValues(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SpotLight.prototype, "innerAngle", { + /** + * Only used in gltf falloff mode, this defines the angle where + * the directional falloff will start before cutting at angle which could be seen + * as outer angle. + */ + get: function () { + return this._innerAngle; + }, + /** + * Only used in gltf falloff mode, this defines the angle where + * the directional falloff will start before cutting at angle which could be seen + * as outer angle. + */ + set: function (value) { + this._innerAngle = value; + this._computeAngleValues(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SpotLight.prototype, "shadowAngleScale", { + /** + * Allows scaling the angle of the light for shadow generation only. + */ + get: function () { + return this._shadowAngleScale; + }, + /** + * Allows scaling the angle of the light for shadow generation only. + */ + set: function (value) { + this._shadowAngleScale = value; + this.forceProjectionMatrixCompute(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", { + /** + * Allows reading the projecton texture + */ + get: function () { + return this._projectionTextureMatrix; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", { + /** + * Gets the near clip of the Spotlight for texture projection. + */ + get: function () { + return this._projectionTextureLightNear; + }, + /** + * Sets the near clip of the Spotlight for texture projection. + */ + set: function (value) { + this._projectionTextureLightNear = value; + this._projectionTextureProjectionLightDirty = true; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", { + /** + * Gets the far clip of the Spotlight for texture projection. + */ + get: function () { + return this._projectionTextureLightFar; + }, + /** + * Sets the far clip of the Spotlight for texture projection. + */ + set: function (value) { + this._projectionTextureLightFar = value; + this._projectionTextureProjectionLightDirty = true; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", { + /** + * Gets the Up vector of the Spotlight for texture projection. + */ + get: function () { + return this._projectionTextureUpDirection; + }, + /** + * Sets the Up vector of the Spotlight for texture projection. + */ + set: function (value) { + this._projectionTextureUpDirection = value; + this._projectionTextureProjectionLightDirty = true; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SpotLight.prototype, "projectionTexture", { + /** + * Gets the projection texture of the light. + */ + get: function () { + return this._projectionTexture; + }, + /** + * Sets the projection texture of the light. + */ + set: function (value) { + var _this = this; + if (this._projectionTexture === value) { + return; + } + this._projectionTexture = value; + this._projectionTextureDirty = true; + if (this._projectionTexture && !this._projectionTexture.isReady()) { + var texture = this._projectionTexture; + if (texture.onLoadObservable) { + texture.onLoadObservable.addOnce(function () { + _this._markMeshesAsLightDirty(); + }); + } + } + }, + enumerable: true, + configurable: true + }); + /** + * Returns the string "SpotLight". + * @returns the class name + */ + SpotLight.prototype.getClassName = function () { + return "SpotLight"; + }; + /** + * Returns the integer 2. + * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x + */ + SpotLight.prototype.getTypeID = function () { + return _light__WEBPACK_IMPORTED_MODULE_4__["Light"].LIGHTTYPEID_SPOTLIGHT; + }; + /** + * Overrides the direction setter to recompute the projection texture view light Matrix. + */ + SpotLight.prototype._setDirection = function (value) { + _super.prototype._setDirection.call(this, value); + this._projectionTextureViewLightDirty = true; + }; + /** + * Overrides the position setter to recompute the projection texture view light Matrix. + */ + SpotLight.prototype._setPosition = function (value) { + _super.prototype._setPosition.call(this, value); + this._projectionTextureViewLightDirty = true; + }; + /** + * Sets the passed matrix "matrix" as perspective projection matrix for the shadows and the passed view matrix with the fov equal to the SpotLight angle and and aspect ratio of 1.0. + * Returns the SpotLight. + */ + SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) { + var activeCamera = this.getScene().activeCamera; + if (!activeCamera) { + return; + } + this._shadowAngleScale = this._shadowAngleScale || 1; + var angle = this._shadowAngleScale * this._angle; + _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"].PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix); + }; + SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () { + this._projectionTextureViewLightDirty = false; + this._projectionTextureDirty = true; + this.position.addToRef(this.direction, this._projectionTextureViewTargetVector); + _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"].LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix); + }; + SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () { + this._projectionTextureProjectionLightDirty = false; + this._projectionTextureDirty = true; + var light_far = this.projectionTextureLightFar; + var light_near = this.projectionTextureLightNear; + var P = light_far / (light_far - light_near); + var Q = -P * light_near; + var S = 1.0 / Math.tan(this._angle / 2.0); + var A = 1.0; + _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"].FromValuesToRef(S / A, 0.0, 0.0, 0.0, 0.0, S, 0.0, 0.0, 0.0, 0.0, P, 1.0, 0.0, 0.0, Q, 0.0, this._projectionTextureProjectionLightMatrix); + }; + /** + * Main function for light texture projection matrix computing. + */ + SpotLight.prototype._computeProjectionTextureMatrix = function () { + this._projectionTextureDirty = false; + this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix); + this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix); + }; + SpotLight.prototype._buildUniformLayout = function () { + this._uniformBuffer.addUniform("vLightData", 4); + this._uniformBuffer.addUniform("vLightDiffuse", 4); + this._uniformBuffer.addUniform("vLightSpecular", 3); + this._uniformBuffer.addUniform("vLightDirection", 3); + this._uniformBuffer.addUniform("vLightFalloff", 4); + this._uniformBuffer.addUniform("shadowsInfo", 3); + this._uniformBuffer.addUniform("depthValues", 2); + this._uniformBuffer.create(); + }; + SpotLight.prototype._computeAngleValues = function () { + this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle)); + this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale; + }; + /** + * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction. + * @param effect The effect to update + * @param lightIndex The index of the light in the effect to update + * @returns The spot light + */ + SpotLight.prototype.transferToEffect = function (effect, lightIndex) { + var normalizeDirection; + if (this.computeTransformedInformation()) { + this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex); + normalizeDirection = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Normalize(this.transformedDirection); + } + else { + this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex); + normalizeDirection = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Normalize(this.direction); + } + this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex); + this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex); + if (this.projectionTexture && this.projectionTexture.isReady()) { + if (this._projectionTextureViewLightDirty) { + this._computeProjectionTextureViewLightMatrix(); + } + if (this._projectionTextureProjectionLightDirty) { + this._computeProjectionTextureProjectionLightMatrix(); + } + if (this._projectionTextureDirty) { + this._computeProjectionTextureMatrix(); + } + effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix); + effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture); + } + return this; + }; + /** + * Disposes the light and the associated resources. + */ + SpotLight.prototype.dispose = function () { + _super.prototype.dispose.call(this); + if (this._projectionTexture) { + this._projectionTexture.dispose(); + } + }; + /** + * Prepares the list of defines specific to the light type. + * @param defines the list of defines + * @param lightIndex defines the index of the light for the effect + */ + SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) { + defines["SPOTLIGHT" + lightIndex] = true; + defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture && this.projectionTexture.isReady() ? true : false; + }; + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], SpotLight.prototype, "angle", null); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], SpotLight.prototype, "innerAngle", null); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], SpotLight.prototype, "shadowAngleScale", null); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], SpotLight.prototype, "exponent", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], SpotLight.prototype, "projectionTextureLightNear", null); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], SpotLight.prototype, "projectionTextureLightFar", null); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], SpotLight.prototype, "projectionTextureUpDirection", null); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])("projectedLightTexture") + ], SpotLight.prototype, "_projectionTexture", void 0); + return SpotLight; +}(_shadowLight__WEBPACK_IMPORTED_MODULE_5__["ShadowLight"])); + + + +/***/ }), + +/***/ "./Loading/Plugins/babylonFileLoader.ts": +/*!**********************************************!*\ + !*** ./Loading/Plugins/babylonFileLoader.ts ***! + \**********************************************/ +/*! exports provided: _BabylonLoaderRegistered */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_BabylonLoaderRegistered", function() { return _BabylonLoaderRegistered; }); +/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Misc/logger */ "./Misc/logger.ts"); +/* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Cameras/camera */ "./Cameras/camera.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Meshes_mesh__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Meshes/mesh */ "./Meshes/mesh.ts"); +/* harmony import */ var _Meshes_geometry__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Meshes/geometry */ "./Meshes/geometry.ts"); +/* harmony import */ var _Meshes_transformNode__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Meshes/transformNode */ "./Meshes/transformNode.ts"); +/* harmony import */ var _Materials_material__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../Materials/material */ "./Materials/material.ts"); +/* harmony import */ var _Materials_multiMaterial__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../Materials/multiMaterial */ "./Materials/multiMaterial.ts"); +/* harmony import */ var _Materials_Textures_cubeTexture__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../Materials/Textures/cubeTexture */ "./Materials/Textures/cubeTexture.ts"); +/* harmony import */ var _Materials_Textures_hdrCubeTexture__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../../Materials/Textures/hdrCubeTexture */ "./Materials/Textures/hdrCubeTexture.ts"); +/* harmony import */ var _Animations_animationGroup__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../../Animations/animationGroup */ "./Animations/animationGroup.ts"); +/* harmony import */ var _Lights_light__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../../Lights/light */ "./Lights/light.ts"); +/* harmony import */ var _sceneComponent__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../../sceneComponent */ "./sceneComponent.ts"); +/* harmony import */ var _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../../Loading/sceneLoader */ "./Loading/sceneLoader.ts"); +/* harmony import */ var _abstractScene__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../../abstractScene */ "./abstractScene.ts"); +/* harmony import */ var _assetContainer__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../../assetContainer */ "./assetContainer.ts"); +/* harmony import */ var _Actions_actionManager__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../../Actions/actionManager */ "./Actions/actionManager.ts"); +/* harmony import */ var _Bones_skeleton__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../../Bones/skeleton */ "./Bones/skeleton.ts"); +/* harmony import */ var _Morph_morphTargetManager__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../../Morph/morphTargetManager */ "./Morph/morphTargetManager.ts"); +/* harmony import */ var _Physics_Plugins_cannonJSPlugin__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../../Physics/Plugins/cannonJSPlugin */ "./Physics/Plugins/cannonJSPlugin.ts"); +/* harmony import */ var _Physics_Plugins_oimoJSPlugin__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../../Physics/Plugins/oimoJSPlugin */ "./Physics/Plugins/oimoJSPlugin.ts"); +/* harmony import */ var _Physics_Plugins_ammoJSPlugin__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ../../Physics/Plugins/ammoJSPlugin */ "./Physics/Plugins/ammoJSPlugin.ts"); +/* harmony import */ var _Probes_reflectionProbe__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ../../Probes/reflectionProbe */ "./Probes/reflectionProbe.ts"); +/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ../../Misc/typeStore */ "./Misc/typeStore.ts"); +/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ../../Misc/tools */ "./Misc/tools.ts"); + + + + + + + + + + + + + + + + + + + + + + + + + +/** @hidden */ +var _BabylonLoaderRegistered = true; +var parseMaterialById = function (id, parsedData, scene, rootUrl) { + for (var index = 0, cache = parsedData.materials.length; index < cache; index++) { + var parsedMaterial = parsedData.materials[index]; + if (parsedMaterial.id === id) { + return _Materials_material__WEBPACK_IMPORTED_MODULE_6__["Material"].Parse(parsedMaterial, scene, rootUrl); + } + } + return null; +}; +var isDescendantOf = function (mesh, names, hierarchyIds) { + for (var i in names) { + if (mesh.name === names[i]) { + hierarchyIds.push(mesh.id); + return true; + } + } + if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) { + hierarchyIds.push(mesh.id); + return true; + } + return false; +}; +var logOperation = function (operation, producer) { + return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown"); +}; +var loadDetailLevels = function (scene, mesh) { + var mastermesh = mesh; + // Every value specified in the ids array of the lod data points to another mesh which should be used as the lower LOD level. + // The distances (or coverages) array values specified are used along with the lod mesh ids as a hint to determine the switching threshold for the various LODs. + if (mesh._waitingData.lods) { + if (mesh._waitingData.lods.ids && mesh._waitingData.lods.ids.length > 0) { + var lodmeshes = mesh._waitingData.lods.ids; + var wasenabled = mastermesh.isEnabled(false); + if (mesh._waitingData.lods.distances) { + var distances = mesh._waitingData.lods.distances; + if (distances.length >= lodmeshes.length) { + var culling = (distances.length > lodmeshes.length) ? distances[distances.length - 1] : 0; + mastermesh.setEnabled(false); + for (var index = 0; index < lodmeshes.length; index++) { + var lodid = lodmeshes[index]; + var lodmesh = scene.getMeshByID(lodid); + if (lodmesh != null) { + mastermesh.addLODLevel(distances[index], lodmesh); + } + } + if (culling > 0) { + mastermesh.addLODLevel(culling, null); + } + if (wasenabled === true) { + mastermesh.setEnabled(true); + } + } + else { + _Misc_tools__WEBPACK_IMPORTED_MODULE_24__["Tools"].Warn("Invalid level of detail distances for " + mesh.name); + } + } + } + mesh._waitingData.lods = null; + } +}; +var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) { + if (addToScene === void 0) { addToScene = false; } + var container = new _assetContainer__WEBPACK_IMPORTED_MODULE_15__["AssetContainer"](scene); + // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details + // when SceneLoader.debugLogging = true (default), or exception encountered. + // Everything stored in var log instead of writing separate lines to support only writing in exception, + // and avoid problems with multiple concurrent .babylon loads. + var log = "importScene has failed JSON parse"; + try { + var parsedData = JSON.parse(data); + log = ""; + var fullDetails = _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_13__["SceneLoader"].loggingLevel === _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_13__["SceneLoader"].DETAILED_LOGGING; + var index; + var cache; + // Environment texture + if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) { + // PBR needed for both HDR texture (gamma space) & a sky box + var isPBR = parsedData.isPBR !== undefined ? parsedData.isPBR : true; + if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") { + var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128; + var hdrTexture = new _Materials_Textures_hdrCubeTexture__WEBPACK_IMPORTED_MODULE_9__["HDRCubeTexture"]((parsedData.environmentTexture.match(/https?:\/\//g) ? "" : rootUrl) + parsedData.environmentTexture, scene, hdrSize, true, !isPBR); + if (parsedData.environmentTextureRotationY) { + hdrTexture.rotationY = parsedData.environmentTextureRotationY; + } + scene.environmentTexture = hdrTexture; + } + else { + if (_Misc_tools__WEBPACK_IMPORTED_MODULE_24__["Tools"].EndsWith(parsedData.environmentTexture, ".env")) { + var compressedTexture = new _Materials_Textures_cubeTexture__WEBPACK_IMPORTED_MODULE_8__["CubeTexture"]((parsedData.environmentTexture.match(/https?:\/\//g) ? "" : rootUrl) + parsedData.environmentTexture, scene); + if (parsedData.environmentTextureRotationY) { + compressedTexture.rotationY = parsedData.environmentTextureRotationY; + } + scene.environmentTexture = compressedTexture; + } + else { + var cubeTexture = _Materials_Textures_cubeTexture__WEBPACK_IMPORTED_MODULE_8__["CubeTexture"].CreateFromPrefilteredData((parsedData.environmentTexture.match(/https?:\/\//g) ? "" : rootUrl) + parsedData.environmentTexture, scene); + if (parsedData.environmentTextureRotationY) { + cubeTexture.rotationY = parsedData.environmentTextureRotationY; + } + scene.environmentTexture = cubeTexture; + } + } + if (parsedData.createDefaultSkybox === true) { + var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000; + var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0; + scene.createDefaultSkybox(scene.environmentTexture, isPBR, skyboxScale, skyboxBlurLevel); + } + container.environmentTexture = scene.environmentTexture; + } + // Lights + if (parsedData.lights !== undefined && parsedData.lights !== null) { + for (index = 0, cache = parsedData.lights.length; index < cache; index++) { + var parsedLight = parsedData.lights[index]; + var light = _Lights_light__WEBPACK_IMPORTED_MODULE_11__["Light"].Parse(parsedLight, scene); + if (light) { + container.lights.push(light); + log += (index === 0 ? "\n\tLights:" : ""); + log += "\n\t\t" + light.toString(fullDetails); + } + } + } + // Reflection probes + if (parsedData.reflectionProbes !== undefined && parsedData.reflectionProbes !== null) { + for (index = 0, cache = parsedData.reflectionProbes.length; index < cache; index++) { + var parsedReflectionProbe = parsedData.reflectionProbes[index]; + var reflectionProbe = _Probes_reflectionProbe__WEBPACK_IMPORTED_MODULE_22__["ReflectionProbe"].Parse(parsedReflectionProbe, scene, rootUrl); + if (reflectionProbe) { + container.reflectionProbes.push(reflectionProbe); + log += (index === 0 ? "\n\tReflection Probes:" : ""); + log += "\n\t\t" + reflectionProbe.toString(fullDetails); + } + } + } + // Animations + if (parsedData.animations !== undefined && parsedData.animations !== null) { + for (index = 0, cache = parsedData.animations.length; index < cache; index++) { + var parsedAnimation = parsedData.animations[index]; + var internalClass = _Misc_typeStore__WEBPACK_IMPORTED_MODULE_23__["_TypeStore"].GetClass("BABYLON.Animation"); + if (internalClass) { + var animation = internalClass.Parse(parsedAnimation); + scene.animations.push(animation); + container.animations.push(animation); + log += (index === 0 ? "\n\tAnimations:" : ""); + log += "\n\t\t" + animation.toString(fullDetails); + } + } + } + // Materials + if (parsedData.materials !== undefined && parsedData.materials !== null) { + for (index = 0, cache = parsedData.materials.length; index < cache; index++) { + var parsedMaterial = parsedData.materials[index]; + var mat = _Materials_material__WEBPACK_IMPORTED_MODULE_6__["Material"].Parse(parsedMaterial, scene, rootUrl); + if (mat) { + container.materials.push(mat); + log += (index === 0 ? "\n\tMaterials:" : ""); + log += "\n\t\t" + mat.toString(fullDetails); + // Textures + var textures = mat.getActiveTextures(); + textures.forEach(function (t) { + if (container.textures.indexOf(t) == -1) { + container.textures.push(t); + } + }); + } + } + } + if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) { + for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) { + var parsedMultiMaterial = parsedData.multiMaterials[index]; + var mmat = _Materials_multiMaterial__WEBPACK_IMPORTED_MODULE_7__["MultiMaterial"].ParseMultiMaterial(parsedMultiMaterial, scene); + container.multiMaterials.push(mmat); + log += (index === 0 ? "\n\tMultiMaterials:" : ""); + log += "\n\t\t" + mmat.toString(fullDetails); + // Textures + var textures = mmat.getActiveTextures(); + textures.forEach(function (t) { + if (container.textures.indexOf(t) == -1) { + container.textures.push(t); + } + }); + } + } + // Morph targets + if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) { + for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) { + var managerData = _a[_i]; + container.morphTargetManagers.push(_Morph_morphTargetManager__WEBPACK_IMPORTED_MODULE_18__["MorphTargetManager"].Parse(managerData, scene)); + } + } + // Skeletons + if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) { + for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) { + var parsedSkeleton = parsedData.skeletons[index]; + var skeleton = _Bones_skeleton__WEBPACK_IMPORTED_MODULE_17__["Skeleton"].Parse(parsedSkeleton, scene); + container.skeletons.push(skeleton); + log += (index === 0 ? "\n\tSkeletons:" : ""); + log += "\n\t\t" + skeleton.toString(fullDetails); + } + } + // Geometries + var geometries = parsedData.geometries; + if (geometries !== undefined && geometries !== null) { + var addedGeometry = new Array(); + // VertexData + var vertexData = geometries.vertexData; + if (vertexData !== undefined && vertexData !== null) { + for (index = 0, cache = vertexData.length; index < cache; index++) { + var parsedVertexData = vertexData[index]; + addedGeometry.push(_Meshes_geometry__WEBPACK_IMPORTED_MODULE_4__["Geometry"].Parse(parsedVertexData, scene, rootUrl)); + } + } + addedGeometry.forEach(function (g) { + if (g) { + container.geometries.push(g); + } + }); + } + // Transform nodes + if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) { + for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) { + var parsedTransformNode = parsedData.transformNodes[index]; + var node = _Meshes_transformNode__WEBPACK_IMPORTED_MODULE_5__["TransformNode"].Parse(parsedTransformNode, scene, rootUrl); + container.transformNodes.push(node); + } + } + // Meshes + if (parsedData.meshes !== undefined && parsedData.meshes !== null) { + for (index = 0, cache = parsedData.meshes.length; index < cache; index++) { + var parsedMesh = parsedData.meshes[index]; + var mesh = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_3__["Mesh"].Parse(parsedMesh, scene, rootUrl); + container.meshes.push(mesh); + log += (index === 0 ? "\n\tMeshes:" : ""); + log += "\n\t\t" + mesh.toString(fullDetails); + } + } + // Cameras + if (parsedData.cameras !== undefined && parsedData.cameras !== null) { + for (index = 0, cache = parsedData.cameras.length; index < cache; index++) { + var parsedCamera = parsedData.cameras[index]; + var camera = _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__["Camera"].Parse(parsedCamera, scene); + container.cameras.push(camera); + log += (index === 0 ? "\n\tCameras:" : ""); + log += "\n\t\t" + camera.toString(fullDetails); + } + } + // Animation Groups + if (parsedData.animationGroups !== undefined && parsedData.animationGroups !== null) { + for (index = 0, cache = parsedData.animationGroups.length; index < cache; index++) { + var parsedAnimationGroup = parsedData.animationGroups[index]; + var animationGroup = _Animations_animationGroup__WEBPACK_IMPORTED_MODULE_10__["AnimationGroup"].Parse(parsedAnimationGroup, scene); + container.animationGroups.push(animationGroup); + log += (index === 0 ? "\n\tAnimationGroups:" : ""); + log += "\n\t\t" + animationGroup.toString(fullDetails); + } + } + // Browsing all the graph to connect the dots + for (index = 0, cache = scene.cameras.length; index < cache; index++) { + var camera = scene.cameras[index]; + if (camera._waitingParentId) { + camera.parent = scene.getLastEntryByID(camera._waitingParentId); + camera._waitingParentId = null; + } + } + for (index = 0, cache = scene.lights.length; index < cache; index++) { + var light_1 = scene.lights[index]; + if (light_1 && light_1._waitingParentId) { + light_1.parent = scene.getLastEntryByID(light_1._waitingParentId); + light_1._waitingParentId = null; + } + } + // Connect parents & children and parse actions and lods + for (index = 0, cache = scene.transformNodes.length; index < cache; index++) { + var transformNode = scene.transformNodes[index]; + if (transformNode._waitingParentId) { + transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId); + transformNode._waitingParentId = null; + } + } + for (index = 0, cache = scene.meshes.length; index < cache; index++) { + var mesh = scene.meshes[index]; + if (mesh._waitingParentId) { + mesh.parent = scene.getLastEntryByID(mesh._waitingParentId); + mesh._waitingParentId = null; + } + if (mesh._waitingData.lods) { + loadDetailLevels(scene, mesh); + } + } + // link skeleton transform nodes + for (index = 0, cache = scene.skeletons.length; index < cache; index++) { + var skeleton = scene.skeletons[index]; + if (skeleton._hasWaitingData) { + if (skeleton.bones != null) { + skeleton.bones.forEach(function (bone) { + if (bone._waitingTransformNodeId) { + var linkTransformNode = scene.getLastEntryByID(bone._waitingTransformNodeId); + if (linkTransformNode) { + bone.linkTransformNode(linkTransformNode); + } + bone._waitingTransformNodeId = null; + } + }); + } + skeleton._hasWaitingData = null; + } + } + // freeze world matrix application + for (index = 0, cache = scene.meshes.length; index < cache; index++) { + var currentMesh = scene.meshes[index]; + if (currentMesh._waitingData.freezeWorldMatrix) { + currentMesh.freezeWorldMatrix(); + currentMesh._waitingData.freezeWorldMatrix = null; + } + else { + currentMesh.computeWorldMatrix(true); + } + } + // Lights exclusions / inclusions + for (index = 0, cache = scene.lights.length; index < cache; index++) { + var light_2 = scene.lights[index]; + // Excluded check + if (light_2._excludedMeshesIds.length > 0) { + for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) { + var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]); + if (excludedMesh) { + light_2.excludedMeshes.push(excludedMesh); + } + } + light_2._excludedMeshesIds = []; + } + // Included check + if (light_2._includedOnlyMeshesIds.length > 0) { + for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) { + var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]); + if (includedOnlyMesh) { + light_2.includedOnlyMeshes.push(includedOnlyMesh); + } + } + light_2._includedOnlyMeshesIds = []; + } + } + _abstractScene__WEBPACK_IMPORTED_MODULE_14__["AbstractScene"].Parse(parsedData, scene, container, rootUrl); + // Actions (scene) Done last as it can access other objects. + for (index = 0, cache = scene.meshes.length; index < cache; index++) { + var mesh = scene.meshes[index]; + if (mesh._waitingData.actions) { + _Actions_actionManager__WEBPACK_IMPORTED_MODULE_16__["ActionManager"].Parse(mesh._waitingData.actions, mesh, scene); + mesh._waitingData.actions = null; + } + } + if (parsedData.actions !== undefined && parsedData.actions !== null) { + _Actions_actionManager__WEBPACK_IMPORTED_MODULE_16__["ActionManager"].Parse(parsedData.actions, null, scene); + } + if (!addToScene) { + container.removeAllFromScene(); + } + } + catch (err) { + var msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log; + if (onError) { + onError(msg, err); + } + else { + _Misc_logger__WEBPACK_IMPORTED_MODULE_0__["Logger"].Log(msg); + throw err; + } + } + finally { + if (log !== null && _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_13__["SceneLoader"].loggingLevel !== _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_13__["SceneLoader"].NO_LOGGING) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_0__["Logger"].Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (_Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_13__["SceneLoader"].loggingLevel !== _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_13__["SceneLoader"].MINIMAL_LOGGING ? log : "")); + } + } + return container; +}; +_Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_13__["SceneLoader"].RegisterPlugin({ + name: "babylon.js", + extensions: ".babylon", + canDirectLoad: function (data) { + if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled + return true; + } + return false; + }, + importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) { + // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details + // when SceneLoader.debugLogging = true (default), or exception encountered. + // Everything stored in var log instead of writing separate lines to support only writing in exception, + // and avoid problems with multiple concurrent .babylon loads. + var log = "importMesh has failed JSON parse"; + try { + var parsedData = JSON.parse(data); + log = ""; + var fullDetails = _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_13__["SceneLoader"].loggingLevel === _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_13__["SceneLoader"].DETAILED_LOGGING; + if (!meshesNames) { + meshesNames = null; + } + else if (!Array.isArray(meshesNames)) { + meshesNames = [meshesNames]; + } + var hierarchyIds = new Array(); + if (parsedData.meshes !== undefined && parsedData.meshes !== null) { + var loadedSkeletonsIds = []; + var loadedMaterialsIds = []; + var index; + var cache; + for (index = 0, cache = parsedData.meshes.length; index < cache; index++) { + var parsedMesh = parsedData.meshes[index]; + if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) { + if (meshesNames !== null) { + // Remove found mesh name from list. + delete meshesNames[meshesNames.indexOf(parsedMesh.name)]; + } + //Geometry? + if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) { + //does the file contain geometries? + if (parsedData.geometries !== undefined && parsedData.geometries !== null) { + //find the correct geometry and add it to the scene + var found = false; + ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) { + if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) { + return; + } + else { + parsedData.geometries[geometryType].forEach(function (parsedGeometryData) { + if (parsedGeometryData.id === parsedMesh.geometryId) { + switch (geometryType) { + case "vertexData": + _Meshes_geometry__WEBPACK_IMPORTED_MODULE_4__["Geometry"].Parse(parsedGeometryData, scene, rootUrl); + break; + } + found = true; + } + }); + } + }); + if (found === false) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_0__["Logger"].Warn("Geometry not found for mesh " + parsedMesh.id); + } + } + } + // Material ? + if (parsedMesh.materialId) { + var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1); + if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) { + for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) { + var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex]; + if (parsedMultiMaterial.id === parsedMesh.materialId) { + for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) { + var subMatId = parsedMultiMaterial.materials[matIndex]; + loadedMaterialsIds.push(subMatId); + var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl); + if (mat) { + log += "\n\tMaterial " + mat.toString(fullDetails); + } + } + loadedMaterialsIds.push(parsedMultiMaterial.id); + var mmat = _Materials_multiMaterial__WEBPACK_IMPORTED_MODULE_7__["MultiMaterial"].ParseMultiMaterial(parsedMultiMaterial, scene); + if (mmat) { + materialFound = true; + log += "\n\tMulti-Material " + mmat.toString(fullDetails); + } + break; + } + } + } + if (materialFound === false) { + loadedMaterialsIds.push(parsedMesh.materialId); + var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl); + if (!mat) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_0__["Logger"].Warn("Material not found for mesh " + parsedMesh.id); + } + else { + log += "\n\tMaterial " + mat.toString(fullDetails); + } + } + } + // Skeleton ? + if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) { + var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1); + if (skeletonAlreadyLoaded === false) { + for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) { + var parsedSkeleton = parsedData.skeletons[skeletonIndex]; + if (parsedSkeleton.id === parsedMesh.skeletonId) { + var skeleton = _Bones_skeleton__WEBPACK_IMPORTED_MODULE_17__["Skeleton"].Parse(parsedSkeleton, scene); + skeletons.push(skeleton); + loadedSkeletonsIds.push(parsedSkeleton.id); + log += "\n\tSkeleton " + skeleton.toString(fullDetails); + } + } + } + } + // Morph targets ? + if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) { + for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) { + var managerData = _a[_i]; + _Morph_morphTargetManager__WEBPACK_IMPORTED_MODULE_18__["MorphTargetManager"].Parse(managerData, scene); + } + } + var mesh = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_3__["Mesh"].Parse(parsedMesh, scene, rootUrl); + meshes.push(mesh); + log += "\n\tMesh " + mesh.toString(fullDetails); + } + } + // Connecting parents and lods + var currentMesh; + for (index = 0, cache = scene.meshes.length; index < cache; index++) { + currentMesh = scene.meshes[index]; + if (currentMesh._waitingParentId) { + currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId); + currentMesh._waitingParentId = null; + } + if (currentMesh._waitingData.lods) { + loadDetailLevels(scene, currentMesh); + } + } + // link skeleton transform nodes + for (index = 0, cache = scene.skeletons.length; index < cache; index++) { + var skeleton = scene.skeletons[index]; + if (skeleton._hasWaitingData) { + if (skeleton.bones != null) { + skeleton.bones.forEach(function (bone) { + if (bone._waitingTransformNodeId) { + var linkTransformNode = scene.getLastEntryByID(bone._waitingTransformNodeId); + if (linkTransformNode) { + bone.linkTransformNode(linkTransformNode); + } + bone._waitingTransformNodeId = null; + } + }); + } + skeleton._hasWaitingData = null; + } + } + // freeze and compute world matrix application + for (index = 0, cache = scene.meshes.length; index < cache; index++) { + currentMesh = scene.meshes[index]; + if (currentMesh._waitingData.freezeWorldMatrix) { + currentMesh.freezeWorldMatrix(); + currentMesh._waitingData.freezeWorldMatrix = null; + } + else { + currentMesh.computeWorldMatrix(true); + } + } + } + // Particles + if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) { + var parser = _abstractScene__WEBPACK_IMPORTED_MODULE_14__["AbstractScene"].GetIndividualParser(_sceneComponent__WEBPACK_IMPORTED_MODULE_12__["SceneComponentConstants"].NAME_PARTICLESYSTEM); + if (parser) { + for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) { + var parsedParticleSystem = parsedData.particleSystems[index]; + if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) { + particleSystems.push(parser(parsedParticleSystem, scene, rootUrl)); + } + } + } + } + return true; + } + catch (err) { + var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log; + if (onError) { + onError(msg, err); + } + else { + _Misc_logger__WEBPACK_IMPORTED_MODULE_0__["Logger"].Log(msg); + throw err; + } + } + finally { + if (log !== null && _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_13__["SceneLoader"].loggingLevel !== _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_13__["SceneLoader"].NO_LOGGING) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_0__["Logger"].Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (_Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_13__["SceneLoader"].loggingLevel !== _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_13__["SceneLoader"].MINIMAL_LOGGING ? log : "")); + } + } + return false; + }, + load: function (scene, data, rootUrl, onError) { + // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details + // when SceneLoader.debugLogging = true (default), or exception encountered. + // Everything stored in var log instead of writing separate lines to support only writing in exception, + // and avoid problems with multiple concurrent .babylon loads. + var log = "importScene has failed JSON parse"; + try { + var parsedData = JSON.parse(data); + log = ""; + // Scene + if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) { + scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !_Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_13__["SceneLoader"].ForceFullSceneLoadingForIncremental; + } + if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) { + scene.autoClear = parsedData.autoClear; + } + if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) { + scene.clearColor = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color4"].FromArray(parsedData.clearColor); + } + if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) { + scene.ambientColor = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color3"].FromArray(parsedData.ambientColor); + } + if (parsedData.gravity !== undefined && parsedData.gravity !== null) { + scene.gravity = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].FromArray(parsedData.gravity); + } + // Fog + if (parsedData.fogMode && parsedData.fogMode !== 0) { + scene.fogMode = parsedData.fogMode; + scene.fogColor = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color3"].FromArray(parsedData.fogColor); + scene.fogStart = parsedData.fogStart; + scene.fogEnd = parsedData.fogEnd; + scene.fogDensity = parsedData.fogDensity; + log += "\tFog mode for scene: "; + switch (scene.fogMode) { + // getters not compiling, so using hardcoded + case 1: + log += "exp\n"; + break; + case 2: + log += "exp2\n"; + break; + case 3: + log += "linear\n"; + break; + } + } + //Physics + if (parsedData.physicsEnabled) { + var physicsPlugin; + if (parsedData.physicsEngine === "cannon") { + physicsPlugin = new _Physics_Plugins_cannonJSPlugin__WEBPACK_IMPORTED_MODULE_19__["CannonJSPlugin"](); + } + else if (parsedData.physicsEngine === "oimo") { + physicsPlugin = new _Physics_Plugins_oimoJSPlugin__WEBPACK_IMPORTED_MODULE_20__["OimoJSPlugin"](); + } + else if (parsedData.physicsEngine === "ammo") { + physicsPlugin = new _Physics_Plugins_ammoJSPlugin__WEBPACK_IMPORTED_MODULE_21__["AmmoJSPlugin"](); + } + log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n"; + //else - default engine, which is currently oimo + var physicsGravity = parsedData.physicsGravity ? _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].FromArray(parsedData.physicsGravity) : null; + scene.enablePhysics(physicsGravity, physicsPlugin); + } + // Metadata + if (parsedData.metadata !== undefined && parsedData.metadata !== null) { + scene.metadata = parsedData.metadata; + } + //collisions, if defined. otherwise, default is true + if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) { + scene.collisionsEnabled = parsedData.collisionsEnabled; + } + var container = loadAssetContainer(scene, data, rootUrl, onError, true); + if (!container) { + return false; + } + if (parsedData.autoAnimate) { + scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0); + } + if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) { + scene.setActiveCameraByID(parsedData.activeCameraID); + } + // Environment texture + if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) { + // PBR needed for both HDR texture (gamma space) & a sky box + var isPBR = parsedData.isPBR !== undefined ? parsedData.isPBR : true; + if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") { + var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128; + var hdrTexture = new _Materials_Textures_hdrCubeTexture__WEBPACK_IMPORTED_MODULE_9__["HDRCubeTexture"](rootUrl + parsedData.environmentTexture, scene, hdrSize, true, !isPBR); + if (parsedData.environmentTextureRotationY) { + hdrTexture.rotationY = parsedData.environmentTextureRotationY; + } + scene.environmentTexture = hdrTexture; + } + else { + if (_Misc_tools__WEBPACK_IMPORTED_MODULE_24__["Tools"].EndsWith(parsedData.environmentTexture, ".env")) { + var compressedTexture = new _Materials_Textures_cubeTexture__WEBPACK_IMPORTED_MODULE_8__["CubeTexture"](rootUrl + parsedData.environmentTexture, scene); + if (parsedData.environmentTextureRotationY) { + compressedTexture.rotationY = parsedData.environmentTextureRotationY; + } + scene.environmentTexture = compressedTexture; + } + else { + var cubeTexture = _Materials_Textures_cubeTexture__WEBPACK_IMPORTED_MODULE_8__["CubeTexture"].CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene); + if (parsedData.environmentTextureRotationY) { + cubeTexture.rotationY = parsedData.environmentTextureRotationY; + } + scene.environmentTexture = cubeTexture; + } + } + if (parsedData.createDefaultSkybox === true) { + var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000; + var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0; + scene.createDefaultSkybox(scene.environmentTexture, isPBR, skyboxScale, skyboxBlurLevel); + } + } + // Finish + return true; + } + catch (err) { + var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log; + if (onError) { + onError(msg, err); + } + else { + _Misc_logger__WEBPACK_IMPORTED_MODULE_0__["Logger"].Log(msg); + throw err; + } + } + finally { + if (log !== null && _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_13__["SceneLoader"].loggingLevel !== _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_13__["SceneLoader"].NO_LOGGING) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_0__["Logger"].Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (_Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_13__["SceneLoader"].loggingLevel !== _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_13__["SceneLoader"].MINIMAL_LOGGING ? log : "")); + } + } + return false; + }, + loadAssetContainer: function (scene, data, rootUrl, onError) { + var container = loadAssetContainer(scene, data, rootUrl, onError); + return container; + } +}); + + +/***/ }), + +/***/ "./Loading/Plugins/index.ts": +/*!**********************************!*\ + !*** ./Loading/Plugins/index.ts ***! + \**********************************/ +/*! exports provided: _BabylonLoaderRegistered */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _babylonFileLoader__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./babylonFileLoader */ "./Loading/Plugins/babylonFileLoader.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_BabylonLoaderRegistered", function() { return _babylonFileLoader__WEBPACK_IMPORTED_MODULE_0__["_BabylonLoaderRegistered"]; }); + + + + +/***/ }), + +/***/ "./Loading/index.ts": +/*!**************************!*\ + !*** ./Loading/index.ts ***! + \**************************/ +/*! exports provided: DefaultLoadingScreen, SceneLoaderProgressEvent, SceneLoader, SceneLoaderFlags, _BabylonLoaderRegistered */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _loadingScreen__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./loadingScreen */ "./Loading/loadingScreen.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DefaultLoadingScreen", function() { return _loadingScreen__WEBPACK_IMPORTED_MODULE_0__["DefaultLoadingScreen"]; }); + +/* harmony import */ var _Plugins_index__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Plugins/index */ "./Loading/Plugins/index.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_BabylonLoaderRegistered", function() { return _Plugins_index__WEBPACK_IMPORTED_MODULE_1__["_BabylonLoaderRegistered"]; }); + +/* harmony import */ var _sceneLoader__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./sceneLoader */ "./Loading/sceneLoader.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SceneLoaderProgressEvent", function() { return _sceneLoader__WEBPACK_IMPORTED_MODULE_2__["SceneLoaderProgressEvent"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SceneLoader", function() { return _sceneLoader__WEBPACK_IMPORTED_MODULE_2__["SceneLoader"]; }); + +/* harmony import */ var _sceneLoaderFlags__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./sceneLoaderFlags */ "./Loading/sceneLoaderFlags.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SceneLoaderFlags", function() { return _sceneLoaderFlags__WEBPACK_IMPORTED_MODULE_3__["SceneLoaderFlags"]; }); + + + + + + + +/***/ }), + +/***/ "./Loading/loadingScreen.ts": +/*!**********************************!*\ + !*** ./Loading/loadingScreen.ts ***! + \**********************************/ +/*! exports provided: DefaultLoadingScreen */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DefaultLoadingScreen", function() { return DefaultLoadingScreen; }); +/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Engines/engine */ "./Engines/engine.ts"); + +/** + * Class used for the default loading screen + * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen + */ +var DefaultLoadingScreen = /** @class */ (function () { + /** + * Creates a new default loading screen + * @param _renderingCanvas defines the canvas used to render the scene + * @param _loadingText defines the default text to display + * @param _loadingDivBackgroundColor defines the default background color + */ + function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) { + var _this = this; + if (_loadingText === void 0) { _loadingText = ""; } + if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; } + this._renderingCanvas = _renderingCanvas; + this._loadingText = _loadingText; + this._loadingDivBackgroundColor = _loadingDivBackgroundColor; + // Resize + this._resizeLoadingUI = function () { + var canvasRect = _this._renderingCanvas.getBoundingClientRect(); + var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position; + if (!_this._loadingDiv) { + return; + } + _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute"; + _this._loadingDiv.style.left = canvasRect.left + "px"; + _this._loadingDiv.style.top = canvasRect.top + "px"; + _this._loadingDiv.style.width = canvasRect.width + "px"; + _this._loadingDiv.style.height = canvasRect.height + "px"; + }; + } + /** + * Function called to display the loading screen + */ + DefaultLoadingScreen.prototype.displayLoadingUI = function () { + if (this._loadingDiv) { + // Do not add a loading screen if there is already one + return; + } + this._loadingDiv = document.createElement("div"); + this._loadingDiv.id = "babylonjsLoadingDiv"; + this._loadingDiv.style.opacity = "0"; + this._loadingDiv.style.transition = "opacity 1.5s ease"; + this._loadingDiv.style.pointerEvents = "none"; + // Loading text + this._loadingTextDiv = document.createElement("div"); + this._loadingTextDiv.style.position = "absolute"; + this._loadingTextDiv.style.left = "0"; + this._loadingTextDiv.style.top = "50%"; + this._loadingTextDiv.style.marginTop = "80px"; + this._loadingTextDiv.style.width = "100%"; + this._loadingTextDiv.style.height = "20px"; + this._loadingTextDiv.style.fontFamily = "Arial"; + this._loadingTextDiv.style.fontSize = "14px"; + this._loadingTextDiv.style.color = "white"; + this._loadingTextDiv.style.textAlign = "center"; + this._loadingTextDiv.innerHTML = "Loading"; + this._loadingDiv.appendChild(this._loadingTextDiv); + //set the predefined text + this._loadingTextDiv.innerHTML = this._loadingText; + // Generating keyframes + var style = document.createElement('style'); + style.type = 'text/css'; + var keyFrames = "@-webkit-keyframes spin1 { 0% { -webkit-transform: rotate(0deg);}\n 100% { -webkit-transform: rotate(360deg);}\n } @keyframes spin1 { 0% { transform: rotate(0deg);}\n 100% { transform: rotate(360deg);}\n }"; + style.innerHTML = keyFrames; + document.getElementsByTagName('head')[0].appendChild(style); + // Loading img + var imgBack = new Image(); + if (!DefaultLoadingScreen.DefaultLogoUrl) { + imgBack.src = "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxODAuMTcgMjA4LjA0Ij48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2ZmZjt9LmNscy0ye2ZpbGw6I2UwNjg0Yjt9LmNscy0ze2ZpbGw6I2JiNDY0Yjt9LmNscy00e2ZpbGw6I2UwZGVkODt9LmNscy01e2ZpbGw6I2Q1ZDJjYTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPkJhYnlsb25Mb2dvPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iUGFnZV9FbGVtZW50cyIgZGF0YS1uYW1lPSJQYWdlIEVsZW1lbnRzIj48cGF0aCBjbGFzcz0iY2xzLTEiIGQ9Ik05MC4wOSwwLDAsNTJWMTU2bDkwLjA5LDUyLDkwLjA4LTUyVjUyWiIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtMiIgcG9pbnRzPSIxODAuMTcgNTIuMDEgMTUxLjk3IDM1LjczIDEyNC44NSA1MS4zOSAxNTMuMDUgNjcuNjcgMTgwLjE3IDUyLjAxIi8+PHBvbHlnb24gY2xhc3M9ImNscy0yIiBwb2ludHM9IjI3LjEyIDY3LjY3IDExNy4yMSAxNS42NiA5MC4wOCAwIDAgNTIuMDEgMjcuMTIgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTIiIHBvaW50cz0iNjEuODkgMTIwLjMgOTAuMDggMTM2LjU4IDExOC4yOCAxMjAuMyA5MC4wOCAxMDQuMDIgNjEuODkgMTIwLjMiLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDE1My4wNSAxNDAuMzcgOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyAwIDUyLjAxIDAgMTU2LjAzIDkwLjA4IDIwOC4wNCAxODAuMTcgMTU2LjAzIDE4MC4xNyA1Mi4wMSAxNTMuMDUgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iOTAuMDggNzEuNDYgNjEuODkgODcuNzQgNjEuODkgMTIwLjMgOTAuMDggMTA0LjAyIDExOC4yOCAxMjAuMyAxMTguMjggODcuNzQgOTAuMDggNzEuNDYiLz48cG9seWdvbiBjbGFzcz0iY2xzLTQiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDExOC4yOCA4Ny43NCAxMTguMjggMTIwLjMgOTAuMDggMTM2LjU4IDkwLjA4IDE3Ni43MiAxNTMuMDUgMTQwLjM3IDE1My4wNSA2Ny42NyIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtNSIgcG9pbnRzPSIyNy4xMiA2Ny42NyA2MS44OSA4Ny43NCA2MS44OSAxMjAuMyA5MC4wOCAxMzYuNTggOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyIvPjwvZz48L2c+PC9zdmc+"; + } + else { + imgBack.src = DefaultLoadingScreen.DefaultLogoUrl; + } + imgBack.style.position = "absolute"; + imgBack.style.left = "40%"; + imgBack.style.top = "40%"; + imgBack.style.width = "20%"; + imgBack.style.height = "20%"; + // Loading spinner + var imgSpinner = new Image(); + if (!DefaultLoadingScreen.DefaultSpinnerUrl) { + imgSpinner.src = "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzOTIgMzkyIj48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2UwNjg0Yjt9LmNscy0ye2ZpbGw6bm9uZTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPlNwaW5uZXJJY29uPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iU3Bpbm5lciI+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNNDAuMjEsMTI2LjQzYzMuNy03LjMxLDcuNjctMTQuNDQsMTItMjEuMzJsMy4zNi01LjEsMy41Mi01YzEuMjMtMS42MywyLjQxLTMuMjksMy42NS00LjkxczIuNTMtMy4yMSwzLjgyLTQuNzlBMTg1LjIsMTg1LjIsMCwwLDEsODMuNCw2Ny40M2EyMDgsMjA4LDAsMCwxLDE5LTE1LjY2YzMuMzUtMi40MSw2Ljc0LTQuNzgsMTAuMjUtN3M3LjExLTQuMjgsMTAuNzUtNi4zMmM3LjI5LTQsMTQuNzMtOCwyMi41My0xMS40OSwzLjktMS43Miw3Ljg4LTMuMywxMi00LjY0YTEwNC4yMiwxMDQuMjIsMCwwLDEsMTIuNDQtMy4yMyw2Mi40NCw2Mi40NCwwLDAsMSwxMi43OC0xLjM5QTI1LjkyLDI1LjkyLDAsMCwxLDE5NiwyMS40NGE2LjU1LDYuNTUsMCwwLDEsMi4wNSw5LDYuNjYsNi42NiwwLDAsMS0xLjY0LDEuNzhsLS40MS4yOWEyMi4wNywyMi4wNywwLDAsMS01Ljc4LDMsMzAuNDIsMzAuNDIsMCwwLDEtNS42NywxLjYyLDM3LjgyLDM3LjgyLDAsMCwxLTUuNjkuNzFjLTEsMC0xLjkuMTgtMi44NS4yNmwtMi44NS4yNHEtNS43Mi41MS0xMS40OCwxLjFjLTMuODQuNC03LjcxLjgyLTExLjU4LDEuNGExMTIuMzQsMTEyLjM0LDAsMCwwLTIyLjk0LDUuNjFjLTMuNzIsMS4zNS03LjM0LDMtMTAuOTQsNC42NHMtNy4xNCwzLjUxLTEwLjYsNS41MUExNTEuNiwxNTEuNiwwLDAsMCw2OC41Niw4N0M2Ny4yMyw4OC40OCw2Niw5MCw2NC42NCw5MS41NnMtMi41MSwzLjE1LTMuNzUsNC43M2wtMy41NCw0LjljLTEuMTMsMS42Ni0yLjIzLDMuMzUtMy4zMyw1YTEyNywxMjcsMCwwLDAtMTAuOTMsMjEuNDksMS41OCwxLjU4LDAsMSwxLTMtMS4xNVM0MC4xOSwxMjYuNDcsNDAuMjEsMTI2LjQzWiIvPjxyZWN0IGNsYXNzPSJjbHMtMiIgd2lkdGg9IjM5MiIgaGVpZ2h0PSIzOTIiLz48L2c+PC9nPjwvc3ZnPg=="; + } + else { + imgSpinner.src = DefaultLoadingScreen.DefaultSpinnerUrl; + } + imgSpinner.style.position = "absolute"; + imgSpinner.style.left = "30%"; + imgSpinner.style.top = "30%"; + imgSpinner.style.width = "40%"; + imgSpinner.style.height = "40%"; + imgSpinner.style.animation = "spin1 0.75s infinite linear"; + imgSpinner.style.webkitAnimation = "spin1 0.75s infinite linear"; + imgSpinner.style.transformOrigin = "50% 50%"; + imgSpinner.style.webkitTransformOrigin = "50% 50%"; + this._loadingDiv.appendChild(imgBack); + this._loadingDiv.appendChild(imgSpinner); + this._resizeLoadingUI(); + window.addEventListener("resize", this._resizeLoadingUI); + this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor; + document.body.appendChild(this._loadingDiv); + this._loadingDiv.style.opacity = "1"; + }; + /** + * Function called to hide the loading screen + */ + DefaultLoadingScreen.prototype.hideLoadingUI = function () { + var _this = this; + if (!this._loadingDiv) { + return; + } + var onTransitionEnd = function () { + if (!_this._loadingDiv) { + return; + } + if (_this._loadingDiv.parentElement) { + _this._loadingDiv.parentElement.removeChild(_this._loadingDiv); + } + window.removeEventListener("resize", _this._resizeLoadingUI); + _this._loadingDiv = null; + }; + this._loadingDiv.style.opacity = "0"; + this._loadingDiv.addEventListener("transitionend", onTransitionEnd); + }; + Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", { + get: function () { + return this._loadingText; + }, + /** + * Gets or sets the text to display while loading + */ + set: function (text) { + this._loadingText = text; + if (this._loadingTextDiv) { + this._loadingTextDiv.innerHTML = this._loadingText; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", { + /** + * Gets or sets the color to use for the background + */ + get: function () { + return this._loadingDivBackgroundColor; + }, + set: function (color) { + this._loadingDivBackgroundColor = color; + if (!this._loadingDiv) { + return; + } + this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor; + }, + enumerable: true, + configurable: true + }); + /** Gets or sets the logo url to use for the default loading screen */ + DefaultLoadingScreen.DefaultLogoUrl = ""; + /** Gets or sets the spinner url to use for the default loading screen */ + DefaultLoadingScreen.DefaultSpinnerUrl = ""; + return DefaultLoadingScreen; +}()); + +_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].DefaultLoadingScreenFactory = function (canvas) { return new DefaultLoadingScreen(canvas); }; + + +/***/ }), + +/***/ "./Loading/sceneLoader.ts": +/*!********************************!*\ + !*** ./Loading/sceneLoader.ts ***! + \********************************/ +/*! exports provided: SceneLoaderProgressEvent, SceneLoader */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SceneLoaderProgressEvent", function() { return SceneLoaderProgressEvent; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SceneLoader", function() { return SceneLoader; }); +/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/tools */ "./Misc/tools.ts"); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _Misc_filesInputStore__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/filesInputStore */ "./Misc/filesInputStore.ts"); +/* harmony import */ var _scene__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../scene */ "./scene.ts"); +/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Engines/engine */ "./Engines/engine.ts"); +/* harmony import */ var _Engines_engineStore__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Engines/engineStore */ "./Engines/engineStore.ts"); +/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts"); +/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts"); +/* harmony import */ var _sceneLoaderFlags__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./sceneLoaderFlags */ "./Loading/sceneLoaderFlags.ts"); + + + + + + + + + +/** + * Class used to represent data loading progression + */ +var SceneLoaderProgressEvent = /** @class */ (function () { + /** + * Create a new progress event + * @param lengthComputable defines if data length to load can be evaluated + * @param loaded defines the loaded data length + * @param total defines the data length to load + */ + function SceneLoaderProgressEvent( + /** defines if data length to load can be evaluated */ + lengthComputable, + /** defines the loaded data length */ + loaded, + /** defines the data length to load */ + total) { + this.lengthComputable = lengthComputable; + this.loaded = loaded; + this.total = total; + } + /** + * Creates a new SceneLoaderProgressEvent from a ProgressEvent + * @param event defines the source event + * @returns a new SceneLoaderProgressEvent + */ + SceneLoaderProgressEvent.FromProgressEvent = function (event) { + return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total); + }; + return SceneLoaderProgressEvent; +}()); + +/** + * Class used to load scene from various file formats using registered plugins + * @see http://doc.babylonjs.com/how_to/load_from_any_file_type + */ +var SceneLoader = /** @class */ (function () { + function SceneLoader() { + } + Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", { + /** + * Gets or sets a boolean indicating if entire scene must be loaded even if scene contains incremental data + */ + get: function () { + return _sceneLoaderFlags__WEBPACK_IMPORTED_MODULE_8__["SceneLoaderFlags"].ForceFullSceneLoadingForIncremental; + }, + set: function (value) { + _sceneLoaderFlags__WEBPACK_IMPORTED_MODULE_8__["SceneLoaderFlags"].ForceFullSceneLoadingForIncremental = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SceneLoader, "ShowLoadingScreen", { + /** + * Gets or sets a boolean indicating if loading screen must be displayed while loading a scene + */ + get: function () { + return _sceneLoaderFlags__WEBPACK_IMPORTED_MODULE_8__["SceneLoaderFlags"].ShowLoadingScreen; + }, + set: function (value) { + _sceneLoaderFlags__WEBPACK_IMPORTED_MODULE_8__["SceneLoaderFlags"].ShowLoadingScreen = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SceneLoader, "loggingLevel", { + /** + * Defines the current logging level (while loading the scene) + * @ignorenaming + */ + get: function () { + return _sceneLoaderFlags__WEBPACK_IMPORTED_MODULE_8__["SceneLoaderFlags"].loggingLevel; + }, + set: function (value) { + _sceneLoaderFlags__WEBPACK_IMPORTED_MODULE_8__["SceneLoaderFlags"].loggingLevel = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", { + /** + * Gets or set a boolean indicating if matrix weights must be cleaned upon loading + */ + get: function () { + return _sceneLoaderFlags__WEBPACK_IMPORTED_MODULE_8__["SceneLoaderFlags"].CleanBoneMatrixWeights; + }, + set: function (value) { + _sceneLoaderFlags__WEBPACK_IMPORTED_MODULE_8__["SceneLoaderFlags"].CleanBoneMatrixWeights = value; + }, + enumerable: true, + configurable: true + }); + SceneLoader._getDefaultPlugin = function () { + return SceneLoader._registeredPlugins[".babylon"]; + }; + SceneLoader._getPluginForExtension = function (extension) { + var registeredPlugin = SceneLoader._registeredPlugins[extension]; + if (registeredPlugin) { + return registeredPlugin; + } + _Misc_logger__WEBPACK_IMPORTED_MODULE_6__["Logger"].Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: http://doc.babylonjs.com/how_to/load_from_any_file_type"); + return SceneLoader._getDefaultPlugin(); + }; + SceneLoader._getPluginForDirectLoad = function (data) { + for (var extension in SceneLoader._registeredPlugins) { + var plugin = SceneLoader._registeredPlugins[extension].plugin; + if (plugin.canDirectLoad && plugin.canDirectLoad(data)) { + return SceneLoader._registeredPlugins[extension]; + } + } + return SceneLoader._getDefaultPlugin(); + }; + SceneLoader._getPluginForFilename = function (sceneFilename) { + var queryStringPosition = sceneFilename.indexOf("?"); + if (queryStringPosition !== -1) { + sceneFilename = sceneFilename.substring(0, queryStringPosition); + } + var dotPosition = sceneFilename.lastIndexOf("."); + var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase(); + return SceneLoader._getPluginForExtension(extension); + }; + // use babylon file loader directly if sceneFilename is prefixed with "data:" + SceneLoader._getDirectLoad = function (sceneFilename) { + if (sceneFilename.substr(0, 5) === "data:") { + return sceneFilename.substr(5); + } + return null; + }; + SceneLoader._loadData = function (fileInfo, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) { + var directLoad = SceneLoader._getDirectLoad(fileInfo.name); + var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(fileInfo.name) : SceneLoader._getPluginForFilename(fileInfo.name)); + var plugin; + if (registeredPlugin.plugin.createPlugin) { + plugin = registeredPlugin.plugin.createPlugin(); + } + else { + plugin = registeredPlugin.plugin; + } + if (!plugin) { + throw "The loader plugin corresponding to the file type you are trying to load has not been found. If using es6, please import the plugin you wish to use before."; + } + var useArrayBuffer = registeredPlugin.isBinary; + var offlineProvider; + SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin); + var dataCallback = function (data, responseURL) { + if (scene.isDisposed) { + onError("Scene has been disposed"); + return; + } + scene.offlineProvider = offlineProvider; + onSuccess(plugin, data, responseURL); + }; + var request = null; + var pluginDisposed = false; + var onDisposeObservable = plugin.onDisposeObservable; + if (onDisposeObservable) { + onDisposeObservable.add(function () { + pluginDisposed = true; + if (request) { + request.abort(); + request = null; + } + onDispose(); + }); + } + var manifestChecked = function () { + if (pluginDisposed) { + return; + } + request = _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].LoadFile(fileInfo.url, dataCallback, onProgress ? function (event) { + onProgress(SceneLoaderProgressEvent.FromProgressEvent(event)); + } : undefined, offlineProvider, useArrayBuffer, function (request, exception) { + onError("Failed to load scene." + (exception ? " " + exception.message : ""), exception); + }); + }; + if (directLoad) { + dataCallback(directLoad); + return plugin; + } + var file = fileInfo.file || _Misc_filesInputStore__WEBPACK_IMPORTED_MODULE_2__["FilesInputStore"].FilesToLoad[fileInfo.name.toLowerCase()]; + if (fileInfo.rootUrl.indexOf("file:") === -1 || (fileInfo.rootUrl.indexOf("file:") !== -1 && !file)) { + var engine = scene.getEngine(); + var canUseOfflineSupport = engine.enableOfflineSupport; + if (canUseOfflineSupport) { + // Also check for exceptions + var exceptionFound = false; + for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) { + var regex = _a[_i]; + if (regex.test(fileInfo.url)) { + exceptionFound = true; + break; + } + } + canUseOfflineSupport = !exceptionFound; + } + if (canUseOfflineSupport && _Engines_engine__WEBPACK_IMPORTED_MODULE_4__["Engine"].OfflineProviderFactory) { + // Checking if a manifest file has been set for this scene and if offline mode has been requested + offlineProvider = _Engines_engine__WEBPACK_IMPORTED_MODULE_4__["Engine"].OfflineProviderFactory(fileInfo.url, manifestChecked, engine.disableManifestCheck); + } + else { + manifestChecked(); + } + } + // Loading file from disk via input file or drag'n'drop + else { + if (file) { + request = _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].ReadFile(file, dataCallback, onProgress, useArrayBuffer); + } + else { + onError("Unable to find file named " + fileInfo.name); + } + } + return plugin; + }; + SceneLoader._getFileInfo = function (rootUrl, sceneFilename) { + var url; + var name; + var file = null; + if (!sceneFilename) { + url = rootUrl; + name = _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].GetFilename(rootUrl); + rootUrl = _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].GetFolderPath(rootUrl); + } + else if (sceneFilename.name) { + var sceneFile = sceneFilename; + url = rootUrl + sceneFile.name; + name = sceneFile.name; + file = sceneFile; + } + else { + var filename = sceneFilename; + if (filename.substr(0, 1) === "/") { + _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].Error("Wrong sceneFilename parameter"); + return null; + } + url = rootUrl + filename; + name = filename; + } + return { + url: url, + rootUrl: rootUrl, + name: name, + file: file + }; + }; + // Public functions + /** + * Gets a plugin that can load the given extension + * @param extension defines the extension to load + * @returns a plugin or null if none works + */ + SceneLoader.GetPluginForExtension = function (extension) { + return SceneLoader._getPluginForExtension(extension).plugin; + }; + /** + * Gets a boolean indicating that the given extension can be loaded + * @param extension defines the extension to load + * @returns true if the extension is supported + */ + SceneLoader.IsPluginForExtensionAvailable = function (extension) { + return !!SceneLoader._registeredPlugins[extension]; + }; + /** + * Adds a new plugin to the list of registered plugins + * @param plugin defines the plugin to add + */ + SceneLoader.RegisterPlugin = function (plugin) { + if (typeof plugin.extensions === "string") { + var extension = plugin.extensions; + SceneLoader._registeredPlugins[extension.toLowerCase()] = { + plugin: plugin, + isBinary: false + }; + } + else { + var extensions = plugin.extensions; + Object.keys(extensions).forEach(function (extension) { + SceneLoader._registeredPlugins[extension.toLowerCase()] = { + plugin: plugin, + isBinary: extensions[extension].isBinary + }; + }); + } + }; + /** + * Import meshes into a scene + * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported + * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb) + * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string) + * @param scene the instance of BABYLON.Scene to append to + * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds + * @param onProgress a callback with a progress event for each file being loaded + * @param onError a callback with the scene, a message, and possibly an exception when import fails + * @param pluginExtension the extension used to determine the plugin + * @returns The loaded plugin + */ + SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) { + if (sceneFilename === void 0) { sceneFilename = ""; } + if (scene === void 0) { scene = _Engines_engineStore__WEBPACK_IMPORTED_MODULE_5__["EngineStore"].LastCreatedScene; } + if (onSuccess === void 0) { onSuccess = null; } + if (onProgress === void 0) { onProgress = null; } + if (onError === void 0) { onError = null; } + if (pluginExtension === void 0) { pluginExtension = null; } + if (!scene) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_6__["Logger"].Error("No scene available to import mesh to"); + return null; + } + var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename); + if (!fileInfo) { + return null; + } + var loadingToken = {}; + scene._addPendingData(loadingToken); + var disposeHandler = function () { + scene._removePendingData(loadingToken); + }; + var errorHandler = function (message, exception) { + var errorMessage = "Unable to import meshes from " + fileInfo.url + ": " + message; + if (onError) { + onError(scene, errorMessage, exception); + } + else { + _Misc_logger__WEBPACK_IMPORTED_MODULE_6__["Logger"].Error(errorMessage); + // should the exception be thrown? + } + disposeHandler(); + }; + var progressHandler = onProgress ? function (event) { + try { + onProgress(event); + } + catch (e) { + errorHandler("Error in onProgress callback: " + e, e); + } + } : undefined; + var successHandler = function (meshes, particleSystems, skeletons, animationGroups) { + scene.importedMeshesFiles.push(fileInfo.url); + if (onSuccess) { + try { + onSuccess(meshes, particleSystems, skeletons, animationGroups); + } + catch (e) { + errorHandler("Error in onSuccess callback: " + e, e); + } + } + scene._removePendingData(loadingToken); + }; + return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) { + if (plugin.rewriteRootURL) { + fileInfo.rootUrl = plugin.rewriteRootURL(fileInfo.rootUrl, responseURL); + } + if (plugin.importMesh) { + var syncedPlugin = plugin; + var meshes = new Array(); + var particleSystems = new Array(); + var skeletons = new Array(); + if (!syncedPlugin.importMesh(meshNames, scene, data, fileInfo.rootUrl, meshes, particleSystems, skeletons, errorHandler)) { + return; + } + scene.loadingPluginName = plugin.name; + successHandler(meshes, particleSystems, skeletons, []); + } + else { + var asyncedPlugin = plugin; + asyncedPlugin.importMeshAsync(meshNames, scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (result) { + scene.loadingPluginName = plugin.name; + successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups); + }).catch(function (error) { + errorHandler(error.message, error); + }); + } + }, progressHandler, errorHandler, disposeHandler, pluginExtension); + }; + /** + * Import meshes into a scene + * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported + * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb) + * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string) + * @param scene the instance of BABYLON.Scene to append to + * @param onProgress a callback with a progress event for each file being loaded + * @param pluginExtension the extension used to determine the plugin + * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups + */ + SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) { + if (sceneFilename === void 0) { sceneFilename = ""; } + if (scene === void 0) { scene = _Engines_engineStore__WEBPACK_IMPORTED_MODULE_5__["EngineStore"].LastCreatedScene; } + if (onProgress === void 0) { onProgress = null; } + if (pluginExtension === void 0) { pluginExtension = null; } + return new Promise(function (resolve, reject) { + SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) { + resolve({ + meshes: meshes, + particleSystems: particleSystems, + skeletons: skeletons, + animationGroups: animationGroups + }); + }, onProgress, function (scene, message, exception) { + reject(exception || new Error(message)); + }, pluginExtension); + }); + }; + /** + * Load a scene + * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb) + * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string) + * @param engine is the instance of BABYLON.Engine to use to create the scene + * @param onSuccess a callback with the scene when import succeeds + * @param onProgress a callback with a progress event for each file being loaded + * @param onError a callback with the scene, a message, and possibly an exception when import fails + * @param pluginExtension the extension used to determine the plugin + * @returns The loaded plugin + */ + SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) { + if (sceneFilename === void 0) { sceneFilename = ""; } + if (engine === void 0) { engine = _Engines_engineStore__WEBPACK_IMPORTED_MODULE_5__["EngineStore"].LastCreatedEngine; } + if (onSuccess === void 0) { onSuccess = null; } + if (onProgress === void 0) { onProgress = null; } + if (onError === void 0) { onError = null; } + if (pluginExtension === void 0) { pluginExtension = null; } + if (!engine) { + _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].Error("No engine available"); + return null; + } + return SceneLoader.Append(rootUrl, sceneFilename, new _scene__WEBPACK_IMPORTED_MODULE_3__["Scene"](engine), onSuccess, onProgress, onError, pluginExtension); + }; + /** + * Load a scene + * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb) + * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string) + * @param engine is the instance of BABYLON.Engine to use to create the scene + * @param onProgress a callback with a progress event for each file being loaded + * @param pluginExtension the extension used to determine the plugin + * @returns The loaded scene + */ + SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) { + if (sceneFilename === void 0) { sceneFilename = ""; } + if (engine === void 0) { engine = _Engines_engineStore__WEBPACK_IMPORTED_MODULE_5__["EngineStore"].LastCreatedEngine; } + if (onProgress === void 0) { onProgress = null; } + if (pluginExtension === void 0) { pluginExtension = null; } + return new Promise(function (resolve, reject) { + SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) { + resolve(scene); + }, onProgress, function (scene, message, exception) { + reject(exception || new Error(message)); + }, pluginExtension); + }); + }; + /** + * Append a scene + * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb) + * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string) + * @param scene is the instance of BABYLON.Scene to append to + * @param onSuccess a callback with the scene when import succeeds + * @param onProgress a callback with a progress event for each file being loaded + * @param onError a callback with the scene, a message, and possibly an exception when import fails + * @param pluginExtension the extension used to determine the plugin + * @returns The loaded plugin + */ + SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) { + if (sceneFilename === void 0) { sceneFilename = ""; } + if (scene === void 0) { scene = _Engines_engineStore__WEBPACK_IMPORTED_MODULE_5__["EngineStore"].LastCreatedScene; } + if (onSuccess === void 0) { onSuccess = null; } + if (onProgress === void 0) { onProgress = null; } + if (onError === void 0) { onError = null; } + if (pluginExtension === void 0) { pluginExtension = null; } + if (!scene) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_6__["Logger"].Error("No scene available to append to"); + return null; + } + var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename); + if (!fileInfo) { + return null; + } + if (SceneLoader.ShowLoadingScreen) { + scene.getEngine().displayLoadingUI(); + } + var loadingToken = {}; + scene._addPendingData(loadingToken); + var disposeHandler = function () { + scene._removePendingData(loadingToken); + scene.getEngine().hideLoadingUI(); + }; + var errorHandler = function (message, exception) { + var errorMessage = "Unable to load from " + fileInfo.url + (message ? ": " + message : ""); + if (onError) { + onError(scene, errorMessage, exception); + } + else { + _Misc_logger__WEBPACK_IMPORTED_MODULE_6__["Logger"].Error(errorMessage); + // should the exception be thrown? + } + disposeHandler(); + }; + var progressHandler = onProgress ? function (event) { + try { + onProgress(event); + } + catch (e) { + errorHandler("Error in onProgress callback", e); + } + } : undefined; + var successHandler = function () { + if (onSuccess) { + try { + onSuccess(scene); + } + catch (e) { + errorHandler("Error in onSuccess callback", e); + } + } + scene._removePendingData(loadingToken); + }; + return SceneLoader._loadData(fileInfo, scene, function (plugin, data) { + if (plugin.load) { + var syncedPlugin = plugin; + if (!syncedPlugin.load(scene, data, fileInfo.rootUrl, errorHandler)) { + return; + } + scene.loadingPluginName = plugin.name; + successHandler(); + } + else { + var asyncedPlugin = plugin; + asyncedPlugin.loadAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function () { + scene.loadingPluginName = plugin.name; + successHandler(); + }).catch(function (error) { + errorHandler(error.message, error); + }); + } + if (SceneLoader.ShowLoadingScreen) { + scene.executeWhenReady(function () { + scene.getEngine().hideLoadingUI(); + }); + } + }, progressHandler, errorHandler, disposeHandler, pluginExtension); + }; + /** + * Append a scene + * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb) + * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string) + * @param scene is the instance of BABYLON.Scene to append to + * @param onProgress a callback with a progress event for each file being loaded + * @param pluginExtension the extension used to determine the plugin + * @returns The given scene + */ + SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) { + if (sceneFilename === void 0) { sceneFilename = ""; } + if (scene === void 0) { scene = _Engines_engineStore__WEBPACK_IMPORTED_MODULE_5__["EngineStore"].LastCreatedScene; } + if (onProgress === void 0) { onProgress = null; } + if (pluginExtension === void 0) { pluginExtension = null; } + return new Promise(function (resolve, reject) { + SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) { + resolve(scene); + }, onProgress, function (scene, message, exception) { + reject(exception || new Error(message)); + }, pluginExtension); + }); + }; + /** + * Load a scene into an asset container + * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb) + * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string) + * @param scene is the instance of BABYLON.Scene to append to (default: last created scene) + * @param onSuccess a callback with the scene when import succeeds + * @param onProgress a callback with a progress event for each file being loaded + * @param onError a callback with the scene, a message, and possibly an exception when import fails + * @param pluginExtension the extension used to determine the plugin + * @returns The loaded plugin + */ + SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) { + if (sceneFilename === void 0) { sceneFilename = ""; } + if (scene === void 0) { scene = _Engines_engineStore__WEBPACK_IMPORTED_MODULE_5__["EngineStore"].LastCreatedScene; } + if (onSuccess === void 0) { onSuccess = null; } + if (onProgress === void 0) { onProgress = null; } + if (onError === void 0) { onError = null; } + if (pluginExtension === void 0) { pluginExtension = null; } + if (!scene) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_6__["Logger"].Error("No scene available to load asset container to"); + return null; + } + var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename); + if (!fileInfo) { + return null; + } + var loadingToken = {}; + scene._addPendingData(loadingToken); + var disposeHandler = function () { + scene._removePendingData(loadingToken); + }; + var errorHandler = function (message, exception) { + var errorMessage = "Unable to load assets from " + fileInfo.url + (message ? ": " + message : ""); + if (onError) { + onError(scene, errorMessage, exception); + } + else { + _Misc_logger__WEBPACK_IMPORTED_MODULE_6__["Logger"].Error(errorMessage); + // should the exception be thrown? + } + disposeHandler(); + }; + var progressHandler = onProgress ? function (event) { + try { + onProgress(event); + } + catch (e) { + errorHandler("Error in onProgress callback", e); + } + } : undefined; + var successHandler = function (assets) { + if (onSuccess) { + try { + onSuccess(assets); + } + catch (e) { + errorHandler("Error in onSuccess callback", e); + } + } + scene._removePendingData(loadingToken); + }; + return SceneLoader._loadData(fileInfo, scene, function (plugin, data) { + if (plugin.loadAssetContainer) { + var syncedPlugin = plugin; + var assetContainer = syncedPlugin.loadAssetContainer(scene, data, fileInfo.rootUrl, errorHandler); + if (!assetContainer) { + return; + } + scene.loadingPluginName = plugin.name; + successHandler(assetContainer); + } + else if (plugin.loadAssetContainerAsync) { + var asyncedPlugin = plugin; + asyncedPlugin.loadAssetContainerAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (assetContainer) { + scene.loadingPluginName = plugin.name; + successHandler(assetContainer); + }).catch(function (error) { + errorHandler(error.message, error); + }); + } + else { + errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method."); + } + if (SceneLoader.ShowLoadingScreen) { + scene.executeWhenReady(function () { + scene.getEngine().hideLoadingUI(); + }); + } + }, progressHandler, errorHandler, disposeHandler, pluginExtension); + }; + /** + * Load a scene into an asset container + * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb) + * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string) + * @param scene is the instance of Scene to append to + * @param onProgress a callback with a progress event for each file being loaded + * @param pluginExtension the extension used to determine the plugin + * @returns The loaded asset container + */ + SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) { + if (sceneFilename === void 0) { sceneFilename = ""; } + if (scene === void 0) { scene = _Engines_engineStore__WEBPACK_IMPORTED_MODULE_5__["EngineStore"].LastCreatedScene; } + if (onProgress === void 0) { onProgress = null; } + if (pluginExtension === void 0) { pluginExtension = null; } + return new Promise(function (resolve, reject) { + SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) { + resolve(assetContainer); + }, onProgress, function (scene, message, exception) { + reject(exception || new Error(message)); + }, pluginExtension); + }); + }; + /** + * No logging while loading + */ + SceneLoader.NO_LOGGING = _Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].SCENELOADER_NO_LOGGING; + /** + * Minimal logging while loading + */ + SceneLoader.MINIMAL_LOGGING = _Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].SCENELOADER_MINIMAL_LOGGING; + /** + * Summary logging while loading + */ + SceneLoader.SUMMARY_LOGGING = _Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].SCENELOADER_SUMMARY_LOGGING; + /** + * Detailled logging while loading + */ + SceneLoader.DETAILED_LOGGING = _Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].SCENELOADER_DETAILED_LOGGING; + // Members + /** + * Event raised when a plugin is used to load a scene + */ + SceneLoader.OnPluginActivatedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + SceneLoader._registeredPlugins = {}; + return SceneLoader; +}()); + + + +/***/ }), + +/***/ "./Loading/sceneLoaderFlags.ts": +/*!*************************************!*\ + !*** ./Loading/sceneLoaderFlags.ts ***! + \*************************************/ +/*! exports provided: SceneLoaderFlags */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SceneLoaderFlags", function() { return SceneLoaderFlags; }); +/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts"); + +/** + * Class used to represent data loading progression + */ +var SceneLoaderFlags = /** @class */ (function () { + function SceneLoaderFlags() { + } + Object.defineProperty(SceneLoaderFlags, "ForceFullSceneLoadingForIncremental", { + /** + * Gets or sets a boolean indicating if entire scene must be loaded even if scene contains incremental data + */ + get: function () { + return SceneLoaderFlags._ForceFullSceneLoadingForIncremental; + }, + set: function (value) { + SceneLoaderFlags._ForceFullSceneLoadingForIncremental = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SceneLoaderFlags, "ShowLoadingScreen", { + /** + * Gets or sets a boolean indicating if loading screen must be displayed while loading a scene + */ + get: function () { + return SceneLoaderFlags._ShowLoadingScreen; + }, + set: function (value) { + SceneLoaderFlags._ShowLoadingScreen = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SceneLoaderFlags, "loggingLevel", { + /** + * Defines the current logging level (while loading the scene) + * @ignorenaming + */ + get: function () { + return SceneLoaderFlags._loggingLevel; + }, + set: function (value) { + SceneLoaderFlags._loggingLevel = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(SceneLoaderFlags, "CleanBoneMatrixWeights", { + /** + * Gets or set a boolean indicating if matrix weights must be cleaned upon loading + */ + get: function () { + return SceneLoaderFlags._CleanBoneMatrixWeights; + }, + set: function (value) { + SceneLoaderFlags._CleanBoneMatrixWeights = value; + }, + enumerable: true, + configurable: true + }); + // Flags + SceneLoaderFlags._ForceFullSceneLoadingForIncremental = false; + SceneLoaderFlags._ShowLoadingScreen = true; + SceneLoaderFlags._CleanBoneMatrixWeights = false; + SceneLoaderFlags._loggingLevel = _Engines_constants__WEBPACK_IMPORTED_MODULE_0__["Constants"].SCENELOADER_NO_LOGGING; + return SceneLoaderFlags; +}()); + + + +/***/ }), + +/***/ "./Materials/Background/backgroundMaterial.ts": +/*!****************************************************!*\ + !*** ./Materials/Background/backgroundMaterial.ts ***! + \****************************************************/ +/*! exports provided: BackgroundMaterial */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BackgroundMaterial", function() { return BackgroundMaterial; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _Misc_smartArray__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/smartArray */ "./Misc/smartArray.ts"); +/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Misc/logger */ "./Misc/logger.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Meshes_buffer__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Meshes/buffer */ "./Meshes/buffer.ts"); +/* harmony import */ var _Materials_effect__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../Materials/effect */ "./Materials/effect.ts"); +/* harmony import */ var _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../Materials/materialHelper */ "./Materials/materialHelper.ts"); +/* harmony import */ var _Materials_materialDefines__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../Materials/materialDefines */ "./Materials/materialDefines.ts"); +/* harmony import */ var _Materials_pushMaterial__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../../Materials/pushMaterial */ "./Materials/pushMaterial.ts"); +/* harmony import */ var _Materials_imageProcessingConfiguration__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../../Materials/imageProcessingConfiguration */ "./Materials/imageProcessingConfiguration.ts"); +/* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../../Materials/Textures/texture */ "./Materials/Textures/texture.ts"); +/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../../Engines/constants */ "./Engines/constants.ts"); +/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../../Misc/typeStore */ "./Misc/typeStore.ts"); +/* harmony import */ var _materialFlags__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../materialFlags */ "./Materials/materialFlags.ts"); +/* harmony import */ var _Shaders_background_fragment__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../../Shaders/background.fragment */ "./Shaders/background.fragment.ts"); +/* harmony import */ var _Shaders_background_vertex__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../../Shaders/background.vertex */ "./Shaders/background.vertex.ts"); + + + + + + + + + + + + + + + + + +/** + * Background material defines definition. + * @hidden Mainly internal Use + */ +var BackgroundMaterialDefines = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](BackgroundMaterialDefines, _super); + /** + * Constructor of the defines. + */ + function BackgroundMaterialDefines() { + var _this = _super.call(this) || this; + /** + * True if the diffuse texture is in use. + */ + _this.DIFFUSE = false; + /** + * The direct UV channel to use. + */ + _this.DIFFUSEDIRECTUV = 0; + /** + * True if the diffuse texture is in gamma space. + */ + _this.GAMMADIFFUSE = false; + /** + * True if the diffuse texture has opacity in the alpha channel. + */ + _this.DIFFUSEHASALPHA = false; + /** + * True if you want the material to fade to transparent at grazing angle. + */ + _this.OPACITYFRESNEL = false; + /** + * True if an extra blur needs to be added in the reflection. + */ + _this.REFLECTIONBLUR = false; + /** + * True if you want the material to fade to reflection at grazing angle. + */ + _this.REFLECTIONFRESNEL = false; + /** + * True if you want the material to falloff as far as you move away from the scene center. + */ + _this.REFLECTIONFALLOFF = false; + /** + * False if the current Webgl implementation does not support the texture lod extension. + */ + _this.TEXTURELODSUPPORT = false; + /** + * True to ensure the data are premultiplied. + */ + _this.PREMULTIPLYALPHA = false; + /** + * True if the texture contains cooked RGB values and not gray scaled multipliers. + */ + _this.USERGBCOLOR = false; + /** + * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color + * stays aligned with the desired configuration. + */ + _this.USEHIGHLIGHTANDSHADOWCOLORS = false; + /** + * True to add noise in order to reduce the banding effect. + */ + _this.NOISE = false; + /** + * is the reflection texture in BGR color scheme? + * Mainly used to solve a bug in ios10 video tag + */ + _this.REFLECTIONBGR = false; + _this.IMAGEPROCESSING = false; + _this.VIGNETTE = false; + _this.VIGNETTEBLENDMODEMULTIPLY = false; + _this.VIGNETTEBLENDMODEOPAQUE = false; + _this.TONEMAPPING = false; + _this.TONEMAPPING_ACES = false; + _this.CONTRAST = false; + _this.COLORCURVES = false; + _this.COLORGRADING = false; + _this.COLORGRADING3D = false; + _this.SAMPLER3DGREENDEPTH = false; + _this.SAMPLER3DBGRMAP = false; + _this.IMAGEPROCESSINGPOSTPROCESS = false; + _this.EXPOSURE = false; + _this.MULTIVIEW = false; + // Reflection. + _this.REFLECTION = false; + _this.REFLECTIONMAP_3D = false; + _this.REFLECTIONMAP_SPHERICAL = false; + _this.REFLECTIONMAP_PLANAR = false; + _this.REFLECTIONMAP_CUBIC = false; + _this.REFLECTIONMAP_PROJECTION = false; + _this.REFLECTIONMAP_SKYBOX = false; + _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false; + _this.REFLECTIONMAP_EXPLICIT = false; + _this.REFLECTIONMAP_EQUIRECTANGULAR = false; + _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false; + _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false; + _this.INVERTCUBICMAP = false; + _this.REFLECTIONMAP_OPPOSITEZ = false; + _this.LODINREFLECTIONALPHA = false; + _this.GAMMAREFLECTION = false; + _this.RGBDREFLECTION = false; + _this.EQUIRECTANGULAR_RELFECTION_FOV = false; + // Default BJS. + _this.MAINUV1 = false; + _this.MAINUV2 = false; + _this.UV1 = false; + _this.UV2 = false; + _this.CLIPPLANE = false; + _this.CLIPPLANE2 = false; + _this.CLIPPLANE3 = false; + _this.CLIPPLANE4 = false; + _this.POINTSIZE = false; + _this.FOG = false; + _this.NORMAL = false; + _this.NUM_BONE_INFLUENCERS = 0; + _this.BonesPerMesh = 0; + _this.INSTANCES = false; + _this.SHADOWFLOAT = false; + _this.rebuild(); + return _this; + } + return BackgroundMaterialDefines; +}(_Materials_materialDefines__WEBPACK_IMPORTED_MODULE_8__["MaterialDefines"])); +/** + * Background material used to create an efficient environement around your scene. + */ +var BackgroundMaterial = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](BackgroundMaterial, _super); + /** + * Instantiates a Background Material in the given scene + * @param name The friendly name of the material + * @param scene The scene to add the material to + */ + function BackgroundMaterial(name, scene) { + var _this = _super.call(this, name, scene) || this; + /** + * Key light Color (multiply against the environement texture) + */ + _this.primaryColor = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Color3"].White(); + _this._primaryColorShadowLevel = 0; + _this._primaryColorHighlightLevel = 0; + /** + * Reflection Texture used in the material. + * Should be author in a specific way for the best result (refer to the documentation). + */ + _this.reflectionTexture = null; + /** + * Reflection Texture level of blur. + * + * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the + * texture twice. + */ + _this.reflectionBlur = 0; + /** + * Diffuse Texture used in the material. + * Should be author in a specific way for the best result (refer to the documentation). + */ + _this.diffuseTexture = null; + _this._shadowLights = null; + /** + * Specify the list of lights casting shadow on the material. + * All scene shadow lights will be included if null. + */ + _this.shadowLights = null; + /** + * Helps adjusting the shadow to a softer level if required. + * 0 means black shadows and 1 means no shadows. + */ + _this.shadowLevel = 0; + /** + * In case of opacity Fresnel or reflection falloff, this is use as a scene center. + * It is usually zero but might be interesting to modify according to your setup. + */ + _this.sceneCenter = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"].Zero(); + /** + * This helps specifying that the material is falling off to the sky box at grazing angle. + * This helps ensuring a nice transition when the camera goes under the ground. + */ + _this.opacityFresnel = true; + /** + * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle. + * This helps adding a mirror texture on the ground. + */ + _this.reflectionFresnel = false; + /** + * This helps specifying the falloff radius off the reflection texture from the sceneCenter. + * This helps adding a nice falloff effect to the reflection if used as a mirror for instance. + */ + _this.reflectionFalloffDistance = 0.0; + /** + * This specifies the weight of the reflection against the background in case of reflection Fresnel. + */ + _this.reflectionAmount = 1.0; + /** + * This specifies the weight of the reflection at grazing angle. + */ + _this.reflectionReflectance0 = 0.05; + /** + * This specifies the weight of the reflection at a perpendicular point of view. + */ + _this.reflectionReflectance90 = 0.5; + /** + * Helps to directly use the maps channels instead of their level. + */ + _this.useRGBColor = true; + /** + * This helps reducing the banding effect that could occur on the background. + */ + _this.enableNoise = false; + _this._fovMultiplier = 1.0; + /** + * Enable the FOV adjustment feature controlled by fovMultiplier. + */ + _this.useEquirectangularFOV = false; + _this._maxSimultaneousLights = 4; + /** + * Number of Simultaneous lights allowed on the material. + */ + _this.maxSimultaneousLights = 4; + /** + * Keep track of the image processing observer to allow dispose and replace. + */ + _this._imageProcessingObserver = null; + /** + * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB. + * Setting this flag to true (not done automatically!) will convert it back to RGB. + */ + _this.switchToBGR = false; + // Temp values kept as cache in the material. + _this._renderTargets = new _Misc_smartArray__WEBPACK_IMPORTED_MODULE_2__["SmartArray"](16); + _this._reflectionControls = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector4"].Zero(); + _this._white = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Color3"].White(); + _this._primaryShadowColor = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Color3"].Black(); + _this._primaryHighlightColor = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Color3"].Black(); + // Setup the default processing configuration to the scene. + _this._attachImageProcessingConfiguration(null); + _this.getRenderTargetTextures = function () { + _this._renderTargets.reset(); + if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) { + _this._renderTargets.push(_this._diffuseTexture); + } + if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) { + _this._renderTargets.push(_this._reflectionTexture); + } + return _this._renderTargets; + }; + return _this; + } + Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", { + /** + * Experimental Internal Use Only. + * + * Key light Color in "perceptual value" meaning the color you would like to see on screen. + * This acts as a helper to set the primary color to a more "human friendly" value. + * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the + * output color as close as possible from the chosen value. + * (This does not account for contrast color grading and color curves as they are considered post effect and not directly + * part of lighting setup.) + */ + get: function () { + return this.__perceptualColor; + }, + set: function (value) { + this.__perceptualColor = value; + this._computePrimaryColorFromPerceptualColor(); + this._markAllSubMeshesAsLightsDirty(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", { + /** + * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors. + * The color opposite to the primary color is used at the level chosen to define what the black area would look. + */ + get: function () { + return this._primaryColorShadowLevel; + }, + set: function (value) { + this._primaryColorShadowLevel = value; + this._computePrimaryColors(); + this._markAllSubMeshesAsLightsDirty(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", { + /** + * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors. + * The primary color is used at the level chosen to define what the white area would look. + */ + get: function () { + return this._primaryColorHighlightLevel; + }, + set: function (value) { + this._primaryColorHighlightLevel = value; + this._computePrimaryColors(); + this._markAllSubMeshesAsLightsDirty(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", { + /** + * Sets the reflection reflectance fresnel values according to the default standard + * empirically know to work well :-) + */ + set: function (value) { + var reflectionWeight = value; + if (reflectionWeight < 0.5) { + reflectionWeight = reflectionWeight * 2.0; + this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight; + this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight; + } + else { + reflectionWeight = reflectionWeight * 2.0 - 1.0; + this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight; + this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", { + /** + * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out". + * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov. + * Recommended to be keep at 1.0 except for special cases. + */ + get: function () { + return this._fovMultiplier; + }, + set: function (value) { + if (isNaN(value)) { + value = 1.0; + } + this._fovMultiplier = Math.max(0.0, Math.min(2.0, value)); + }, + enumerable: true, + configurable: true + }); + /** + * Attaches a new image processing configuration to the PBR Material. + * @param configuration (if null the scene configuration will be use) + */ + BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) { + var _this = this; + if (configuration === this._imageProcessingConfiguration) { + return; + } + // Detaches observer. + if (this._imageProcessingConfiguration && this._imageProcessingObserver) { + this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver); + } + // Pick the scene configuration if needed. + if (!configuration) { + this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration; + } + else { + this._imageProcessingConfiguration = configuration; + } + // Attaches observer. + if (this._imageProcessingConfiguration) { + this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function () { + _this._computePrimaryColorFromPerceptualColor(); + _this._markAllSubMeshesAsImageProcessingDirty(); + }); + } + }; + Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", { + /** + * Gets the image processing configuration used either in this material. + */ + get: function () { + return this._imageProcessingConfiguration; + }, + /** + * Sets the Default image processing configuration used either in the this material. + * + * If sets to null, the scene one is in use. + */ + set: function (value) { + this._attachImageProcessingConfiguration(value); + // Ensure the effect will be rebuilt. + this._markAllSubMeshesAsTexturesDirty(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", { + /** + * Gets wether the color curves effect is enabled. + */ + get: function () { + return this.imageProcessingConfiguration.colorCurvesEnabled; + }, + /** + * Sets wether the color curves effect is enabled. + */ + set: function (value) { + this.imageProcessingConfiguration.colorCurvesEnabled = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", { + /** + * Gets wether the color grading effect is enabled. + */ + get: function () { + return this.imageProcessingConfiguration.colorGradingEnabled; + }, + /** + * Gets wether the color grading effect is enabled. + */ + set: function (value) { + this.imageProcessingConfiguration.colorGradingEnabled = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", { + /** + * Gets wether tonemapping is enabled or not. + */ + get: function () { + return this._imageProcessingConfiguration.toneMappingEnabled; + }, + /** + * Sets wether tonemapping is enabled or not + */ + set: function (value) { + this._imageProcessingConfiguration.toneMappingEnabled = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", { + /** + * The camera exposure used on this material. + * This property is here and not in the camera to allow controlling exposure without full screen post process. + * This corresponds to a photographic exposure. + */ + get: function () { + return this._imageProcessingConfiguration.exposure; + }, + /** + * The camera exposure used on this material. + * This property is here and not in the camera to allow controlling exposure without full screen post process. + * This corresponds to a photographic exposure. + */ + set: function (value) { + this._imageProcessingConfiguration.exposure = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", { + /** + * Gets The camera contrast used on this material. + */ + get: function () { + return this._imageProcessingConfiguration.contrast; + }, + /** + * Sets The camera contrast used on this material. + */ + set: function (value) { + this._imageProcessingConfiguration.contrast = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", { + /** + * Gets the Color Grading 2D Lookup Texture. + */ + get: function () { + return this._imageProcessingConfiguration.colorGradingTexture; + }, + /** + * Sets the Color Grading 2D Lookup Texture. + */ + set: function (value) { + this.imageProcessingConfiguration.colorGradingTexture = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", { + /** + * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT). + * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects. + * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image; + * corresponding to low luminance, medium luminance, and high luminance areas respectively. + */ + get: function () { + return this.imageProcessingConfiguration.colorCurves; + }, + /** + * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT). + * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects. + * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image; + * corresponding to low luminance, medium luminance, and high luminance areas respectively. + */ + set: function (value) { + this.imageProcessingConfiguration.colorCurves = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(BackgroundMaterial.prototype, "hasRenderTargetTextures", { + /** + * Gets a boolean indicating that current material needs to register RTT + */ + get: function () { + if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) { + return true; + } + if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) { + return true; + } + return false; + }, + enumerable: true, + configurable: true + }); + /** + * The entire material has been created in order to prevent overdraw. + * @returns false + */ + BackgroundMaterial.prototype.needAlphaTesting = function () { + return true; + }; + /** + * The entire material has been created in order to prevent overdraw. + * @returns true if blending is enable + */ + BackgroundMaterial.prototype.needAlphaBlending = function () { + return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha)); + }; + /** + * Checks wether the material is ready to be rendered for a given mesh. + * @param mesh The mesh to render + * @param subMesh The submesh to check against + * @param useInstances Specify wether or not the material is used with instances + * @returns true if all the dependencies are ready (Textures, Effects...) + */ + BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) { + var _this = this; + if (useInstances === void 0) { useInstances = false; } + if (subMesh.effect && this.isFrozen) { + if (this._wasPreviouslyReady) { + return true; + } + } + if (!subMesh._materialDefines) { + subMesh._materialDefines = new BackgroundMaterialDefines(); + } + var scene = this.getScene(); + var defines = subMesh._materialDefines; + if (!this.checkReadyOnEveryCall && subMesh.effect) { + if (defines._renderId === scene.getRenderId()) { + return true; + } + } + var engine = scene.getEngine(); + // Lights + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_7__["MaterialHelper"].PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights); + defines._needNormals = true; + // Multiview + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_7__["MaterialHelper"].PrepareDefinesForMultiview(scene, defines); + // Textures + if (defines._areTexturesDirty) { + defines._needUVs = false; + if (scene.texturesEnabled) { + if (scene.getEngine().getCaps().textureLOD) { + defines.TEXTURELODSUPPORT = true; + } + if (this._diffuseTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_14__["MaterialFlags"].DiffuseTextureEnabled) { + if (!this._diffuseTexture.isReadyOrNotBlocking()) { + return false; + } + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_7__["MaterialHelper"].PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE"); + defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha; + defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace; + defines.OPACITYFRESNEL = this._opacityFresnel; + } + else { + defines.DIFFUSE = false; + defines.DIFFUSEHASALPHA = false; + defines.GAMMADIFFUSE = false; + defines.OPACITYFRESNEL = false; + } + var reflectionTexture = this._reflectionTexture; + if (reflectionTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_14__["MaterialFlags"].ReflectionTextureEnabled) { + if (!reflectionTexture.isReadyOrNotBlocking()) { + return false; + } + defines.REFLECTION = true; + defines.GAMMAREFLECTION = reflectionTexture.gammaSpace; + defines.RGBDREFLECTION = reflectionTexture.isRGBD; + defines.REFLECTIONBLUR = this._reflectionBlur > 0; + defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ; + defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha; + defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV; + defines.REFLECTIONBGR = this.switchToBGR; + if (reflectionTexture.coordinatesMode === _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_11__["Texture"].INVCUBIC_MODE) { + defines.INVERTCUBICMAP = true; + } + defines.REFLECTIONMAP_3D = reflectionTexture.isCube; + switch (reflectionTexture.coordinatesMode) { + case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_11__["Texture"].EXPLICIT_MODE: + defines.REFLECTIONMAP_EXPLICIT = true; + break; + case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_11__["Texture"].PLANAR_MODE: + defines.REFLECTIONMAP_PLANAR = true; + break; + case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_11__["Texture"].PROJECTION_MODE: + defines.REFLECTIONMAP_PROJECTION = true; + break; + case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_11__["Texture"].SKYBOX_MODE: + defines.REFLECTIONMAP_SKYBOX = true; + defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity(); + break; + case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_11__["Texture"].SPHERICAL_MODE: + defines.REFLECTIONMAP_SPHERICAL = true; + break; + case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_11__["Texture"].EQUIRECTANGULAR_MODE: + defines.REFLECTIONMAP_EQUIRECTANGULAR = true; + break; + case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_11__["Texture"].FIXED_EQUIRECTANGULAR_MODE: + defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true; + break; + case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_11__["Texture"].FIXED_EQUIRECTANGULAR_MIRRORED_MODE: + defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true; + break; + case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_11__["Texture"].CUBIC_MODE: + case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_11__["Texture"].INVCUBIC_MODE: + default: + defines.REFLECTIONMAP_CUBIC = true; + break; + } + if (this.reflectionFresnel) { + defines.REFLECTIONFRESNEL = true; + defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0; + this._reflectionControls.x = this.reflectionAmount; + this._reflectionControls.y = this.reflectionReflectance0; + this._reflectionControls.z = this.reflectionReflectance90; + this._reflectionControls.w = 1 / this.reflectionFalloffDistance; + } + else { + defines.REFLECTIONFRESNEL = false; + defines.REFLECTIONFALLOFF = false; + } + } + else { + defines.REFLECTION = false; + defines.REFLECTIONFRESNEL = false; + defines.REFLECTIONFALLOFF = false; + defines.REFLECTIONBLUR = false; + defines.REFLECTIONMAP_3D = false; + defines.REFLECTIONMAP_SPHERICAL = false; + defines.REFLECTIONMAP_PLANAR = false; + defines.REFLECTIONMAP_CUBIC = false; + defines.REFLECTIONMAP_PROJECTION = false; + defines.REFLECTIONMAP_SKYBOX = false; + defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false; + defines.REFLECTIONMAP_EXPLICIT = false; + defines.REFLECTIONMAP_EQUIRECTANGULAR = false; + defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false; + defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false; + defines.INVERTCUBICMAP = false; + defines.REFLECTIONMAP_OPPOSITEZ = false; + defines.LODINREFLECTIONALPHA = false; + defines.GAMMAREFLECTION = false; + defines.RGBDREFLECTION = false; + } + } + defines.PREMULTIPLYALPHA = (this.alphaMode === _Engines_constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].ALPHA_PREMULTIPLIED || this.alphaMode === _Engines_constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].ALPHA_PREMULTIPLIED_PORTERDUFF); + defines.USERGBCOLOR = this._useRGBColor; + defines.NOISE = this._enableNoise; + } + if (defines._areLightsDirty) { + defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0); + } + if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) { + if (!this._imageProcessingConfiguration.isReady()) { + return false; + } + this._imageProcessingConfiguration.prepareDefines(defines); + } + // Misc. + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_7__["MaterialHelper"].PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines); + // Values that need to be evaluated on every frame + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_7__["MaterialHelper"].PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances); + // Attribs + if (_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_7__["MaterialHelper"].PrepareDefinesForAttributes(mesh, defines, false, true, false)) { + if (mesh) { + if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_5__["VertexBuffer"].NormalKind)) { + mesh.createNormals(true); + _Misc_logger__WEBPACK_IMPORTED_MODULE_3__["Logger"].Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name); + } + } + } + // Get correct effect + if (defines.isDirty) { + defines.markAsProcessed(); + scene.resetCachedMaterial(); + // Fallbacks + var fallbacks = new _Materials_effect__WEBPACK_IMPORTED_MODULE_6__["EffectFallbacks"](); + if (defines.FOG) { + fallbacks.addFallback(0, "FOG"); + } + if (defines.POINTSIZE) { + fallbacks.addFallback(1, "POINTSIZE"); + } + if (defines.MULTIVIEW) { + fallbacks.addFallback(0, "MULTIVIEW"); + } + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_7__["MaterialHelper"].HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights); + if (defines.NUM_BONE_INFLUENCERS > 0) { + fallbacks.addCPUSkinningFallback(0, mesh); + } + //Attributes + var attribs = [_Meshes_buffer__WEBPACK_IMPORTED_MODULE_5__["VertexBuffer"].PositionKind]; + if (defines.NORMAL) { + attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_5__["VertexBuffer"].NormalKind); + } + if (defines.UV1) { + attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_5__["VertexBuffer"].UVKind); + } + if (defines.UV2) { + attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_5__["VertexBuffer"].UV2Kind); + } + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_7__["MaterialHelper"].PrepareAttributesForBones(attribs, mesh, defines, fallbacks); + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_7__["MaterialHelper"].PrepareAttributesForInstances(attribs, defines); + var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", + "vFogInfos", "vFogColor", "pointSize", + "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones", + "vPrimaryColor", "vPrimaryColorShadow", + "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier", + "shadowLevel", "alpha", + "vBackgroundCenter", "vReflectionControl", + "vDiffuseInfos", "diffuseMatrix", + ]; + var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"]; + var uniformBuffers = ["Material", "Scene"]; + if (_Materials_imageProcessingConfiguration__WEBPACK_IMPORTED_MODULE_10__["ImageProcessingConfiguration"]) { + _Materials_imageProcessingConfiguration__WEBPACK_IMPORTED_MODULE_10__["ImageProcessingConfiguration"].PrepareUniforms(uniforms, defines); + _Materials_imageProcessingConfiguration__WEBPACK_IMPORTED_MODULE_10__["ImageProcessingConfiguration"].PrepareSamplers(samplers, defines); + } + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_7__["MaterialHelper"].PrepareUniformsAndSamplersList({ + uniformsNames: uniforms, + uniformBuffersNames: uniformBuffers, + samplers: samplers, + defines: defines, + maxSimultaneousLights: this._maxSimultaneousLights + }); + var onCompiled = function (effect) { + if (_this.onCompiled) { + _this.onCompiled(effect); + } + _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer()); + }; + var join = defines.toString(); + subMesh.setEffect(scene.getEngine().createEffect("background", { + attributes: attribs, + uniformsNames: uniforms, + uniformBuffersNames: uniformBuffers, + samplers: samplers, + defines: join, + fallbacks: fallbacks, + onCompiled: onCompiled, + onError: this.onError, + indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights } + }, engine), defines); + this.buildUniformLayout(); + } + if (!subMesh.effect || !subMesh.effect.isReady()) { + return false; + } + defines._renderId = scene.getRenderId(); + this._wasPreviouslyReady = true; + return true; + }; + /** + * Compute the primary color according to the chosen perceptual color. + */ + BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () { + if (!this.__perceptualColor) { + return; + } + this._primaryColor.copyFrom(this.__perceptualColor); + // Revert gamma space. + this._primaryColor.toLinearSpaceToRef(this._primaryColor); + // Revert image processing configuration. + if (this._imageProcessingConfiguration) { + // Revert Exposure. + this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor); + } + this._computePrimaryColors(); + }; + /** + * Compute the highlights and shadow colors according to their chosen levels. + */ + BackgroundMaterial.prototype._computePrimaryColors = function () { + if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) { + return; + } + // Find the highlight color based on the configuration. + this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor); + this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor); + // Find the shadow color based on the configuration. + this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor); + this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor); + this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor); + }; + /** + * Build the uniform buffer used in the material. + */ + BackgroundMaterial.prototype.buildUniformLayout = function () { + // Order is important ! + this._uniformBuffer.addUniform("vPrimaryColor", 4); + this._uniformBuffer.addUniform("vPrimaryColorShadow", 4); + this._uniformBuffer.addUniform("vDiffuseInfos", 2); + this._uniformBuffer.addUniform("vReflectionInfos", 2); + this._uniformBuffer.addUniform("diffuseMatrix", 16); + this._uniformBuffer.addUniform("reflectionMatrix", 16); + this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3); + this._uniformBuffer.addUniform("fFovMultiplier", 1); + this._uniformBuffer.addUniform("pointSize", 1); + this._uniformBuffer.addUniform("shadowLevel", 1); + this._uniformBuffer.addUniform("alpha", 1); + this._uniformBuffer.addUniform("vBackgroundCenter", 3); + this._uniformBuffer.addUniform("vReflectionControl", 4); + this._uniformBuffer.create(); + }; + /** + * Unbind the material. + */ + BackgroundMaterial.prototype.unbind = function () { + if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) { + this._uniformBuffer.setTexture("diffuseSampler", null); + } + if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) { + this._uniformBuffer.setTexture("reflectionSampler", null); + } + _super.prototype.unbind.call(this); + }; + /** + * Bind only the world matrix to the material. + * @param world The world matrix to bind. + */ + BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) { + this._activeEffect.setMatrix("world", world); + }; + /** + * Bind the material for a dedicated submeh (every used meshes will be considered opaque). + * @param world The world matrix to bind. + * @param subMesh The submesh to bind for. + */ + BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) { + var scene = this.getScene(); + var defines = subMesh._materialDefines; + if (!defines) { + return; + } + var effect = subMesh.effect; + if (!effect) { + return; + } + this._activeEffect = effect; + // Matrices + this.bindOnlyWorldMatrix(world); + // Bones + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_7__["MaterialHelper"].BindBonesParameters(mesh, this._activeEffect); + var mustRebind = this._mustRebind(scene, effect, mesh.visibility); + if (mustRebind) { + this._uniformBuffer.bindToEffect(effect, "Material"); + this.bindViewProjection(effect); + var reflectionTexture = this._reflectionTexture; + if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) { + // Texture uniforms + if (scene.texturesEnabled) { + if (this._diffuseTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_14__["MaterialFlags"].DiffuseTextureEnabled) { + this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level); + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_7__["MaterialHelper"].BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse"); + } + if (reflectionTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_14__["MaterialFlags"].ReflectionTextureEnabled) { + this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix()); + this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur); + this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset); + } + } + if (this.shadowLevel > 0) { + this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel); + } + this._uniformBuffer.updateFloat("alpha", this.alpha); + // Point size + if (this.pointsCloud) { + this._uniformBuffer.updateFloat("pointSize", this.pointSize); + } + if (defines.USEHIGHLIGHTANDSHADOWCOLORS) { + this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0); + this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0); + } + else { + this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0); + } + } + this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier); + // Textures + if (scene.texturesEnabled) { + if (this._diffuseTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_14__["MaterialFlags"].DiffuseTextureEnabled) { + this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture); + } + if (reflectionTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_14__["MaterialFlags"].ReflectionTextureEnabled) { + if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) { + this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture); + } + else if (!defines.REFLECTIONBLUR) { + this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture); + } + else { + this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture); + this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture); + this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture); + } + if (defines.REFLECTIONFRESNEL) { + this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z); + this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w); + } + } + } + // Clip plane + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_7__["MaterialHelper"].BindClipPlane(this._activeEffect, scene); + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_7__["MaterialHelper"].BindEyePosition(effect, scene); + } + if (mustRebind || !this.isFrozen) { + if (scene.lightsEnabled) { + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_7__["MaterialHelper"].BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false); + } + // View + this.bindView(effect); + // Fog + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_7__["MaterialHelper"].BindFogParameters(scene, mesh, this._activeEffect, true); + // image processing + if (this._imageProcessingConfiguration) { + this._imageProcessingConfiguration.bind(this._activeEffect); + } + } + this._uniformBuffer.update(); + this._afterBind(mesh, this._activeEffect); + }; + /** + * Dispose the material. + * @param forceDisposeEffect Force disposal of the associated effect. + * @param forceDisposeTextures Force disposal of the associated textures. + */ + BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) { + if (forceDisposeEffect === void 0) { forceDisposeEffect = false; } + if (forceDisposeTextures === void 0) { forceDisposeTextures = false; } + if (forceDisposeTextures) { + if (this.diffuseTexture) { + this.diffuseTexture.dispose(); + } + if (this.reflectionTexture) { + this.reflectionTexture.dispose(); + } + } + this._renderTargets.dispose(); + if (this._imageProcessingConfiguration && this._imageProcessingObserver) { + this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver); + } + _super.prototype.dispose.call(this, forceDisposeEffect); + }; + /** + * Clones the material. + * @param name The cloned name. + * @returns The cloned material. + */ + BackgroundMaterial.prototype.clone = function (name) { + var _this = this; + return _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this); + }; + /** + * Serializes the current material to its JSON representation. + * @returns The JSON representation. + */ + BackgroundMaterial.prototype.serialize = function () { + var serializationObject = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(this); + serializationObject.customType = "BABYLON.BackgroundMaterial"; + return serializationObject; + }; + /** + * Gets the class name of the material + * @returns "BackgroundMaterial" + */ + BackgroundMaterial.prototype.getClassName = function () { + return "BackgroundMaterial"; + }; + /** + * Parse a JSON input to create back a background material. + * @param source The JSON data to parse + * @param scene The scene to create the parsed material in + * @param rootUrl The root url of the assets the material depends upon + * @returns the instantiated BackgroundMaterial. + */ + BackgroundMaterial.Parse = function (source, scene, rootUrl) { + return _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl); + }; + /** + * Standard reflectance value at parallel view angle. + */ + BackgroundMaterial.StandardReflectance0 = 0.05; + /** + * Standard reflectance value at grazing angle. + */ + BackgroundMaterial.StandardReflectance90 = 0.5; + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])() + ], BackgroundMaterial.prototype, "_primaryColor", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsLightsDirty") + ], BackgroundMaterial.prototype, "primaryColor", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])() + ], BackgroundMaterial.prototype, "__perceptualColor", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsLightsDirty") + ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])() + ], BackgroundMaterial.prototype, "_reflectionTexture", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], BackgroundMaterial.prototype, "reflectionTexture", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], BackgroundMaterial.prototype, "_reflectionBlur", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], BackgroundMaterial.prototype, "reflectionBlur", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])() + ], BackgroundMaterial.prototype, "_diffuseTexture", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], BackgroundMaterial.prototype, "diffuseTexture", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], BackgroundMaterial.prototype, "shadowLights", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], BackgroundMaterial.prototype, "_shadowLevel", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], BackgroundMaterial.prototype, "shadowLevel", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsVector3"])() + ], BackgroundMaterial.prototype, "_sceneCenter", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], BackgroundMaterial.prototype, "sceneCenter", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], BackgroundMaterial.prototype, "_opacityFresnel", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], BackgroundMaterial.prototype, "opacityFresnel", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], BackgroundMaterial.prototype, "reflectionFresnel", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], BackgroundMaterial.prototype, "_reflectionAmount", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], BackgroundMaterial.prototype, "reflectionAmount", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], BackgroundMaterial.prototype, "_useRGBColor", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], BackgroundMaterial.prototype, "useRGBColor", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], BackgroundMaterial.prototype, "_enableNoise", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], BackgroundMaterial.prototype, "enableNoise", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsImageProcessingConfiguration"])() + ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0); + return BackgroundMaterial; +}(_Materials_pushMaterial__WEBPACK_IMPORTED_MODULE_9__["PushMaterial"])); + +_Misc_typeStore__WEBPACK_IMPORTED_MODULE_13__["_TypeStore"].RegisteredTypes["BABYLON.BackgroundMaterial"] = BackgroundMaterial; + + +/***/ }), + +/***/ "./Materials/Background/index.ts": +/*!***************************************!*\ + !*** ./Materials/Background/index.ts ***! + \***************************************/ +/*! exports provided: BackgroundMaterial */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _backgroundMaterial__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./backgroundMaterial */ "./Materials/Background/backgroundMaterial.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BackgroundMaterial", function() { return _backgroundMaterial__WEBPACK_IMPORTED_MODULE_0__["BackgroundMaterial"]; }); + + + + +/***/ }), + +/***/ "./Materials/Node/Blocks/Dual/fogBlock.ts": +/*!************************************************!*\ + !*** ./Materials/Node/Blocks/Dual/fogBlock.ts ***! + \************************************************/ +/*! exports provided: FogBlock */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FogBlock", function() { return FogBlock; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts"); +/* harmony import */ var _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/nodeMaterialBlockConnectionPointTypes.ts"); +/* harmony import */ var _nodeMaterialWellKnownValues__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../nodeMaterialWellKnownValues */ "./Materials/Node/nodeMaterialWellKnownValues.ts"); +/* harmony import */ var _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../nodeMaterialBlockTargets */ "./Materials/Node/nodeMaterialBlockTargets.ts"); +/* harmony import */ var _materialHelper__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../../materialHelper */ "./Materials/materialHelper.ts"); + + + + + + +/** + * Block used to add support for scene fog + */ +var FogBlock = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](FogBlock, _super); + /** + * Create a new FogBlock + * @param name defines the block name + */ + function FogBlock(name) { + var _this = _super.call(this, name, _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].VertexAndFragment, true) || this; + // Vertex + _this.registerInput("worldPosition", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4, false, _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Vertex); + _this.registerInput("view", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Matrix, false, _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Vertex); + _this.registerOutput("vFogDistance", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3, _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Vertex); + // Fragment + _this.registerInput("color", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3OrColor4, false, _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment); + _this.registerInput("fogColor", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3, false, _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment); + _this.registerInput("fogParameters", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4, false, _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment); + _this.registerOutput("output", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3, _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment); + return _this; + } + /** + * Gets the current class name + * @returns the class name + */ + FogBlock.prototype.getClassName = function () { + return "FogBlock"; + }; + Object.defineProperty(FogBlock.prototype, "worldPosition", { + /** + * Gets the world position input component + */ + get: function () { + return this._inputs[0]; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(FogBlock.prototype, "view", { + /** + * Gets the view input component + */ + get: function () { + return this._inputs[1]; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(FogBlock.prototype, "color", { + /** + * Gets the color input component + */ + get: function () { + return this._inputs[2]; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(FogBlock.prototype, "fogColor", { + /** + * Gets the fog color input component + */ + get: function () { + return this._inputs[3]; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(FogBlock.prototype, "fogParameters", { + /** + * Gets the for parameter input component + */ + get: function () { + return this._inputs[4]; + }, + enumerable: true, + configurable: true + }); + FogBlock.prototype.autoConfigure = function () { + if (!this.view.connectedPoint) { + this.view.setAsWellKnownValue(_nodeMaterialWellKnownValues__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialWellKnownValues"].View); + } + if (!this.fogColor.connectedPoint) { + this.fogColor.setAsWellKnownValue(_nodeMaterialWellKnownValues__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialWellKnownValues"].Automatic); + } + if (!this.fogParameters.connectedPoint) { + this.fogParameters.setAsWellKnownValue(_nodeMaterialWellKnownValues__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialWellKnownValues"].Automatic); + } + this._outputs[0].isVarying = true; + }; + FogBlock.prototype.prepareDefines = function (mesh, nodeMaterial, defines) { + var scene = mesh.getScene(); + defines.setValue("FOG", nodeMaterial.fogEnabled && _materialHelper__WEBPACK_IMPORTED_MODULE_5__["MaterialHelper"].GetFogState(mesh, scene)); + }; + FogBlock.prototype.bind = function (effect, nodeMaterial, mesh) { + if (!mesh) { + return; + } + var scene = mesh.getScene(); + effect.setColor3("fogColor", scene.fogColor); + effect.setFloat4("fogParameters", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity); + }; + FogBlock.prototype._buildBlock = function (state) { + _super.prototype._buildBlock.call(this, state); + state.sharedData.blocksWithDefines.push(this); + if (state.target === _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment) { + state._emitFunctionFromInclude("fogFragmentDeclaration", "//" + this.name, { + removeUniforms: true, + removeVaryings: true, + removeIfDef: false, + replaceStrings: [{ search: /float CalcFogFactor\(\)/, replace: "float CalcFogFactor(vec3 vFogDistance, vec4 vFogInfos)" }] + }); + var tempFogVariablename = state._getFreeVariableName("fog"); + var color = this.color; + var fogColor = this.fogColor; + var fogParameters = this.fogParameters; + var output = this._outputs[1]; + var vFogDistance = this._outputs[0]; + state.compilationString += "#ifdef FOG\r\n"; + state.compilationString += "float " + tempFogVariablename + " = CalcFogFactor(" + vFogDistance.associatedVariableName + ", " + fogParameters.associatedVariableName + ");\r\n"; + state.compilationString += this._declareOutput(output, state) + (" = " + tempFogVariablename + " * " + color.associatedVariableName + ".rgb + (1.0 - " + tempFogVariablename + ") * " + fogColor.associatedVariableName + ";\r\n"); + state.compilationString += "#else\r\n" + this._declareOutput(output, state) + " = " + color.associatedVariableName + ".rgb;\r\n"; + state.compilationString += "#endif\r\n"; + } + else { + var worldPos = this.worldPosition; + var view = this.view; + var vFogDistance = this._outputs[0]; + state.compilationString += this._declareOutput(vFogDistance, state) + (" = (" + view.associatedVariableName + " * " + worldPos.associatedVariableName + ").xyz;\r\n"); + } + return this; + }; + return FogBlock; +}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"])); + + + +/***/ }), + +/***/ "./Materials/Node/Blocks/Dual/index.ts": +/*!*********************************************!*\ + !*** ./Materials/Node/Blocks/Dual/index.ts ***! + \*********************************************/ +/*! exports provided: FogBlock */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _fogBlock__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./fogBlock */ "./Materials/Node/Blocks/Dual/fogBlock.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FogBlock", function() { return _fogBlock__WEBPACK_IMPORTED_MODULE_0__["FogBlock"]; }); + + + + +/***/ }), + +/***/ "./Materials/Node/Blocks/Fragment/alphaTestBlock.ts": +/*!**********************************************************!*\ + !*** ./Materials/Node/Blocks/Fragment/alphaTestBlock.ts ***! + \**********************************************************/ +/*! exports provided: AlphaTestBlock */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AlphaTestBlock", function() { return AlphaTestBlock; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts"); +/* harmony import */ var _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/nodeMaterialBlockConnectionPointTypes.ts"); +/* harmony import */ var _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../nodeMaterialBlockTargets */ "./Materials/Node/nodeMaterialBlockTargets.ts"); + + + + +/** + * Block used to add an alpha test in the fragment shader + */ +var AlphaTestBlock = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](AlphaTestBlock, _super); + /** + * Create a new AlphaTestBlock + * @param name defines the block name + */ + function AlphaTestBlock(name) { + var _this = _super.call(this, name, _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment) || this; + /** + * Gets or sets the alpha value where alpha testing happens + */ + _this.alphaCutOff = 0.4; + _this.registerInput("color", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color4); + return _this; + } + /** + * Gets the current class name + * @returns the class name + */ + AlphaTestBlock.prototype.getClassName = function () { + return "AlphaTestBlock"; + }; + Object.defineProperty(AlphaTestBlock.prototype, "color", { + /** + * Gets the color input component + */ + get: function () { + return this._inputs[0]; + }, + enumerable: true, + configurable: true + }); + AlphaTestBlock.prototype._buildBlock = function (state) { + _super.prototype._buildBlock.call(this, state); + state.sharedData.hints.needAlphaTesting = true; + state.compilationString += "if (" + this.color.associatedVariableName + ".a < " + this.alphaCutOff + ") discard;\r\n"; + return this; + }; + return AlphaTestBlock; +}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"])); + + + +/***/ }), + +/***/ "./Materials/Node/Blocks/Fragment/fragmentOutputBlock.ts": +/*!***************************************************************!*\ + !*** ./Materials/Node/Blocks/Fragment/fragmentOutputBlock.ts ***! + \***************************************************************/ +/*! exports provided: FragmentOutputBlock */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FragmentOutputBlock", function() { return FragmentOutputBlock; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts"); +/* harmony import */ var _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/nodeMaterialBlockConnectionPointTypes.ts"); +/* harmony import */ var _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../nodeMaterialBlockTargets */ "./Materials/Node/nodeMaterialBlockTargets.ts"); + + + + +/** + * Block used to output the final color + */ +var FragmentOutputBlock = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](FragmentOutputBlock, _super); + /** + * Create a new FragmentOutputBlock + * @param name defines the block name + */ + function FragmentOutputBlock(name) { + var _this = _super.call(this, name, _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment, true) || this; + /** + * Gets or sets a boolean indicating if this block will output an alpha value + */ + _this.alphaBlendingEnabled = false; + _this.registerInput("color", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3OrColor4); + return _this; + } + /** + * Gets the current class name + * @returns the class name + */ + FragmentOutputBlock.prototype.getClassName = function () { + return "FragmentOutputBlock"; + }; + Object.defineProperty(FragmentOutputBlock.prototype, "color", { + /** + * Gets the color input component + */ + get: function () { + return this._inputs[0]; + }, + enumerable: true, + configurable: true + }); + FragmentOutputBlock.prototype._buildBlock = function (state) { + _super.prototype._buildBlock.call(this, state); + var input = this.color; + state.sharedData.hints.needAlphaBlending = this.alphaBlendingEnabled; + if (input.connectedPoint && input.connectedPoint.type === _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3) { + state.compilationString += "gl_FragColor = vec4(" + input.associatedVariableName + ", 1.0);\r\n"; + } + else { + state.compilationString += "gl_FragColor = " + input.associatedVariableName + ";\r\n"; + } + return this; + }; + return FragmentOutputBlock; +}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"])); + + + +/***/ }), + +/***/ "./Materials/Node/Blocks/Fragment/imageProcessingBlock.ts": +/*!****************************************************************!*\ + !*** ./Materials/Node/Blocks/Fragment/imageProcessingBlock.ts ***! + \****************************************************************/ +/*! exports provided: ImageProcessingBlock */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ImageProcessingBlock", function() { return ImageProcessingBlock; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts"); +/* harmony import */ var _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/nodeMaterialBlockConnectionPointTypes.ts"); +/* harmony import */ var _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../nodeMaterialBlockTargets */ "./Materials/Node/nodeMaterialBlockTargets.ts"); + + + + +/** + * Block used to add image processing support to fragment shader + */ +var ImageProcessingBlock = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ImageProcessingBlock, _super); + /** + * Create a new ImageProcessingBlock + * @param name defines the block name + */ + function ImageProcessingBlock(name) { + var _this = _super.call(this, name, _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment) || this; + _this.registerInput("color", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3OrColor4); + _this.registerOutput("output", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color4); + return _this; + } + /** + * Gets the current class name + * @returns the class name + */ + ImageProcessingBlock.prototype.getClassName = function () { + return "ImageProcessingBlock"; + }; + Object.defineProperty(ImageProcessingBlock.prototype, "color", { + /** + * Gets the color input component + */ + get: function () { + return this._inputs[0]; + }, + enumerable: true, + configurable: true + }); + /** + * Initialize the block and prepare the context for build + * @param state defines the state that will be used for the build + */ + ImageProcessingBlock.prototype.initialize = function (state) { + state._excludeVariableName("exposureLinear"); + state._excludeVariableName("contrast"); + state._excludeVariableName("vInverseScreenSize"); + state._excludeVariableName("vignetteSettings1"); + state._excludeVariableName("vignetteSettings2"); + state._excludeVariableName("vCameraColorCurveNegative"); + state._excludeVariableName("vCameraColorCurveNeutral"); + state._excludeVariableName("vCameraColorCurvePositive"); + state._excludeVariableName("txColorTransform"); + state._excludeVariableName("colorTransformSettings"); + }; + ImageProcessingBlock.prototype.isReady = function (mesh, nodeMaterial, defines) { + if (defines._areImageProcessingDirty && nodeMaterial.imageProcessingConfiguration) { + if (!nodeMaterial.imageProcessingConfiguration.isReady()) { + return false; + } + } + return true; + }; + ImageProcessingBlock.prototype.prepareDefines = function (mesh, nodeMaterial, defines) { + if (defines._areImageProcessingDirty && nodeMaterial.imageProcessingConfiguration) { + nodeMaterial.imageProcessingConfiguration.prepareDefines(defines); + } + }; + ImageProcessingBlock.prototype.bind = function (effect, nodeMaterial, mesh) { + if (!mesh) { + return; + } + if (!nodeMaterial.imageProcessingConfiguration) { + return; + } + nodeMaterial.imageProcessingConfiguration.bind(effect); + }; + ImageProcessingBlock.prototype._buildBlock = function (state) { + _super.prototype._buildBlock.call(this, state); + // Register for defines + state.sharedData.blocksWithDefines.push(this); + // Register for blocking + state.sharedData.blockingBlocks.push(this); + // Register for binding + state.sharedData.bindableBlocks.push(this); + // Uniforms + state.uniforms.push("exposureLinear"); + state.uniforms.push("contrast"); + state.uniforms.push("vInverseScreenSize"); + state.uniforms.push("vignetteSettings1"); + state.uniforms.push("vignetteSettings2"); + state.uniforms.push("vCameraColorCurveNegative"); + state.uniforms.push("vCameraColorCurveNeutral"); + state.uniforms.push("vCameraColorCurvePositive"); + state.uniforms.push("txColorTransform"); + state.uniforms.push("colorTransformSettings"); + // Emit code + var color = this.color; + var output = this._outputs[0]; + var comments = "//" + this.name; + state._emitFunctionFromInclude("helperFunctions", comments); + state._emitFunctionFromInclude("imageProcessingDeclaration", comments); + state._emitFunctionFromInclude("imageProcessingFunctions", comments); + if (color.connectedPoint.type === _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color4) { + state.compilationString += this._declareOutput(output, state) + " = " + color.associatedVariableName + ";\r\n"; + } + else { + state.compilationString += this._declareOutput(output, state) + " = vec4(" + color.associatedVariableName + ", 1.0);\r\n"; + } + state.compilationString += "#ifdef IMAGEPROCESSINGPOSTPROCESS\r\n"; + state.compilationString += output.associatedVariableName + ".rgb = toLinearSpace(" + color.associatedVariableName + ".rgb);\r\n"; + state.compilationString += "#else\r\n"; + state.compilationString += "#ifdef IMAGEPROCESSING\r\n"; + state.compilationString += output.associatedVariableName + ".rgb = toLinearSpace(" + color.associatedVariableName + ".rgb);\r\n"; + state.compilationString += output.associatedVariableName + " = applyImageProcessing(" + output.associatedVariableName + ");\r\n"; + state.compilationString += "#endif\r\n"; + state.compilationString += "#endif\r\n"; + return this; + }; + return ImageProcessingBlock; +}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"])); + + + +/***/ }), + +/***/ "./Materials/Node/Blocks/Fragment/index.ts": +/*!*************************************************!*\ + !*** ./Materials/Node/Blocks/Fragment/index.ts ***! + \*************************************************/ +/*! exports provided: FragmentOutputBlock, AlphaTestBlock, RGBAMergerBlock, RGBMergerBlock, RGBASplitterBlock, RGBSplitterBlock, TextureBlock, ImageProcessingBlock */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _fragmentOutputBlock__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./fragmentOutputBlock */ "./Materials/Node/Blocks/Fragment/fragmentOutputBlock.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FragmentOutputBlock", function() { return _fragmentOutputBlock__WEBPACK_IMPORTED_MODULE_0__["FragmentOutputBlock"]; }); + +/* harmony import */ var _alphaTestBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./alphaTestBlock */ "./Materials/Node/Blocks/Fragment/alphaTestBlock.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AlphaTestBlock", function() { return _alphaTestBlock__WEBPACK_IMPORTED_MODULE_1__["AlphaTestBlock"]; }); + +/* harmony import */ var _rgbaMergerBlock__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./rgbaMergerBlock */ "./Materials/Node/Blocks/Fragment/rgbaMergerBlock.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RGBAMergerBlock", function() { return _rgbaMergerBlock__WEBPACK_IMPORTED_MODULE_2__["RGBAMergerBlock"]; }); + +/* harmony import */ var _rgbMergerBlock__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./rgbMergerBlock */ "./Materials/Node/Blocks/Fragment/rgbMergerBlock.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RGBMergerBlock", function() { return _rgbMergerBlock__WEBPACK_IMPORTED_MODULE_3__["RGBMergerBlock"]; }); + +/* harmony import */ var _rgbaSplitterBlock__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./rgbaSplitterBlock */ "./Materials/Node/Blocks/Fragment/rgbaSplitterBlock.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RGBASplitterBlock", function() { return _rgbaSplitterBlock__WEBPACK_IMPORTED_MODULE_4__["RGBASplitterBlock"]; }); + +/* harmony import */ var _rgbSplitterBlock__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./rgbSplitterBlock */ "./Materials/Node/Blocks/Fragment/rgbSplitterBlock.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RGBSplitterBlock", function() { return _rgbSplitterBlock__WEBPACK_IMPORTED_MODULE_5__["RGBSplitterBlock"]; }); + +/* harmony import */ var _textureBlock__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./textureBlock */ "./Materials/Node/Blocks/Fragment/textureBlock.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TextureBlock", function() { return _textureBlock__WEBPACK_IMPORTED_MODULE_6__["TextureBlock"]; }); + +/* harmony import */ var _imageProcessingBlock__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./imageProcessingBlock */ "./Materials/Node/Blocks/Fragment/imageProcessingBlock.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ImageProcessingBlock", function() { return _imageProcessingBlock__WEBPACK_IMPORTED_MODULE_7__["ImageProcessingBlock"]; }); + + + + + + + + + + + +/***/ }), + +/***/ "./Materials/Node/Blocks/Fragment/rgbMergerBlock.ts": +/*!**********************************************************!*\ + !*** ./Materials/Node/Blocks/Fragment/rgbMergerBlock.ts ***! + \**********************************************************/ +/*! exports provided: RGBMergerBlock */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RGBMergerBlock", function() { return RGBMergerBlock; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts"); +/* harmony import */ var _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/nodeMaterialBlockConnectionPointTypes.ts"); +/* harmony import */ var _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../nodeMaterialBlockTargets */ "./Materials/Node/nodeMaterialBlockTargets.ts"); + + + + +/** + * Block used to create a Color3 out of 3 inputs (one for each component) + */ +var RGBMergerBlock = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](RGBMergerBlock, _super); + /** + * Create a new RGBMergerBlock + * @param name defines the block name + */ + function RGBMergerBlock(name) { + var _this = _super.call(this, name, _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment) || this; + _this.registerInput("r", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float); + _this.registerInput("g", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float); + _this.registerInput("b", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float); + _this.registerOutput("output", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3); + return _this; + } + /** + * Gets the current class name + * @returns the class name + */ + RGBMergerBlock.prototype.getClassName = function () { + return "RGBMergerBlock"; + }; + Object.defineProperty(RGBMergerBlock.prototype, "r", { + /** + * Gets the R component input + */ + get: function () { + return this._inputs[0]; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(RGBMergerBlock.prototype, "g", { + /** + * Gets the G component input + */ + get: function () { + return this._inputs[1]; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(RGBMergerBlock.prototype, "b", { + /** + * Gets the B component input + */ + get: function () { + return this._inputs[2]; + }, + enumerable: true, + configurable: true + }); + RGBMergerBlock.prototype._buildBlock = function (state) { + _super.prototype._buildBlock.call(this, state); + var rInput = this.r; + var gInput = this.g; + var bInput = this.b; + var output = this._outputs[0]; + state.compilationString += this._declareOutput(output, state) + (" = vec3(" + this._writeVariable(rInput) + ", " + this._writeVariable(gInput) + ", " + this._writeVariable(bInput) + ");\r\n"); + return this; + }; + return RGBMergerBlock; +}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"])); + + + +/***/ }), + +/***/ "./Materials/Node/Blocks/Fragment/rgbSplitterBlock.ts": +/*!************************************************************!*\ + !*** ./Materials/Node/Blocks/Fragment/rgbSplitterBlock.ts ***! + \************************************************************/ +/*! exports provided: RGBSplitterBlock */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RGBSplitterBlock", function() { return RGBSplitterBlock; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts"); +/* harmony import */ var _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/nodeMaterialBlockConnectionPointTypes.ts"); +/* harmony import */ var _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../nodeMaterialBlockTargets */ "./Materials/Node/nodeMaterialBlockTargets.ts"); + + + + +/** + * Block used to expand a Color3 or a Vector3 into 3 outputs (one for each component) + */ +var RGBSplitterBlock = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](RGBSplitterBlock, _super); + /** + * Create a new RGBSplitterBlock + * @param name defines the block name + */ + function RGBSplitterBlock(name) { + var _this = _super.call(this, name, _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment) || this; + _this.registerInput("input", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3OrColor3); + _this.registerOutput("r", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float); + _this.registerOutput("g", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float); + _this.registerOutput("b", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float); + return _this; + } + /** + * Gets the current class name + * @returns the class name + */ + RGBSplitterBlock.prototype.getClassName = function () { + return "RGBSplitterBlock"; + }; + Object.defineProperty(RGBSplitterBlock.prototype, "input", { + /** + * Gets the input component + */ + get: function () { + return this._inputs[0]; + }, + enumerable: true, + configurable: true + }); + RGBSplitterBlock.prototype._buildBlock = function (state) { + _super.prototype._buildBlock.call(this, state); + var input = this.input; + var rOutput = this._outputs[0]; + var gOutput = this._outputs[1]; + var bOutput = this._outputs[2]; + if (rOutput.connectedBlocks.length > 0) { + state.compilationString += this._declareOutput(rOutput, state) + (" = " + input.associatedVariableName + ".r;\r\n"); + } + if (gOutput.connectedBlocks.length > 0) { + state.compilationString += this._declareOutput(gOutput, state) + (" = " + input.associatedVariableName + ".g;\r\n"); + } + if (bOutput.connectedBlocks.length > 0) { + state.compilationString += this._declareOutput(bOutput, state) + (" = " + input.associatedVariableName + ".b;\r\n"); + } + return this; + }; + return RGBSplitterBlock; +}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"])); + + + +/***/ }), + +/***/ "./Materials/Node/Blocks/Fragment/rgbaMergerBlock.ts": +/*!***********************************************************!*\ + !*** ./Materials/Node/Blocks/Fragment/rgbaMergerBlock.ts ***! + \***********************************************************/ +/*! exports provided: RGBAMergerBlock */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RGBAMergerBlock", function() { return RGBAMergerBlock; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts"); +/* harmony import */ var _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/nodeMaterialBlockConnectionPointTypes.ts"); +/* harmony import */ var _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../nodeMaterialBlockTargets */ "./Materials/Node/nodeMaterialBlockTargets.ts"); + + + + +/** + * Block used to create a Color4 out of 4 inputs (one for each component) + */ +var RGBAMergerBlock = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](RGBAMergerBlock, _super); + /** + * Create a new RGBAMergerBlock + * @param name defines the block name + */ + function RGBAMergerBlock(name) { + var _this = _super.call(this, name, _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment) || this; + _this.registerInput("r", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, true); + _this.registerInput("g", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, true); + _this.registerInput("b", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, true); + _this.registerInput("rgb", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3OrColor3OrVector4OrColor4, true); + _this.registerInput("a", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, true); + _this.registerOutput("output", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color4); + return _this; + } + /** + * Gets the current class name + * @returns the class name + */ + RGBAMergerBlock.prototype.getClassName = function () { + return "RGBAMergerBlock"; + }; + Object.defineProperty(RGBAMergerBlock.prototype, "r", { + /** + * Gets the R input component + */ + get: function () { + return this._inputs[0]; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(RGBAMergerBlock.prototype, "g", { + /** + * Gets the G input component + */ + get: function () { + return this._inputs[1]; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(RGBAMergerBlock.prototype, "b", { + /** + * Gets the B input component + */ + get: function () { + return this._inputs[2]; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(RGBAMergerBlock.prototype, "rgb", { + /** + * Gets the RGB input component + */ + get: function () { + return this._inputs[3]; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(RGBAMergerBlock.prototype, "a", { + /** + * Gets the R input component + */ + get: function () { + return this._inputs[4]; + }, + enumerable: true, + configurable: true + }); + RGBAMergerBlock.prototype._buildBlock = function (state) { + _super.prototype._buildBlock.call(this, state); + var rgbInput = this.rgb; + var aInput = this.a; + var output = this._outputs[0]; + if (rgbInput.connectedPoint) { + state.compilationString += this._declareOutput(output, state) + (" = vec4(" + rgbInput.associatedVariableName + ".rgb, " + this._writeVariable(aInput) + ");\r\n"); + } + else { + var rInput = this._inputs[0]; + var gInput = this._inputs[1]; + var bInput = this._inputs[2]; + state.compilationString += this._declareOutput(output, state) + (" = vec4(" + this._writeVariable(rInput) + ", " + this._writeVariable(gInput) + ", " + this._writeVariable(bInput) + ", " + this._writeVariable(aInput) + ");\r\n"); + } + return this; + }; + return RGBAMergerBlock; +}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"])); + + + +/***/ }), + +/***/ "./Materials/Node/Blocks/Fragment/rgbaSplitterBlock.ts": +/*!*************************************************************!*\ + !*** ./Materials/Node/Blocks/Fragment/rgbaSplitterBlock.ts ***! + \*************************************************************/ +/*! exports provided: RGBASplitterBlock */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RGBASplitterBlock", function() { return RGBASplitterBlock; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts"); +/* harmony import */ var _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/nodeMaterialBlockConnectionPointTypes.ts"); +/* harmony import */ var _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../nodeMaterialBlockTargets */ "./Materials/Node/nodeMaterialBlockTargets.ts"); + + + + +/** + * Block used to expand a Color4 or a Vector4 into 4 outputs (one for each component) + */ +var RGBASplitterBlock = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](RGBASplitterBlock, _super); + /** + * Create a new RGBASplitterBlock + * @param name defines the block name + */ + function RGBASplitterBlock(name) { + var _this = _super.call(this, name, _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment) || this; + _this.registerInput("input", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4OrColor4); + _this.registerOutput("r", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float); + _this.registerOutput("g", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float); + _this.registerOutput("b", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float); + _this.registerOutput("a", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float); + return _this; + } + /** + * Gets the current class name + * @returns the class name + */ + RGBASplitterBlock.prototype.getClassName = function () { + return "RGBASplitterBlock"; + }; + Object.defineProperty(RGBASplitterBlock.prototype, "input", { + /** + * Gets the input component + */ + get: function () { + return this._inputs[0]; + }, + enumerable: true, + configurable: true + }); + RGBASplitterBlock.prototype._buildBlock = function (state) { + _super.prototype._buildBlock.call(this, state); + var input = this.input; + var rOutput = this._outputs[0]; + var gOutput = this._outputs[1]; + var bOutput = this._outputs[2]; + var aOutput = this._outputs[3]; + if (rOutput.connectedBlocks.length > 0) { + state.compilationString += this._declareOutput(rOutput, state) + (" = " + input.associatedVariableName + ".r;\r\n"); + } + if (gOutput.connectedBlocks.length > 0) { + state.compilationString += this._declareOutput(gOutput, state) + (" = " + input.associatedVariableName + ".g;\r\n"); + } + if (bOutput.connectedBlocks.length > 0) { + state.compilationString += this._declareOutput(bOutput, state) + (" = " + input.associatedVariableName + ".b;\r\n"); + } + if (aOutput.connectedBlocks.length > 0) { + state.compilationString += this._declareOutput(aOutput, state) + (" = " + input.associatedVariableName + ".a;\r\n"); + } + return this; + }; + return RGBASplitterBlock; +}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"])); + + + +/***/ }), + +/***/ "./Materials/Node/Blocks/Fragment/textureBlock.ts": +/*!********************************************************!*\ + !*** ./Materials/Node/Blocks/Fragment/textureBlock.ts ***! + \********************************************************/ +/*! exports provided: TextureBlock */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextureBlock", function() { return TextureBlock; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts"); +/* harmony import */ var _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/nodeMaterialBlockConnectionPointTypes.ts"); +/* harmony import */ var _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../nodeMaterialBlockTargets */ "./Materials/Node/nodeMaterialBlockTargets.ts"); + + + + +/** + * Block used to read a texture from a sampler + */ +var TextureBlock = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](TextureBlock, _super); + /** + * Create a new TextureBlock + * @param name defines the block name + */ + function TextureBlock(name) { + var _this = _super.call(this, name, _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment) || this; + /** + * Gets or sets a boolean indicating that the block can automatically fetch the texture matrix + */ + _this.autoConnectTextureMatrix = true; + /** + * Gets or sets a boolean indicating that the block can automatically select the uv channel based on texture + */ + _this.autoSelectUV = true; + _this.registerInput("uv", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector2); + _this.registerInput("textureInfo", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector2, true); + _this.registerInput("transformedUV", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector2, false, _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Vertex); + _this.registerInput("texture", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Texture, false, _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment); + _this.registerInput("textureTransform", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Matrix, true, _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Vertex); + _this.registerOutput("color", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color4); + // Setup + _this._inputs[0]._needToEmitVarying = false; + return _this; + } + /** + * Gets the current class name + * @returns the class name + */ + TextureBlock.prototype.getClassName = function () { + return "TextureBlock"; + }; + Object.defineProperty(TextureBlock.prototype, "uv", { + /** + * Gets the uv input component + */ + get: function () { + return this._inputs[0]; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(TextureBlock.prototype, "textureInfo", { + /** + * Gets the texture information input component + */ + get: function () { + return this._inputs[1]; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(TextureBlock.prototype, "transformedUV", { + /** + * Gets the transformed uv input component + */ + get: function () { + return this._inputs[2]; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(TextureBlock.prototype, "texture", { + /** + * Gets the texture input component + */ + get: function () { + return this._inputs[3]; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(TextureBlock.prototype, "textureTransform", { + /** + * Gets the texture transform input component + */ + get: function () { + return this._inputs[4]; + }, + enumerable: true, + configurable: true + }); + TextureBlock.prototype.autoConfigure = function () { + if (!this.uv.connectedPoint) { + this.uv.setAsAttribute(); + this.uv.connectTo(this.transformedUV); + } + }; + TextureBlock.prototype.initialize = function (state) { + if (this.texture.value && this.texture.value.getTextureMatrix) { + var texture_1 = this.texture.value; + if (this.autoConnectTextureMatrix) { + this.textureTransform.valueCallback = function () { return texture_1.getTextureMatrix(); }; + } + if (this.autoSelectUV) { + this.uv.setAsAttribute("uv" + (texture_1.coordinatesIndex ? (texture_1.coordinatesIndex + 1) : "")); + } + } + }; + TextureBlock.prototype.prepareDefines = function (mesh, nodeMaterial, defines) { + if (!this.texture.value || !this.texture.value.getTextureMatrix) { + return; + } + var uvInput = this.uv; + var textureTransform = this.textureTransform; + var isTextureTransformConnected = textureTransform.connectedPoint != null || textureTransform.isUniform; + var texture = this.texture.value; + var mainUVName = ("vMain" + uvInput.associatedVariableName).toUpperCase(); + if (isTextureTransformConnected && !texture.getTextureMatrix().isIdentityAs3x2()) { + defines.setValue(this._defineName, true); + defines.setValue(mainUVName, false); + } + else { + defines.setValue(this._defineName, false); + defines.setValue(mainUVName, true); + } + }; + TextureBlock.prototype.isReady = function () { + var texture = this.texture.value; + if (texture && !texture.isReadyOrNotBlocking()) { + return false; + } + return true; + }; + TextureBlock.prototype._injectVertexCode = function (state) { + var uvInput = this.uv; + var transformedUV = this.transformedUV; + var textureTransform = this.textureTransform; + var isTextureTransformConnected = textureTransform.connectedPoint != null || textureTransform.isUniform; + // Inject code in vertex + this._defineName = state._getFreeDefineName("UVTRANSFORM"); + var mainUVName = "vMain" + uvInput.associatedVariableName; + transformedUV.associatedVariableName = state._getFreeVariableName(transformedUV.name); + state._emitVaryings(transformedUV, this._defineName, true); + state._emitVaryings(transformedUV, mainUVName.toUpperCase(), true, false, mainUVName); + textureTransform.associatedVariableName = state._getFreeVariableName(textureTransform.name); + state._emitUniformOrAttributes(textureTransform, this._defineName); + if (isTextureTransformConnected) { + if (state.sharedData.emitComments) { + state.compilationString += "\r\n//" + this.name + "\r\n"; + } + state.compilationString += "#ifdef " + this._defineName + "\r\n"; + state.compilationString += transformedUV.associatedVariableName + " = vec2(" + textureTransform.associatedVariableName + " * vec4(" + uvInput.associatedVariableName + ", 1.0, 0.0));\r\n"; + state.compilationString += "#else\r\n"; + state.compilationString += mainUVName + " = " + uvInput.associatedVariableName + ";\r\n"; + state.compilationString += "#endif\r\n"; + } + else { + state.compilationString += mainUVName + " = " + uvInput.associatedVariableName + ";\r\n"; + } + }; + TextureBlock.prototype._buildBlock = function (state) { + _super.prototype._buildBlock.call(this, state); + state.sharedData.blockingBlocks.push(this); + // Vertex + this._injectVertexCode(state._vertexState); + // Fragment + state.sharedData.blocksWithDefines.push(this); + var uvInput = this.uv; + var transformedUV = this.transformedUV; + var textureInfo = this.textureInfo; + var samplerInput = this.texture; + var output = this._outputs[0]; + var isTextureInfoConnected = textureInfo.connectedPoint != null || textureInfo.isUniform; + var complement = isTextureInfoConnected ? " * " + textureInfo.associatedVariableName + ".y" : ""; + state.compilationString += "#ifdef " + this._defineName + "\r\n"; + state.compilationString += "vec4 " + output.associatedVariableName + " = texture2D(" + samplerInput.associatedVariableName + ", " + transformedUV.associatedVariableName + ")" + complement + ";\r\n"; + state.compilationString += "#else\r\n"; + state.compilationString += "vec4 " + output.associatedVariableName + " = texture2D(" + samplerInput.associatedVariableName + ", " + ("vMain" + uvInput.associatedVariableName) + ")" + complement + ";\r\n"; + state.compilationString += "#endif\r\n"; + return this; + }; + return TextureBlock; +}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"])); + + + +/***/ }), + +/***/ "./Materials/Node/Blocks/Vertex/bonesBlock.ts": +/*!****************************************************!*\ + !*** ./Materials/Node/Blocks/Vertex/bonesBlock.ts ***! + \****************************************************/ +/*! exports provided: BonesBlock */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BonesBlock", function() { return BonesBlock; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts"); +/* harmony import */ var _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/nodeMaterialBlockConnectionPointTypes.ts"); +/* harmony import */ var _nodeMaterialWellKnownValues__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../nodeMaterialWellKnownValues */ "./Materials/Node/nodeMaterialWellKnownValues.ts"); +/* harmony import */ var _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../nodeMaterialBlockTargets */ "./Materials/Node/nodeMaterialBlockTargets.ts"); +/* harmony import */ var _materialHelper__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../../materialHelper */ "./Materials/materialHelper.ts"); + + + + + + +/** + * Block used to add support for vertex skinning (bones) + */ +var BonesBlock = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](BonesBlock, _super); + /** + * Creates a new BonesBlock + * @param name defines the block name + */ + function BonesBlock(name) { + var _this = _super.call(this, name, _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Vertex) || this; + _this.registerInput("matricesIndices", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4); + _this.registerInput("matricesWeights", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4); + _this.registerInput("matricesIndicesExtra", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4); + _this.registerInput("matricesWeightsExtra", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4); + _this.registerInput("world", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Matrix); + _this.registerOutput("output", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Matrix); + return _this; + } + /** + * Initialize the block and prepare the context for build + * @param state defines the state that will be used for the build + */ + BonesBlock.prototype.initialize = function (state) { + state._excludeVariableName("boneSampler"); + state._excludeVariableName("boneTextureWidth"); + state._excludeVariableName("mBones"); + state._excludeVariableName("BonesPerMesh"); + }; + /** + * Gets the current class name + * @returns the class name + */ + BonesBlock.prototype.getClassName = function () { + return "BonesBlock"; + }; + Object.defineProperty(BonesBlock.prototype, "matricesIndices", { + /** + * Gets the matrix indices input component + */ + get: function () { + return this._inputs[0]; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(BonesBlock.prototype, "matricesWeights", { + /** + * Gets the matrix weights input component + */ + get: function () { + return this._inputs[1]; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(BonesBlock.prototype, "matricesIndicesExtra", { + /** + * Gets the extra matrix indices input component + */ + get: function () { + return this._inputs[2]; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(BonesBlock.prototype, "matricesWeightsExtra", { + /** + * Gets the extra matrix weights input component + */ + get: function () { + return this._inputs[3]; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(BonesBlock.prototype, "world", { + /** + * Gets the world input component + */ + get: function () { + return this._inputs[4]; + }, + enumerable: true, + configurable: true + }); + BonesBlock.prototype.autoConfigure = function () { + if (!this.matricesIndices.connectedPoint) { + this.matricesIndices.setAsAttribute(); + } + if (!this.matricesWeights.connectedPoint) { + this.matricesWeights.setAsAttribute(); + } + if (!this.matricesIndicesExtra.connectedPoint) { + this.matricesIndicesExtra.setAsAttribute(); + } + if (!this.matricesWeightsExtra.connectedPoint) { + this.matricesWeightsExtra.setAsAttribute(); + } + if (!this.world.connectedPoint) { + this.world.setAsWellKnownValue(_nodeMaterialWellKnownValues__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialWellKnownValues"].World); + } + }; + BonesBlock.prototype.provideFallbacks = function (mesh, fallbacks) { + if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) { + fallbacks.addCPUSkinningFallback(0, mesh); + } + }; + BonesBlock.prototype.bind = function (effect, nodeMaterial, mesh) { + _materialHelper__WEBPACK_IMPORTED_MODULE_5__["MaterialHelper"].BindBonesParameters(mesh, effect); + }; + BonesBlock.prototype.prepareDefines = function (mesh, nodeMaterial, defines) { + if (!defines._areAttributesDirty) { + return; + } + _materialHelper__WEBPACK_IMPORTED_MODULE_5__["MaterialHelper"].PrepareDefinesForBones(mesh, defines); + }; + BonesBlock.prototype._buildBlock = function (state) { + _super.prototype._buildBlock.call(this, state); + // Register for compilation fallbacks + state.sharedData.blocksWithFallbacks.push(this); + // Register for binding + state.sharedData.bindableBlocks.push(this); + // Register for defines + state.sharedData.blocksWithDefines.push(this); + // Register internal uniforms and samplers + state.uniforms.push("boneTextureWidth"); + state.uniforms.push("mBones"); + state.samplers.push("boneSampler"); + // Emit code + var comments = "//" + this.name; + state._emitFunctionFromInclude("bonesDeclaration", comments, { + removeAttributes: true, + removeUniforms: false, + removeVaryings: true, + removeIfDef: false + }); + var influenceVariablename = state._getFreeVariableName("influence"); + state.compilationString += state._emitCodeFromInclude("bonesVertex", comments, { + replaceStrings: [ + { + search: /finalWorld=finalWorld\*influence;/, + replace: "" + }, + { + search: /influence/gm, + replace: influenceVariablename + } + ] + }); + var output = this._outputs[0]; + var worldInput = this.world; + state.compilationString += this._declareOutput(output, state) + (" = " + worldInput.associatedVariableName + " * " + influenceVariablename + ";"); + return this; + }; + return BonesBlock; +}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"])); + + + +/***/ }), + +/***/ "./Materials/Node/Blocks/Vertex/index.ts": +/*!***********************************************!*\ + !*** ./Materials/Node/Blocks/Vertex/index.ts ***! + \***********************************************/ +/*! exports provided: VertexOutputBlock, BonesBlock, InstancesBlock, MorphTargetsBlock */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _vertexOutputBlock__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./vertexOutputBlock */ "./Materials/Node/Blocks/Vertex/vertexOutputBlock.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VertexOutputBlock", function() { return _vertexOutputBlock__WEBPACK_IMPORTED_MODULE_0__["VertexOutputBlock"]; }); + +/* harmony import */ var _bonesBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./bonesBlock */ "./Materials/Node/Blocks/Vertex/bonesBlock.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BonesBlock", function() { return _bonesBlock__WEBPACK_IMPORTED_MODULE_1__["BonesBlock"]; }); + +/* harmony import */ var _instancesBlock__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./instancesBlock */ "./Materials/Node/Blocks/Vertex/instancesBlock.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InstancesBlock", function() { return _instancesBlock__WEBPACK_IMPORTED_MODULE_2__["InstancesBlock"]; }); + +/* harmony import */ var _morphTargetsBlock__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./morphTargetsBlock */ "./Materials/Node/Blocks/Vertex/morphTargetsBlock.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MorphTargetsBlock", function() { return _morphTargetsBlock__WEBPACK_IMPORTED_MODULE_3__["MorphTargetsBlock"]; }); + + + + + + + +/***/ }), + +/***/ "./Materials/Node/Blocks/Vertex/instancesBlock.ts": +/*!********************************************************!*\ + !*** ./Materials/Node/Blocks/Vertex/instancesBlock.ts ***! + \********************************************************/ +/*! exports provided: InstancesBlock */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InstancesBlock", function() { return InstancesBlock; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts"); +/* harmony import */ var _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../nodeMaterialBlockTargets */ "./Materials/Node/nodeMaterialBlockTargets.ts"); +/* harmony import */ var _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/nodeMaterialBlockConnectionPointTypes.ts"); +/* harmony import */ var _nodeMaterialWellKnownValues__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../nodeMaterialWellKnownValues */ "./Materials/Node/nodeMaterialWellKnownValues.ts"); + + + + + +/** + * Block used to add support for instances + * @see https://doc.babylonjs.com/how_to/how_to_use_instances + */ +var InstancesBlock = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](InstancesBlock, _super); + /** + * Creates a new InstancesBlock + * @param name defines the block name + */ + function InstancesBlock(name) { + var _this = _super.call(this, name, _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockTargets"].Vertex) || this; + _this.registerInput("world0", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointTypes"].Vector4); + _this.registerInput("world1", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointTypes"].Vector4); + _this.registerInput("world2", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointTypes"].Vector4); + _this.registerInput("world3", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointTypes"].Vector4); + _this.registerInput("world", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointTypes"].Matrix, true); + _this.registerOutput("output", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointTypes"].Matrix); + return _this; + } + /** + * Gets the current class name + * @returns the class name + */ + InstancesBlock.prototype.getClassName = function () { + return "InstancesBlock"; + }; + Object.defineProperty(InstancesBlock.prototype, "world0", { + /** + * Gets the first world row input component + */ + get: function () { + return this._inputs[0]; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(InstancesBlock.prototype, "world1", { + /** + * Gets the second world row input component + */ + get: function () { + return this._inputs[1]; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(InstancesBlock.prototype, "world2", { + /** + * Gets the third world row input component + */ + get: function () { + return this._inputs[2]; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(InstancesBlock.prototype, "world3", { + /** + * Gets the forth world row input component + */ + get: function () { + return this._inputs[3]; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(InstancesBlock.prototype, "world", { + /** + * Gets the world input component + */ + get: function () { + return this._inputs[4]; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(InstancesBlock.prototype, "output", { + /** + * Gets the output component + */ + get: function () { + return this._outputs[0]; + }, + enumerable: true, + configurable: true + }); + InstancesBlock.prototype.autoConfigure = function () { + if (!this.world0.connectedPoint) { + this.world0.setAsAttribute(); + } + if (!this.world1.connectedPoint) { + this.world1.setAsAttribute(); + } + if (!this.world2.connectedPoint) { + this.world2.setAsAttribute(); + } + if (!this.world3.connectedPoint) { + this.world3.setAsAttribute(); + } + if (!this.world.connectedPoint) { + this.world.setAsWellKnownValue(_nodeMaterialWellKnownValues__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialWellKnownValues"].World); + } + this.world.define = "!INSTANCES"; + }; + InstancesBlock.prototype.prepareDefines = function (mesh, nodeMaterial, defines, useInstances) { + if (useInstances === void 0) { useInstances = false; } + var changed = false; + if (defines["INSTANCES"] !== useInstances) { + defines.setValue("INSTANCES", useInstances); + changed = true; + } + if (changed) { + defines.markAsUnprocessed(); + } + }; + InstancesBlock.prototype._buildBlock = function (state) { + _super.prototype._buildBlock.call(this, state); + // Register for defines + state.sharedData.blocksWithDefines.push(this); + // Emit code + var output = this._outputs[0]; + var world0 = this.world0; + var world1 = this.world1; + var world2 = this.world2; + var world3 = this.world3; + state.compilationString += "#ifdef INSTANCES\r\n"; + state.compilationString += this._declareOutput(output, state) + (" = mat4(" + world0.associatedVariableName + ", " + world1.associatedVariableName + ", " + world2.associatedVariableName + ", " + world3.associatedVariableName + ");\r\n"); + state.compilationString += "#else\r\n"; + state.compilationString += this._declareOutput(output, state) + (" = " + this.world.associatedVariableName + ";\r\n"); + state.compilationString += "#endif\r\n"; + return this; + }; + return InstancesBlock; +}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"])); + + + +/***/ }), + +/***/ "./Materials/Node/Blocks/Vertex/morphTargetsBlock.ts": +/*!***********************************************************!*\ + !*** ./Materials/Node/Blocks/Vertex/morphTargetsBlock.ts ***! + \***********************************************************/ +/*! exports provided: MorphTargetsBlock */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MorphTargetsBlock", function() { return MorphTargetsBlock; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts"); +/* harmony import */ var _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/nodeMaterialBlockConnectionPointTypes.ts"); +/* harmony import */ var _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../nodeMaterialBlockTargets */ "./Materials/Node/nodeMaterialBlockTargets.ts"); +/* harmony import */ var _materialHelper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../materialHelper */ "./Materials/materialHelper.ts"); +/* harmony import */ var _Meshes_buffer__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../../../Meshes/buffer */ "./Meshes/buffer.ts"); + + + + + + +/** + * Block used to add morph targets support to vertex shader + */ +var MorphTargetsBlock = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](MorphTargetsBlock, _super); + /** + * Create a new MorphTargetsBlock + * @param name defines the block name + */ + function MorphTargetsBlock(name) { + var _this = _super.call(this, name, _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Vertex) || this; + _this._repeatebleContentGenerated = 0; + _this.registerInput("position", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3); + _this.registerInput("normal", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3); + _this.registerInput("tangent", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3); + _this.registerOutput("positionOutput", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3); + _this.registerOutput("normalOutput", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3); + _this.registerOutput("tangentOutput", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3); + return _this; + } + /** + * Gets the current class name + * @returns the class name + */ + MorphTargetsBlock.prototype.getClassName = function () { + return "MorphTargetsBlock"; + }; + Object.defineProperty(MorphTargetsBlock.prototype, "position", { + /** + * Gets the position input component + */ + get: function () { + return this._inputs[0]; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(MorphTargetsBlock.prototype, "normal", { + /** + * Gets the normal input component + */ + get: function () { + return this._inputs[1]; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(MorphTargetsBlock.prototype, "tangent", { + /** + * Gets the tangent input component + */ + get: function () { + return this._inputs[2]; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(MorphTargetsBlock.prototype, "positionOutput", { + /** + * Gets the position output component + */ + get: function () { + return this._outputs[0]; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(MorphTargetsBlock.prototype, "normalOutput", { + /** + * Gets the normal output component + */ + get: function () { + return this._outputs[1]; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(MorphTargetsBlock.prototype, "tangentOutput", { + /** + * Gets the tangent output component + */ + get: function () { + return this._outputs[2]; + }, + enumerable: true, + configurable: true + }); + MorphTargetsBlock.prototype.initialize = function (state) { + state._excludeVariableName("morphTargetInfluences"); + }; + MorphTargetsBlock.prototype.autoConfigure = function () { + if (!this.position.connectedPoint) { + this.position.setAsAttribute(); + } + if (!this.normal.connectedPoint) { + this.normal.setAsAttribute(); + this.normal.define = "NORMAL"; + } + if (!this.tangent.connectedPoint) { + this.tangent.setAsAttribute(); + this.tangent.define = "TANGENT"; + } + }; + MorphTargetsBlock.prototype.prepareDefines = function (mesh, nodeMaterial, defines) { + if (!defines._areAttributesDirty) { + return; + } + _materialHelper__WEBPACK_IMPORTED_MODULE_4__["MaterialHelper"].PrepareDefinesForMorphTargets(mesh, defines); + }; + MorphTargetsBlock.prototype.bind = function (effect, nodeMaterial, mesh) { + if (mesh && this._repeatebleContentGenerated) { + _materialHelper__WEBPACK_IMPORTED_MODULE_4__["MaterialHelper"].BindMorphTargetParameters(mesh, effect); + } + }; + MorphTargetsBlock.prototype.replaceRepeatableContent = function (vertexShaderState, fragmentShaderState, mesh, defines) { + var position = this.position; + var normal = this.normal; + var tangent = this.tangent; + var positionOutput = this.positionOutput; + var normalOutput = this.normalOutput; + var tangentOutput = this.tangentOutput; + var state = vertexShaderState; + var repeatCount = defines.NUM_MORPH_INFLUENCERS; + this._repeatebleContentGenerated = repeatCount; + var manager = mesh.morphTargetManager; + var hasNormals = manager && manager.supportsNormals && defines["NORMAL"]; + var hasTangents = manager && manager.supportsTangents && defines["TANGENT"]; + var injectionCode = ""; + for (var index = 0; index < repeatCount; index++) { + injectionCode += "#ifdef MORPHTARGETS\r\n"; + injectionCode += positionOutput.associatedVariableName + " += (position" + index + " - " + position.associatedVariableName + ") * morphTargetInfluences[" + index + "];\r\n"; + if (hasNormals) { + injectionCode += "#ifdef MORPHTARGETS_NORMAL\r\n"; + injectionCode += normalOutput.associatedVariableName + " += (normal" + index + " - " + normal.associatedVariableName + ") * morphTargetInfluences[" + index + "];\r\n"; + injectionCode += "#endif\r\n"; + } + if (hasTangents) { + injectionCode += "#ifdef MORPHTARGETS_TANGENT\r\n"; + injectionCode += tangentOutput.associatedVariableName + ".xyz += (tangent" + index + " - " + tangent.associatedVariableName + ".xyz) * morphTargetInfluences[" + index + "];\r\n"; + injectionCode += "#endif\r\n"; + } + injectionCode += "#endif\r\n"; + } + state.compilationString = state.compilationString.replace(this._repeatableContentAnchor, injectionCode); + if (repeatCount > 0) { + for (var index = 0; index < repeatCount; index++) { + state.attributes.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_5__["VertexBuffer"].PositionKind + index); + if (hasNormals) { + state.attributes.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_5__["VertexBuffer"].NormalKind + index); + } + if (hasTangents) { + state.attributes.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_5__["VertexBuffer"].TangentKind + index); + } + } + } + }; + MorphTargetsBlock.prototype._buildBlock = function (state) { + _super.prototype._buildBlock.call(this, state); + // Register for defines + state.sharedData.blocksWithDefines.push(this); + // Register for binding + state.sharedData.bindableBlocks.push(this); + // Register for repeatable content generation + state.sharedData.repeatableContentBlocks.push(this); + // Emit code + var position = this.position; + var normal = this.normal; + var tangent = this.tangent; + var positionOutput = this.positionOutput; + var normalOutput = this.normalOutput; + var tangentOutput = this.tangentOutput; + var comments = "//" + this.name; + state.uniforms.push("morphTargetInfluences"); + state._emitFunctionFromInclude("morphTargetsVertexGlobalDeclaration", comments); + state._emitFunctionFromInclude("morphTargetsVertexDeclaration", comments, { + repeatKey: "maxSimultaneousMorphTargets" + }); + state.compilationString += this._declareOutput(positionOutput, state) + " = " + position.associatedVariableName + ";\r\n"; + state.compilationString += "#ifdef NORMAL\r\n"; + state.compilationString += this._declareOutput(normalOutput, state) + " = " + normal.associatedVariableName + ";\r\n"; + state.compilationString += "#endif\r\n"; + state.compilationString += "#ifdef TANGENT\r\n"; + state.compilationString += this._declareOutput(tangentOutput, state) + " = " + tangent.associatedVariableName + ";\r\n"; + state.compilationString += "#endif\r\n"; + // Repeatable content + this._repeatableContentAnchor = state._repeatableContentAnchor; + state.compilationString += this._repeatableContentAnchor; + return this; + }; + return MorphTargetsBlock; +}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"])); + + + +/***/ }), + +/***/ "./Materials/Node/Blocks/Vertex/vertexOutputBlock.ts": +/*!***********************************************************!*\ + !*** ./Materials/Node/Blocks/Vertex/vertexOutputBlock.ts ***! + \***********************************************************/ +/*! exports provided: VertexOutputBlock */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VertexOutputBlock", function() { return VertexOutputBlock; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts"); +/* harmony import */ var _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/nodeMaterialBlockConnectionPointTypes.ts"); +/* harmony import */ var _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../nodeMaterialBlockTargets */ "./Materials/Node/nodeMaterialBlockTargets.ts"); + + + + +/** + * Block used to output the vertex position + */ +var VertexOutputBlock = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](VertexOutputBlock, _super); + /** + * Creates a new VertexOutputBlock + * @param name defines the block name + */ + function VertexOutputBlock(name) { + var _this = _super.call(this, name, _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Vertex, true) || this; + _this.registerInput("vector", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4); + return _this; + } + /** + * Gets the current class name + * @returns the class name + */ + VertexOutputBlock.prototype.getClassName = function () { + return "VertexOutputBlock"; + }; + Object.defineProperty(VertexOutputBlock.prototype, "vector", { + /** + * Gets the vector input component + */ + get: function () { + return this._inputs[0]; + }, + enumerable: true, + configurable: true + }); + VertexOutputBlock.prototype._buildBlock = function (state) { + _super.prototype._buildBlock.call(this, state); + var input = this.vector; + state.compilationString += "gl_Position = " + input.associatedVariableName + ";\r\n"; + return this; + }; + return VertexOutputBlock; +}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"])); + + + +/***/ }), + +/***/ "./Materials/Node/Blocks/addBlock.ts": +/*!*******************************************!*\ + !*** ./Materials/Node/Blocks/addBlock.ts ***! + \*******************************************/ +/*! exports provided: AddBlock */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AddBlock", function() { return AddBlock; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts"); +/* harmony import */ var _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/nodeMaterialBlockConnectionPointTypes.ts"); + + + +/** + * Block used to add 2 vector4 + */ +var AddBlock = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](AddBlock, _super); + /** + * Creates a new AddBlock + * @param name defines the block name + */ + function AddBlock(name) { + var _this = _super.call(this, name) || this; + _this.registerInput("left", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4OrColor4); + _this.registerInput("right", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4OrColor4); + _this.registerOutput("output", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4OrColor4); + return _this; + } + /** + * Gets the current class name + * @returns the class name + */ + AddBlock.prototype.getClassName = function () { + return "AddBlock"; + }; + Object.defineProperty(AddBlock.prototype, "left", { + /** + * Gets the left operand input component + */ + get: function () { + return this._inputs[0]; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(AddBlock.prototype, "right", { + /** + * Gets the right operand input component + */ + get: function () { + return this._inputs[1]; + }, + enumerable: true, + configurable: true + }); + AddBlock.prototype._buildBlock = function (state) { + _super.prototype._buildBlock.call(this, state); + var output = this._outputs[0]; + state.compilationString += this._declareOutput(output, state) + (" = " + this.left.associatedVariableName + " + " + this.right.associatedVariableName + ";\r\n"); + return this; + }; + return AddBlock; +}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"])); + + + +/***/ }), + +/***/ "./Materials/Node/Blocks/clampBlock.ts": +/*!*********************************************!*\ + !*** ./Materials/Node/Blocks/clampBlock.ts ***! + \*********************************************/ +/*! exports provided: ClampBlock */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ClampBlock", function() { return ClampBlock; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts"); +/* harmony import */ var _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/nodeMaterialBlockConnectionPointTypes.ts"); + + + +/** + * Block used to clamp a float + */ +var ClampBlock = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ClampBlock, _super); + /** + * Creates a new ClampBlock + * @param name defines the block name + */ + function ClampBlock(name) { + var _this = _super.call(this, name) || this; + /** Gets or sets the minimum range */ + _this.minimum = 0.0; + /** Gets or sets the maximum range */ + _this.maximum = 1.0; + _this.registerInput("value", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float); + _this.registerOutput("output", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float); + return _this; + } + /** + * Gets the current class name + * @returns the class name + */ + ClampBlock.prototype.getClassName = function () { + return "ClampBlock"; + }; + Object.defineProperty(ClampBlock.prototype, "value", { + /** + * Gets the value input component + */ + get: function () { + return this._inputs[0]; + }, + enumerable: true, + configurable: true + }); + ClampBlock.prototype._buildBlock = function (state) { + _super.prototype._buildBlock.call(this, state); + var output = this._outputs[0]; + state.compilationString += this._declareOutput(output, state) + (" = clamp(" + this.value.associatedVariableName + ", " + this._writeFloat(this.minimum) + ", " + this._writeFloat(this.maximum) + ");\r\n"); + return this; + }; + return ClampBlock; +}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"])); + + + +/***/ }), + +/***/ "./Materials/Node/Blocks/index.ts": +/*!****************************************!*\ + !*** ./Materials/Node/Blocks/index.ts ***! + \****************************************/ +/*! exports provided: MultiplyBlock, AddBlock, ClampBlock, Vector2TransformBlock, Vector3TransformBlock, Vector4TransformBlock, MatrixMultiplicationBlock, VertexOutputBlock, BonesBlock, InstancesBlock, MorphTargetsBlock, FragmentOutputBlock, AlphaTestBlock, RGBAMergerBlock, RGBMergerBlock, RGBASplitterBlock, RGBSplitterBlock, TextureBlock, ImageProcessingBlock, FogBlock */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Vertex_index__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Vertex/index */ "./Materials/Node/Blocks/Vertex/index.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VertexOutputBlock", function() { return _Vertex_index__WEBPACK_IMPORTED_MODULE_0__["VertexOutputBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BonesBlock", function() { return _Vertex_index__WEBPACK_IMPORTED_MODULE_0__["BonesBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InstancesBlock", function() { return _Vertex_index__WEBPACK_IMPORTED_MODULE_0__["InstancesBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MorphTargetsBlock", function() { return _Vertex_index__WEBPACK_IMPORTED_MODULE_0__["MorphTargetsBlock"]; }); + +/* harmony import */ var _Fragment_index__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Fragment/index */ "./Materials/Node/Blocks/Fragment/index.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FragmentOutputBlock", function() { return _Fragment_index__WEBPACK_IMPORTED_MODULE_1__["FragmentOutputBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AlphaTestBlock", function() { return _Fragment_index__WEBPACK_IMPORTED_MODULE_1__["AlphaTestBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RGBAMergerBlock", function() { return _Fragment_index__WEBPACK_IMPORTED_MODULE_1__["RGBAMergerBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RGBMergerBlock", function() { return _Fragment_index__WEBPACK_IMPORTED_MODULE_1__["RGBMergerBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RGBASplitterBlock", function() { return _Fragment_index__WEBPACK_IMPORTED_MODULE_1__["RGBASplitterBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RGBSplitterBlock", function() { return _Fragment_index__WEBPACK_IMPORTED_MODULE_1__["RGBSplitterBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TextureBlock", function() { return _Fragment_index__WEBPACK_IMPORTED_MODULE_1__["TextureBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ImageProcessingBlock", function() { return _Fragment_index__WEBPACK_IMPORTED_MODULE_1__["ImageProcessingBlock"]; }); + +/* harmony import */ var _Dual_index__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Dual/index */ "./Materials/Node/Blocks/Dual/index.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FogBlock", function() { return _Dual_index__WEBPACK_IMPORTED_MODULE_2__["FogBlock"]; }); + +/* harmony import */ var _multiplyBlock__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./multiplyBlock */ "./Materials/Node/Blocks/multiplyBlock.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MultiplyBlock", function() { return _multiplyBlock__WEBPACK_IMPORTED_MODULE_3__["MultiplyBlock"]; }); + +/* harmony import */ var _addBlock__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./addBlock */ "./Materials/Node/Blocks/addBlock.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AddBlock", function() { return _addBlock__WEBPACK_IMPORTED_MODULE_4__["AddBlock"]; }); + +/* harmony import */ var _clampBlock__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./clampBlock */ "./Materials/Node/Blocks/clampBlock.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ClampBlock", function() { return _clampBlock__WEBPACK_IMPORTED_MODULE_5__["ClampBlock"]; }); + +/* harmony import */ var _vector2TransformBlock__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./vector2TransformBlock */ "./Materials/Node/Blocks/vector2TransformBlock.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Vector2TransformBlock", function() { return _vector2TransformBlock__WEBPACK_IMPORTED_MODULE_6__["Vector2TransformBlock"]; }); + +/* harmony import */ var _vector3TransformBlock__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./vector3TransformBlock */ "./Materials/Node/Blocks/vector3TransformBlock.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Vector3TransformBlock", function() { return _vector3TransformBlock__WEBPACK_IMPORTED_MODULE_7__["Vector3TransformBlock"]; }); + +/* harmony import */ var _vector4TransformBlock__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./vector4TransformBlock */ "./Materials/Node/Blocks/vector4TransformBlock.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Vector4TransformBlock", function() { return _vector4TransformBlock__WEBPACK_IMPORTED_MODULE_8__["Vector4TransformBlock"]; }); + +/* harmony import */ var _matrixMultiplicationBlock__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./matrixMultiplicationBlock */ "./Materials/Node/Blocks/matrixMultiplicationBlock.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MatrixMultiplicationBlock", function() { return _matrixMultiplicationBlock__WEBPACK_IMPORTED_MODULE_9__["MatrixMultiplicationBlock"]; }); + + + + + + + + + + + + + +/***/ }), + +/***/ "./Materials/Node/Blocks/matrixMultiplicationBlock.ts": +/*!************************************************************!*\ + !*** ./Materials/Node/Blocks/matrixMultiplicationBlock.ts ***! + \************************************************************/ +/*! exports provided: MatrixMultiplicationBlock */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MatrixMultiplicationBlock", function() { return MatrixMultiplicationBlock; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts"); +/* harmony import */ var _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/nodeMaterialBlockConnectionPointTypes.ts"); +/* harmony import */ var _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../nodeMaterialBlockTargets */ "./Materials/Node/nodeMaterialBlockTargets.ts"); + + + + +/** + * Block used to multiply two matrices + */ +var MatrixMultiplicationBlock = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](MatrixMultiplicationBlock, _super); + /** + * Creates a new MatrixMultiplicationBlock + * @param name defines the block name + */ + function MatrixMultiplicationBlock(name) { + var _this = _super.call(this, name, _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Vertex) || this; + _this.registerInput("left", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Matrix); + _this.registerInput("right", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Matrix); + _this.registerOutput("output", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Matrix); + return _this; + } + Object.defineProperty(MatrixMultiplicationBlock.prototype, "left", { + /** + * Gets the left operand + */ + get: function () { + return this._inputs[0]; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(MatrixMultiplicationBlock.prototype, "right", { + /** + * Gets the right operand + */ + get: function () { + return this._inputs[1]; + }, + enumerable: true, + configurable: true + }); + /** + * Gets the current class name + * @returns the class name + */ + MatrixMultiplicationBlock.prototype.getClassName = function () { + return "MatrixMultiplicationBlock"; + }; + MatrixMultiplicationBlock.prototype._buildBlock = function (state) { + _super.prototype._buildBlock.call(this, state); + var output = this._outputs[0]; + state.compilationString += this._declareOutput(output, state) + (" = " + this.left.associatedVariableName + " * " + this.right.associatedVariableName + ";\r\n"); + return this; + }; + return MatrixMultiplicationBlock; +}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"])); + + + +/***/ }), + +/***/ "./Materials/Node/Blocks/multiplyBlock.ts": +/*!************************************************!*\ + !*** ./Materials/Node/Blocks/multiplyBlock.ts ***! + \************************************************/ +/*! exports provided: MultiplyBlock */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MultiplyBlock", function() { return MultiplyBlock; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts"); +/* harmony import */ var _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/nodeMaterialBlockConnectionPointTypes.ts"); + + + +/** + * Block used to multiply 2 vector4 + */ +var MultiplyBlock = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](MultiplyBlock, _super); + /** + * Creates a new MultiplyBlock + * @param name defines the block name + */ + function MultiplyBlock(name) { + var _this = _super.call(this, name) || this; + _this.registerInput("left", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4OrColor4); + _this.registerInput("right", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4OrColor4); + _this.registerOutput("output", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4OrColor4); + return _this; + } + /** + * Gets the current class name + * @returns the class name + */ + MultiplyBlock.prototype.getClassName = function () { + return "MultiplyBlock"; + }; + Object.defineProperty(MultiplyBlock.prototype, "left", { + /** + * Gets the left operand input component + */ + get: function () { + return this._inputs[0]; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(MultiplyBlock.prototype, "right", { + /** + * Gets the right operand input component + */ + get: function () { + return this._inputs[1]; + }, + enumerable: true, + configurable: true + }); + MultiplyBlock.prototype._buildBlock = function (state) { + _super.prototype._buildBlock.call(this, state); + var output = this._outputs[0]; + state.compilationString += this._declareOutput(output, state) + (" = " + this.left.associatedVariableName + " * " + this.right.associatedVariableName + ";\r\n"); + return this; + }; + return MultiplyBlock; +}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"])); + + + +/***/ }), + +/***/ "./Materials/Node/Blocks/vector2TransformBlock.ts": +/*!********************************************************!*\ + !*** ./Materials/Node/Blocks/vector2TransformBlock.ts ***! + \********************************************************/ +/*! exports provided: Vector2TransformBlock */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Vector2TransformBlock", function() { return Vector2TransformBlock; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts"); +/* harmony import */ var _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/nodeMaterialBlockConnectionPointTypes.ts"); +/* harmony import */ var _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../nodeMaterialBlockTargets */ "./Materials/Node/nodeMaterialBlockTargets.ts"); + + + + +/** + * Block used to transform a vector2 with a matrix + */ +var Vector2TransformBlock = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Vector2TransformBlock, _super); + /** + * Creates a new Vector2TransformBlock + * @param name defines the block name + */ + function Vector2TransformBlock(name) { + var _this = _super.call(this, name, _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Vertex) || this; + /** + * Defines the value to use to complement Vector2 to transform it to a Vector4 + */ + _this.complementZ = 1; + /** + * Defines the value to use to complement Vector2 to transform it to a Vector4 + */ + _this.complementW = 0; + _this.registerInput("vector", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector2); + _this.registerInput("transform", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Matrix); + _this.registerOutput("output", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector2); + return _this; + } + Object.defineProperty(Vector2TransformBlock.prototype, "vector", { + /** + * Gets the vector input + */ + get: function () { + return this._inputs[0]; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Vector2TransformBlock.prototype, "transform", { + /** + * Gets the matrix transform input + */ + get: function () { + return this._inputs[1]; + }, + enumerable: true, + configurable: true + }); + /** + * Gets the current class name + * @returns the class name + */ + Vector2TransformBlock.prototype.getClassName = function () { + return "Vector2TransformBlock"; + }; + Vector2TransformBlock.prototype._buildBlock = function (state) { + _super.prototype._buildBlock.call(this, state); + var output = this._outputs[0]; + var vector = this.vector; + var transform = this.transform; + state.compilationString += this._declareOutput(output, state) + (" = vec2(" + transform.associatedVariableName + " * vec4(" + vector.associatedVariableName + ", " + this.complementZ + ", " + this.complementW + "));\r\n"); + return this; + }; + return Vector2TransformBlock; +}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"])); + + + +/***/ }), + +/***/ "./Materials/Node/Blocks/vector3TransformBlock.ts": +/*!********************************************************!*\ + !*** ./Materials/Node/Blocks/vector3TransformBlock.ts ***! + \********************************************************/ +/*! exports provided: Vector3TransformBlock */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Vector3TransformBlock", function() { return Vector3TransformBlock; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts"); +/* harmony import */ var _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/nodeMaterialBlockConnectionPointTypes.ts"); +/* harmony import */ var _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../nodeMaterialBlockTargets */ "./Materials/Node/nodeMaterialBlockTargets.ts"); + + + + +/** + * Block used to transform a vector3 with a matrix + */ +var Vector3TransformBlock = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Vector3TransformBlock, _super); + /** + * Creates a new Vector3TransformBlock + * @param name defines the block name + */ + function Vector3TransformBlock(name) { + var _this = _super.call(this, name, _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Vertex) || this; + /** + * Defines the value to use to complement Vector3 to transform it to a Vector4 + */ + _this.complement = 1; + _this.registerInput("vector", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3); + _this.registerInput("transform", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Matrix); + _this.registerOutput("output", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4); + return _this; + } + Object.defineProperty(Vector3TransformBlock.prototype, "vector", { + /** + * Gets the vector input + */ + get: function () { + return this._inputs[0]; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Vector3TransformBlock.prototype, "transform", { + /** + * Gets the matrix transform input + */ + get: function () { + return this._inputs[1]; + }, + enumerable: true, + configurable: true + }); + /** + * Gets the current class name + * @returns the class name + */ + Vector3TransformBlock.prototype.getClassName = function () { + return "Vector3TransformBlock"; + }; + Vector3TransformBlock.prototype._buildBlock = function (state) { + _super.prototype._buildBlock.call(this, state); + var output = this._outputs[0]; + var vector = this.vector; + var transform = this.transform; + state.compilationString += this._declareOutput(output, state) + (" = " + transform.associatedVariableName + " * vec4(" + vector.associatedVariableName + ", " + this.complement + ");\r\n"); + return this; + }; + return Vector3TransformBlock; +}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"])); + + + +/***/ }), + +/***/ "./Materials/Node/Blocks/vector4TransformBlock.ts": +/*!********************************************************!*\ + !*** ./Materials/Node/Blocks/vector4TransformBlock.ts ***! + \********************************************************/ +/*! exports provided: Vector4TransformBlock */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Vector4TransformBlock", function() { return Vector4TransformBlock; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts"); +/* harmony import */ var _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/nodeMaterialBlockConnectionPointTypes.ts"); +/* harmony import */ var _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../nodeMaterialBlockTargets */ "./Materials/Node/nodeMaterialBlockTargets.ts"); + + + + +/** + * Block used to transform a vector4 with a matrix + */ +var Vector4TransformBlock = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Vector4TransformBlock, _super); + /** + * Creates a new Vector4TransformBlock + * @param name defines the block name + */ + function Vector4TransformBlock(name) { + var _this = _super.call(this, name, _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Vertex) || this; + /** + * Defines the value to use to complement Vector3 to transform it to a Vector4 + */ + _this.complementW = 1; + _this.registerInput("vector", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3OrVector4); + _this.registerInput("transform", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Matrix); + _this.registerOutput("output", _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4); + return _this; + } + /** + * Gets the current class name + * @returns the class name + */ + Vector4TransformBlock.prototype.getClassName = function () { + return "Vector4TransformBlock"; + }; + Object.defineProperty(Vector4TransformBlock.prototype, "vector", { + /** + * Gets the vector input + */ + get: function () { + return this._inputs[0]; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Vector4TransformBlock.prototype, "transform", { + /** + * Gets the matrix transform input + */ + get: function () { + return this._inputs[1]; + }, + enumerable: true, + configurable: true + }); + Vector4TransformBlock.prototype._buildBlock = function (state) { + _super.prototype._buildBlock.call(this, state); + var output = this._outputs[0]; + var vector = this.vector; + var transform = this.transform; + if (vector.connectedPoint && vector.connectedPoint.type === _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3) { + state.compilationString += this._declareOutput(output, state) + (" = " + transform.associatedVariableName + " * vec4(" + vector.associatedVariableName + ", " + this._writeFloat(this.complementW) + ");\r\n"); + } + else { + state.compilationString += this._declareOutput(output, state) + (" = " + transform.associatedVariableName + " * " + vector.associatedVariableName + ";\r\n"); + } + return this; + }; + return Vector4TransformBlock; +}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"])); + + + +/***/ }), + +/***/ "./Materials/Node/NodeMaterialBlockConnectionPointMode.ts": +/*!****************************************************************!*\ + !*** ./Materials/Node/NodeMaterialBlockConnectionPointMode.ts ***! + \****************************************************************/ +/*! exports provided: NodeMaterialBlockConnectionPointMode */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialBlockConnectionPointMode", function() { return NodeMaterialBlockConnectionPointMode; }); +/** + * Enum defining the mode of a NodeMaterialBlockConnectionPoint + */ +var NodeMaterialBlockConnectionPointMode; +(function (NodeMaterialBlockConnectionPointMode) { + /** Value is an uniform */ + NodeMaterialBlockConnectionPointMode[NodeMaterialBlockConnectionPointMode["Uniform"] = 0] = "Uniform"; + /** Value is a mesh attribute */ + NodeMaterialBlockConnectionPointMode[NodeMaterialBlockConnectionPointMode["Attribute"] = 1] = "Attribute"; + /** Value is a varying between vertex and fragment shaders */ + NodeMaterialBlockConnectionPointMode[NodeMaterialBlockConnectionPointMode["Varying"] = 2] = "Varying"; + /** Mode is undefined */ + NodeMaterialBlockConnectionPointMode[NodeMaterialBlockConnectionPointMode["Undefined"] = 3] = "Undefined"; +})(NodeMaterialBlockConnectionPointMode || (NodeMaterialBlockConnectionPointMode = {})); + + +/***/ }), + +/***/ "./Materials/Node/Optimizers/index.ts": +/*!********************************************!*\ + !*** ./Materials/Node/Optimizers/index.ts ***! + \********************************************/ +/*! exports provided: NodeMaterialOptimizer */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _nodeMaterialOptimizer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./nodeMaterialOptimizer */ "./Materials/Node/Optimizers/nodeMaterialOptimizer.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialOptimizer", function() { return _nodeMaterialOptimizer__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialOptimizer"]; }); + + + + +/***/ }), + +/***/ "./Materials/Node/Optimizers/nodeMaterialOptimizer.ts": +/*!************************************************************!*\ + !*** ./Materials/Node/Optimizers/nodeMaterialOptimizer.ts ***! + \************************************************************/ +/*! exports provided: NodeMaterialOptimizer */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialOptimizer", function() { return NodeMaterialOptimizer; }); +/** + * Root class for all node material optimizers + */ +var NodeMaterialOptimizer = /** @class */ (function () { + function NodeMaterialOptimizer() { + } + /** + * Function used to optimize a NodeMaterial graph + * @param vertexOutputNodes defines the list of output nodes for the vertex shader + * @param fragmentOutputNodes defines the list of output nodes for the fragment shader + */ + NodeMaterialOptimizer.prototype.optimize = function (vertexOutputNodes, fragmentOutputNodes) { + // Do nothing by default + }; + return NodeMaterialOptimizer; +}()); + + + +/***/ }), + +/***/ "./Materials/Node/index.ts": +/*!*********************************!*\ + !*** ./Materials/Node/index.ts ***! + \*********************************/ +/*! exports provided: NodeMaterialBlockTargets, NodeMaterialBlockConnectionPointTypes, NodeMaterialConnectionPoint, NodeMaterialBlock, NodeMaterialDefines, NodeMaterial, NodeMaterialWellKnownValues, MultiplyBlock, AddBlock, ClampBlock, Vector2TransformBlock, Vector3TransformBlock, Vector4TransformBlock, MatrixMultiplicationBlock, NodeMaterialOptimizer, VertexOutputBlock, BonesBlock, InstancesBlock, MorphTargetsBlock, FragmentOutputBlock, AlphaTestBlock, RGBAMergerBlock, RGBMergerBlock, RGBASplitterBlock, RGBSplitterBlock, TextureBlock, ImageProcessingBlock, FogBlock */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./nodeMaterialBlockTargets */ "./Materials/Node/nodeMaterialBlockTargets.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialBlockTargets", function() { return _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockTargets"]; }); + +/* harmony import */ var _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/nodeMaterialBlockConnectionPointTypes.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialBlockConnectionPointTypes", function() { return _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlockConnectionPointTypes"]; }); + +/* harmony import */ var _nodeMaterialBlockConnectionPoint__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./nodeMaterialBlockConnectionPoint */ "./Materials/Node/nodeMaterialBlockConnectionPoint.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialConnectionPoint", function() { return _nodeMaterialBlockConnectionPoint__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialConnectionPoint"]; }); + +/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialBlock", function() { return _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlock"]; }); + +/* harmony import */ var _nodeMaterial__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./nodeMaterial */ "./Materials/Node/nodeMaterial.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialDefines", function() { return _nodeMaterial__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialDefines"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterial", function() { return _nodeMaterial__WEBPACK_IMPORTED_MODULE_4__["NodeMaterial"]; }); + +/* harmony import */ var _nodeMaterialWellKnownValues__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./nodeMaterialWellKnownValues */ "./Materials/Node/nodeMaterialWellKnownValues.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialWellKnownValues", function() { return _nodeMaterialWellKnownValues__WEBPACK_IMPORTED_MODULE_5__["NodeMaterialWellKnownValues"]; }); + +/* harmony import */ var _Blocks_index__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Blocks/index */ "./Materials/Node/Blocks/index.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MultiplyBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_6__["MultiplyBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AddBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_6__["AddBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ClampBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_6__["ClampBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Vector2TransformBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_6__["Vector2TransformBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Vector3TransformBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_6__["Vector3TransformBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Vector4TransformBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_6__["Vector4TransformBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MatrixMultiplicationBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_6__["MatrixMultiplicationBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VertexOutputBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_6__["VertexOutputBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BonesBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_6__["BonesBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InstancesBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_6__["InstancesBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MorphTargetsBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_6__["MorphTargetsBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FragmentOutputBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_6__["FragmentOutputBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AlphaTestBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_6__["AlphaTestBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RGBAMergerBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_6__["RGBAMergerBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RGBMergerBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_6__["RGBMergerBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RGBASplitterBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_6__["RGBASplitterBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RGBSplitterBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_6__["RGBSplitterBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TextureBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_6__["TextureBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ImageProcessingBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_6__["ImageProcessingBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FogBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_6__["FogBlock"]; }); + +/* harmony import */ var _Optimizers_index__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Optimizers/index */ "./Materials/Node/Optimizers/index.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialOptimizer", function() { return _Optimizers_index__WEBPACK_IMPORTED_MODULE_7__["NodeMaterialOptimizer"]; }); + + + + + + + + + + + +/***/ }), + +/***/ "./Materials/Node/nodeMaterial.ts": +/*!****************************************!*\ + !*** ./Materials/Node/nodeMaterial.ts ***! + \****************************************/ +/*! exports provided: NodeMaterialDefines, NodeMaterial */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialDefines", function() { return NodeMaterialDefines; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NodeMaterial", function() { return NodeMaterial; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _pushMaterial__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../pushMaterial */ "./Materials/pushMaterial.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Engines/engine */ "./Engines/engine.ts"); +/* harmony import */ var _nodeMaterialBuildState__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./nodeMaterialBuildState */ "./Materials/Node/nodeMaterialBuildState.ts"); +/* harmony import */ var _effect__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../effect */ "./Materials/effect.ts"); +/* harmony import */ var _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/nodeMaterialBlockConnectionPointTypes.ts"); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./nodeMaterialBlockTargets */ "./Materials/Node/nodeMaterialBlockTargets.ts"); +/* harmony import */ var _nodeMaterialBuildStateSharedData__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./nodeMaterialBuildStateSharedData */ "./Materials/Node/nodeMaterialBuildStateSharedData.ts"); +/* harmony import */ var _Materials_materialDefines__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../../Materials/materialDefines */ "./Materials/materialDefines.ts"); +/* harmony import */ var _Meshes_buffer__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../../Meshes/buffer */ "./Meshes/buffer.ts"); +/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../../Misc/tools */ "./Misc/tools.ts"); +/* harmony import */ var _Blocks_vector4TransformBlock__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./Blocks/vector4TransformBlock */ "./Materials/Node/Blocks/vector4TransformBlock.ts"); +/* harmony import */ var _Blocks_Vertex_vertexOutputBlock__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./Blocks/Vertex/vertexOutputBlock */ "./Materials/Node/Blocks/Vertex/vertexOutputBlock.ts"); +/* harmony import */ var _Blocks_Fragment_fragmentOutputBlock__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./Blocks/Fragment/fragmentOutputBlock */ "./Materials/Node/Blocks/Fragment/fragmentOutputBlock.ts"); + + + + + + + + + + + + + + + + +/** @hidden */ +var NodeMaterialDefines = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](NodeMaterialDefines, _super); + function NodeMaterialDefines() { + var _this = _super.call(this) || this; + /** BONES */ + _this.NUM_BONE_INFLUENCERS = 0; + _this.BonesPerMesh = 0; + _this.BONETEXTURE = false; + /** MORPH TARGETS */ + _this.MORPHTARGETS = false; + _this.MORPHTARGETS_NORMAL = false; + _this.MORPHTARGETS_TANGENT = false; + _this.NUM_MORPH_INFLUENCERS = 0; + /** IMAGE PROCESSING */ + _this.IMAGEPROCESSING = false; + _this.VIGNETTE = false; + _this.VIGNETTEBLENDMODEMULTIPLY = false; + _this.VIGNETTEBLENDMODEOPAQUE = false; + _this.TONEMAPPING = false; + _this.TONEMAPPING_ACES = false; + _this.CONTRAST = false; + _this.EXPOSURE = false; + _this.COLORCURVES = false; + _this.COLORGRADING = false; + _this.COLORGRADING3D = false; + _this.SAMPLER3DGREENDEPTH = false; + _this.SAMPLER3DBGRMAP = false; + _this.IMAGEPROCESSINGPOSTPROCESS = false; + _this.rebuild(); + return _this; + } + NodeMaterialDefines.prototype.setValue = function (name, value) { + if (this[name] === undefined) { + this._keys.push(name); + } + this[name] = value; + }; + return NodeMaterialDefines; +}(_Materials_materialDefines__WEBPACK_IMPORTED_MODULE_10__["MaterialDefines"])); + +/** + * Class used to create a node based material built by assembling shader blocks + */ +var NodeMaterial = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](NodeMaterial, _super); + /** + * Create a new node based material + * @param name defines the material name + * @param scene defines the hosting scene + * @param options defines creation option + */ + function NodeMaterial(name, scene, options) { + if (options === void 0) { options = {}; } + var _this = _super.call(this, name, scene || _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].LastCreatedScene) || this; + _this._buildId = 0; + _this._buildWasSuccessful = false; + _this._cachedWorldViewMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"](); + _this._cachedWorldViewProjectionMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"](); + _this._textureConnectionPoints = new Array(); + _this._optimizers = new Array(); + _this.BJSNODEMATERIALEDITOR = _this._getGlobalNodeMaterialEditor(); + /** + * Defines the maximum number of lights that can be used in the material + */ + _this.maxSimultaneousLights = 4; + /** + * Observable raised when the material is built + */ + _this.onBuildObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_7__["Observable"](); + /** + * Gets or sets the root nodes of the material vertex shader + */ + _this._vertexOutputNodes = new Array(); + /** + * Gets or sets the root nodes of the material fragment (pixel) shader + */ + _this._fragmentOutputNodes = new Array(); + _this._options = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({ emitComments: false }, options); + // Setup the default processing configuration to the scene. + _this._attachImageProcessingConfiguration(null); + return _this; + } + /** Get the inspector from bundle or global */ + NodeMaterial.prototype._getGlobalNodeMaterialEditor = function () { + // UMD Global name detection from Webpack Bundle UMD Name. + if (typeof NODEEDITOR !== 'undefined') { + return NODEEDITOR; + } + // In case of module let's check the global emitted from the editor entry point. + if (typeof BABYLON !== 'undefined' && typeof BABYLON.NodeEditor !== 'undefined') { + return BABYLON; + } + return undefined; + }; + Object.defineProperty(NodeMaterial.prototype, "options", { + /** Gets or sets options to control the node material overall behavior */ + get: function () { + return this._options; + }, + set: function (options) { + this._options = options; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(NodeMaterial.prototype, "imageProcessingConfiguration", { + /** + * Gets the image processing configuration used either in this material. + */ + get: function () { + return this._imageProcessingConfiguration; + }, + /** + * Sets the Default image processing configuration used either in the this material. + * + * If sets to null, the scene one is in use. + */ + set: function (value) { + this._attachImageProcessingConfiguration(value); + // Ensure the effect will be rebuilt. + this._markAllSubMeshesAsTexturesDirty(); + }, + enumerable: true, + configurable: true + }); + /** + * Gets the current class name of the material e.g. "NodeMaterial" + * @returns the class name + */ + NodeMaterial.prototype.getClassName = function () { + return "NodeMaterial"; + }; + /** + * Attaches a new image processing configuration to the Standard Material. + * @param configuration + */ + NodeMaterial.prototype._attachImageProcessingConfiguration = function (configuration) { + var _this = this; + if (configuration === this._imageProcessingConfiguration) { + return; + } + // Detaches observer. + if (this._imageProcessingConfiguration && this._imageProcessingObserver) { + this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver); + } + // Pick the scene configuration if needed. + if (!configuration) { + this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration; + } + else { + this._imageProcessingConfiguration = configuration; + } + // Attaches observer. + if (this._imageProcessingConfiguration) { + this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function () { + _this._markAllSubMeshesAsImageProcessingDirty(); + }); + } + }; + /** + * Adds a new optimizer to the list of optimizers + * @param optimizer defines the optimizers to add + * @returns the current material + */ + NodeMaterial.prototype.registerOptimizer = function (optimizer) { + var index = this._optimizers.indexOf(optimizer); + if (index > -1) { + return; + } + this._optimizers.push(optimizer); + return this; + }; + /** + * Remove an optimizer from the list of optimizers + * @param optimizer defines the optimizers to remove + * @returns the current material + */ + NodeMaterial.prototype.unregisterOptimizer = function (optimizer) { + var index = this._optimizers.indexOf(optimizer); + if (index === -1) { + return; + } + this._optimizers.splice(index, 1); + return this; + }; + /** + * Add a new block to the list of output nodes + * @param node defines the node to add + * @returns the current material + */ + NodeMaterial.prototype.addOutputNode = function (node) { + if (node.target === null) { + throw "This node is not meant to be an output node. You may want to explicitly set its target value."; + } + if ((node.target & _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_8__["NodeMaterialBlockTargets"].Vertex) !== 0) { + this._addVertexOutputNode(node); + } + if ((node.target & _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_8__["NodeMaterialBlockTargets"].Fragment) !== 0) { + this._addFragmentOutputNode(node); + } + return this; + }; + /** + * Remove a block from the list of root nodes + * @param node defines the node to remove + * @returns the current material + */ + NodeMaterial.prototype.removeOutputNode = function (node) { + if (node.target === null) { + return this; + } + if ((node.target & _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_8__["NodeMaterialBlockTargets"].Vertex) !== 0) { + this._removeVertexOutputNode(node); + } + if ((node.target & _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_8__["NodeMaterialBlockTargets"].Fragment) !== 0) { + this._removeFragmentOutputNode(node); + } + return this; + }; + NodeMaterial.prototype._addVertexOutputNode = function (node) { + if (this._vertexOutputNodes.indexOf(node) !== -1) { + return; + } + node.target = _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_8__["NodeMaterialBlockTargets"].Vertex; + this._vertexOutputNodes.push(node); + return this; + }; + NodeMaterial.prototype._removeVertexOutputNode = function (node) { + var index = this._vertexOutputNodes.indexOf(node); + if (index === -1) { + return; + } + this._vertexOutputNodes.splice(index, 1); + return this; + }; + NodeMaterial.prototype._addFragmentOutputNode = function (node) { + if (this._fragmentOutputNodes.indexOf(node) !== -1) { + return; + } + node.target = _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_8__["NodeMaterialBlockTargets"].Fragment; + this._fragmentOutputNodes.push(node); + return this; + }; + NodeMaterial.prototype._removeFragmentOutputNode = function (node) { + var index = this._fragmentOutputNodes.indexOf(node); + if (index === -1) { + return; + } + this._fragmentOutputNodes.splice(index, 1); + return this; + }; + /** + * Specifies if the material will require alpha blending + * @returns a boolean specifying if alpha blending is needed + */ + NodeMaterial.prototype.needAlphaBlending = function () { + return (this.alpha < 1.0) || this._sharedData.hints.needAlphaBlending; + }; + /** + * Specifies if this material should be rendered in alpha test mode + * @returns a boolean specifying if an alpha test is needed. + */ + NodeMaterial.prototype.needAlphaTesting = function () { + return this._sharedData.hints.needAlphaTesting; + }; + NodeMaterial.prototype._initializeBlock = function (node, state) { + node.initialize(state); + node.autoConfigure(); + for (var _i = 0, _a = node.inputs; _i < _a.length; _i++) { + var inputs = _a[_i]; + var connectedPoint = inputs.connectedPoint; + if (connectedPoint) { + var block = connectedPoint.ownerBlock; + if (block !== node) { + this._initializeBlock(block, state); + } + } + } + }; + NodeMaterial.prototype._resetDualBlocks = function (node, id) { + if (node.target === _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_8__["NodeMaterialBlockTargets"].VertexAndFragment) { + node.buildId = id; + } + for (var _i = 0, _a = node.inputs; _i < _a.length; _i++) { + var inputs = _a[_i]; + var connectedPoint = inputs.connectedPoint; + if (connectedPoint) { + var block = connectedPoint.ownerBlock; + if (block !== node) { + this._resetDualBlocks(block, id); + } + } + } + }; + /** + * Build the material and generates the inner effect + * @param verbose defines if the build should log activity + */ + NodeMaterial.prototype.build = function (verbose) { + if (verbose === void 0) { verbose = false; } + this._buildWasSuccessful = false; + if (this._vertexOutputNodes.length === 0) { + throw "You must define at least one vertexOutputNode"; + } + if (this._fragmentOutputNodes.length === 0) { + throw "You must define at least one fragmentOutputNode"; + } + // Compilation state + this._vertexCompilationState = new _nodeMaterialBuildState__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBuildState"](); + this._vertexCompilationState.target = _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_8__["NodeMaterialBlockTargets"].Vertex; + this._fragmentCompilationState = new _nodeMaterialBuildState__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBuildState"](); + this._fragmentCompilationState.target = _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_8__["NodeMaterialBlockTargets"].Fragment; + // Shared data + this._sharedData = new _nodeMaterialBuildStateSharedData__WEBPACK_IMPORTED_MODULE_9__["NodeMaterialBuildStateSharedData"](); + this._vertexCompilationState.sharedData = this._sharedData; + this._fragmentCompilationState.sharedData = this._sharedData; + this._sharedData.buildId = this._buildId; + this._sharedData.emitComments = this._options.emitComments; + this._sharedData.verbose = verbose; + // Initialize blocks + for (var _i = 0, _a = this._vertexOutputNodes; _i < _a.length; _i++) { + var vertexOutputNode = _a[_i]; + this._initializeBlock(vertexOutputNode, this._vertexCompilationState); + } + for (var _b = 0, _c = this._fragmentOutputNodes; _b < _c.length; _b++) { + var fragmentOutputNode = _c[_b]; + this._initializeBlock(fragmentOutputNode, this._fragmentCompilationState); + } + // Optimize + this.optimize(); + // Vertex + for (var _d = 0, _e = this._vertexOutputNodes; _d < _e.length; _d++) { + var vertexOutputNode = _e[_d]; + vertexOutputNode.build(this._vertexCompilationState); + } + // Fragment + this._fragmentCompilationState._vertexState = this._vertexCompilationState; + for (var _f = 0, _g = this._fragmentOutputNodes; _f < _g.length; _f++) { + var fragmentOutputNode = _g[_f]; + this._resetDualBlocks(fragmentOutputNode, this._buildId - 1); + } + for (var _h = 0, _j = this._fragmentOutputNodes; _h < _j.length; _h++) { + var fragmentOutputNode = _j[_h]; + fragmentOutputNode.build(this._fragmentCompilationState); + } + // Finalize + this._vertexCompilationState.finalize(this._vertexCompilationState); + this._fragmentCompilationState.finalize(this._fragmentCompilationState); + // Textures + this._textureConnectionPoints = + this._sharedData.uniformConnectionPoints.filter(function (u) { return u.type === _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_6__["NodeMaterialBlockConnectionPointTypes"].Texture || u.type === _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_6__["NodeMaterialBlockConnectionPointTypes"].Texture3D; }); + this._buildId++; + // Errors + this._sharedData.emitErrors(); + if (verbose) { + console.log("Vertex shader:"); + console.log(this._vertexCompilationState.compilationString); + console.log("Fragment shader:"); + console.log(this._fragmentCompilationState.compilationString); + } + this._buildWasSuccessful = true; + this.onBuildObservable.notifyObservers(this); + this._markAllSubMeshesAsAllDirty(); + }; + /** + * Runs an otpimization phase to try to improve the shader code + */ + NodeMaterial.prototype.optimize = function () { + for (var _i = 0, _a = this._optimizers; _i < _a.length; _i++) { + var optimizer = _a[_i]; + optimizer.optimize(this._vertexOutputNodes, this._fragmentOutputNodes); + } + }; + NodeMaterial.prototype._prepareDefinesForAttributes = function (mesh, defines) { + if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) { + return; + } + defines._normals = defines._needNormals; + defines._uvs = defines._needUVs; + defines.setValue("NORMAL", (defines._needNormals && mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_11__["VertexBuffer"].NormalKind))); + defines.setValue("TANGENT", mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_11__["VertexBuffer"].TangentKind)); + }; + /** + * Get if the submesh is ready to be used and all its information available. + * Child classes can use it to update shaders + * @param mesh defines the mesh to check + * @param subMesh defines which submesh to check + * @param useInstances specifies that instances should be used + * @returns a boolean indicating that the submesh is ready or not + */ + NodeMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) { + var _this = this; + if (useInstances === void 0) { useInstances = false; } + if (!this._buildWasSuccessful) { + return false; + } + if (subMesh.effect && this.isFrozen) { + if (this._wasPreviouslyReady) { + return true; + } + } + if (!subMesh._materialDefines) { + subMesh._materialDefines = new NodeMaterialDefines(); + } + var scene = this.getScene(); + var defines = subMesh._materialDefines; + if (!this.checkReadyOnEveryCall && subMesh.effect) { + if (defines._renderId === scene.getRenderId()) { + return true; + } + } + var engine = scene.getEngine(); + this._prepareDefinesForAttributes(mesh, defines); + // Check if blocks are ready + if (this._sharedData.blockingBlocks.some(function (b) { return !b.isReady(mesh, _this, defines, useInstances); })) { + return false; + } + // Shared defines + this._sharedData.blocksWithDefines.forEach(function (b) { + b.prepareDefines(mesh, _this, defines, useInstances); + }); + // Need to recompile? + if (defines.isDirty) { + defines.markAsProcessed(); + // Repeatable content generators + this._vertexCompilationState.compilationString = this._vertexCompilationState._builtCompilationString; + this._fragmentCompilationState.compilationString = this._fragmentCompilationState._builtCompilationString; + this._sharedData.repeatableContentBlocks.forEach(function (b) { + b.replaceRepeatableContent(_this._vertexCompilationState, _this._fragmentCompilationState, mesh, defines); + }); + // Uniforms + var mergedUniforms_1 = this._vertexCompilationState.uniforms; + this._fragmentCompilationState.uniforms.forEach(function (u) { + var index = mergedUniforms_1.indexOf(u); + if (index === -1) { + mergedUniforms_1.push(u); + } + }); + // Samplers + var mergedSamplers_1 = this._vertexCompilationState.samplers; + this._fragmentCompilationState.samplers.forEach(function (s) { + var index = mergedSamplers_1.indexOf(s); + if (index === -1) { + mergedSamplers_1.push(s); + } + }); + var fallbacks = new _effect__WEBPACK_IMPORTED_MODULE_5__["EffectFallbacks"](); + this._sharedData.blocksWithFallbacks.forEach(function (b) { + b.provideFallbacks(mesh, fallbacks); + }); + var previousEffect = subMesh.effect; + // Compilation + var join = defines.toString(); + var effect = engine.createEffect({ + vertex: "nodeMaterial" + this._buildId, + fragment: "nodeMaterial" + this._buildId, + vertexSource: this._vertexCompilationState.compilationString, + fragmentSource: this._fragmentCompilationState.compilationString + }, { + attributes: this._vertexCompilationState.attributes, + uniformsNames: mergedUniforms_1, + samplers: mergedSamplers_1, + defines: join, + fallbacks: fallbacks, + onCompiled: this.onCompiled, + onError: this.onError, + indexParameters: { maxSimultaneousLights: this.maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS } + }, engine); + if (effect) { + // Use previous effect while new one is compiling + if (this.allowShaderHotSwapping && previousEffect && !effect.isReady()) { + effect = previousEffect; + defines.markAsUnprocessed(); + } + else { + scene.resetCachedMaterial(); + subMesh.setEffect(effect, defines); + } + } + } + if (!subMesh.effect || !subMesh.effect.isReady()) { + return false; + } + defines._renderId = scene.getRenderId(); + this._wasPreviouslyReady = true; + return true; + }; + /** + * Binds the world matrix to the material + * @param world defines the world transformation matrix + */ + NodeMaterial.prototype.bindOnlyWorldMatrix = function (world) { + var scene = this.getScene(); + if (!this._activeEffect) { + return; + } + var hints = this._sharedData.hints; + if (hints.needWorldViewMatrix) { + world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix); + } + if (hints.needWorldViewProjectionMatrix) { + world.multiplyToRef(scene.getTransformMatrix(), this._cachedWorldViewProjectionMatrix); + } + // Connection points + for (var _i = 0, _a = this._sharedData.uniformConnectionPoints; _i < _a.length; _i++) { + var connectionPoint = _a[_i]; + connectionPoint.transmitWorld(this._activeEffect, world, this._cachedWorldViewMatrix, this._cachedWorldViewProjectionMatrix); + } + }; + /** + * Binds the submesh to this material by preparing the effect and shader to draw + * @param world defines the world transformation matrix + * @param mesh defines the mesh containing the submesh + * @param subMesh defines the submesh to bind the material to + */ + NodeMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) { + var scene = this.getScene(); + var effect = subMesh.effect; + if (!effect) { + return; + } + this._activeEffect = effect; + // Matrices + this.bindOnlyWorldMatrix(world); + var mustRebind = this._mustRebind(scene, effect, mesh.visibility); + if (mustRebind) { + var sharedData = this._sharedData; + if (effect && scene.getCachedMaterial() !== this) { + // Bindable blocks + for (var _i = 0, _a = sharedData.bindableBlocks; _i < _a.length; _i++) { + var block = _a[_i]; + block.bind(effect, this, mesh); + } + // Connection points + for (var _b = 0, _c = sharedData.uniformConnectionPoints; _b < _c.length; _b++) { + var connectionPoint = _c[_b]; + connectionPoint.transmit(effect, scene); + } + } + } + this._afterBind(mesh, this._activeEffect); + }; + /** + * Gets the active textures from the material + * @returns an array of textures + */ + NodeMaterial.prototype.getActiveTextures = function () { + var activeTextures = _super.prototype.getActiveTextures.call(this); + for (var _i = 0, _a = this._textureConnectionPoints; _i < _a.length; _i++) { + var connectionPoint = _a[_i]; + if (connectionPoint.value) { + activeTextures.push(connectionPoint.value); + } + } + return activeTextures; + }; + /** + * Specifies if the material uses a texture + * @param texture defines the texture to check against the material + * @returns a boolean specifying if the material uses the texture + */ + NodeMaterial.prototype.hasTexture = function (texture) { + if (_super.prototype.hasTexture.call(this, texture)) { + return true; + } + for (var _i = 0, _a = this._textureConnectionPoints; _i < _a.length; _i++) { + var connectionPoint = _a[_i]; + if (connectionPoint.value === texture) { + return true; + } + } + return false; + }; + /** + * Disposes the material + * @param forceDisposeEffect specifies if effects should be forcefully disposed + * @param forceDisposeTextures specifies if textures should be forcefully disposed + * @param notBoundToMesh specifies if the material that is being disposed is known to be not bound to any mesh + */ + NodeMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures, notBoundToMesh) { + if (forceDisposeTextures) { + for (var _i = 0, _a = this._textureConnectionPoints; _i < _a.length; _i++) { + var connectionPoint = _a[_i]; + if (connectionPoint.value) { + connectionPoint.value.dispose(); + } + } + } + this._textureConnectionPoints = []; + this.onBuildObservable.clear(); + _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures, notBoundToMesh); + }; + /** Creates the node editor window. */ + NodeMaterial.prototype._createNodeEditor = function () { + this.BJSNODEMATERIALEDITOR = this.BJSNODEMATERIALEDITOR || this._getGlobalNodeMaterialEditor(); + this.BJSNODEMATERIALEDITOR.NodeEditor.Show({ + nodeMaterial: this + }); + }; + /** + * Launch the node material editor + * @param config Define the configuration of the editor + * @return a promise fulfilled when the node editor is visible + */ + NodeMaterial.prototype.edit = function (config) { + var _this = this; + return new Promise(function (resolve, reject) { + if (typeof _this.BJSNODEMATERIALEDITOR == 'undefined') { + var editorUrl = config && config.editorURL ? config.editorURL : NodeMaterial.EditorURL; + // Load editor and add it to the DOM + _Misc_tools__WEBPACK_IMPORTED_MODULE_12__["Tools"].LoadScript(editorUrl, function () { + _this._createNodeEditor(); + resolve(); + }); + } + else { + // Otherwise creates the editor + _this._createNodeEditor(); + resolve(); + } + }); + }; + /** + * Clear the current material + */ + NodeMaterial.prototype.clear = function () { + this._vertexOutputNodes = []; + this._fragmentOutputNodes = []; + }; + /** + * Clear the current material and set it to a default state + */ + NodeMaterial.prototype.setToDefault = function () { + this.clear(); + var worldPos = new _Blocks_vector4TransformBlock__WEBPACK_IMPORTED_MODULE_13__["Vector4TransformBlock"]("worldPos"); + worldPos.vector.setAsAttribute("position"); + worldPos.transform.setAsWellKnownValue(BABYLON.NodeMaterialWellKnownValues.World); + var worldPosdMultipliedByViewProjection = new _Blocks_vector4TransformBlock__WEBPACK_IMPORTED_MODULE_13__["Vector4TransformBlock"]("worldPos * viewProjectionTransform"); + worldPos.connectTo(worldPosdMultipliedByViewProjection); + worldPosdMultipliedByViewProjection.transform.setAsWellKnownValue(BABYLON.NodeMaterialWellKnownValues.ViewProjection); + var vertexOutput = new _Blocks_Vertex_vertexOutputBlock__WEBPACK_IMPORTED_MODULE_14__["VertexOutputBlock"]("vertexOutput"); + worldPosdMultipliedByViewProjection.connectTo(vertexOutput); + // Pixel + var pixelOutput = new _Blocks_Fragment_fragmentOutputBlock__WEBPACK_IMPORTED_MODULE_15__["FragmentOutputBlock"]("pixelOutput"); + pixelOutput.color.value = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color4"](0.8, 0.8, 0.8, 1); + // Add to nodes + this.addOutputNode(vertexOutput); + this.addOutputNode(pixelOutput); + }; + /** Define the URl to load node editor script */ + NodeMaterial.EditorURL = "https://unpkg.com/babylonjs-node-editor@" + _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].Version + "/babylon.nodeEditor.js"; + return NodeMaterial; +}(_pushMaterial__WEBPACK_IMPORTED_MODULE_1__["PushMaterial"])); + + + +/***/ }), + +/***/ "./Materials/Node/nodeMaterialBlock.ts": +/*!*********************************************!*\ + !*** ./Materials/Node/nodeMaterialBlock.ts ***! + \*********************************************/ +/*! exports provided: NodeMaterialBlock */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialBlock", function() { return NodeMaterialBlock; }); +/* harmony import */ var _nodeMaterialBlockConnectionPoint__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./nodeMaterialBlockConnectionPoint */ "./Materials/Node/nodeMaterialBlockConnectionPoint.ts"); +/* harmony import */ var _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./nodeMaterialBlockTargets */ "./Materials/Node/nodeMaterialBlockTargets.ts"); + + +/** + * Defines a block that can be used inside a node based material + */ +var NodeMaterialBlock = /** @class */ (function () { + /** + * Creates a new NodeMaterialBlock + * @param name defines the block name + * @param target defines the target of that block (Vertex by default) + * @param isFinalMerger defines a boolean indicating that this block is an end block (e.g. it is generating a system value). Default is false + */ + function NodeMaterialBlock(name, target, isFinalMerger) { + if (target === void 0) { target = _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlockTargets"].Vertex; } + if (isFinalMerger === void 0) { isFinalMerger = false; } + this._isFinalMerger = false; + /** @hidden */ + this._inputs = new Array(); + /** @hidden */ + this._outputs = new Array(); + this.name = name; + this._target = target; + if (isFinalMerger) { + this._isFinalMerger = true; + } + } + Object.defineProperty(NodeMaterialBlock.prototype, "isFinalMerger", { + /** + * Gets a boolean indicating that this block is an end block (e.g. it is generating a system value) + */ + get: function () { + return this._isFinalMerger; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(NodeMaterialBlock.prototype, "buildId", { + /** + * Gets or sets the build Id + */ + get: function () { + return this._buildId; + }, + set: function (value) { + this._buildId = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(NodeMaterialBlock.prototype, "target", { + /** + * Gets or sets the target of the block + */ + get: function () { + return this._target; + }, + set: function (value) { + if ((this._target & value) !== 0) { + return; + } + this._target = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(NodeMaterialBlock.prototype, "inputs", { + /** + * Gets the list of input points + */ + get: function () { + return this._inputs; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(NodeMaterialBlock.prototype, "outputs", { + /** Gets the list of output points */ + get: function () { + return this._outputs; + }, + enumerable: true, + configurable: true + }); + /** + * Find an input by its name + * @param name defines the name of the input to look for + * @returns the input or null if not found + */ + NodeMaterialBlock.prototype.getInputByName = function (name) { + var filter = this._inputs.filter(function (e) { return e.name === name; }); + if (filter.length) { + return filter[0]; + } + return null; + }; + /** + * Find an output by its name + * @param name defines the name of the outputto look for + * @returns the output or null if not found + */ + NodeMaterialBlock.prototype.getOutputByName = function (name) { + var filter = this._outputs.filter(function (e) { return e.name === name; }); + if (filter.length) { + return filter[0]; + } + return null; + }; + /** + * Initialize the block and prepare the context for build + * @param state defines the state that will be used for the build + */ + NodeMaterialBlock.prototype.initialize = function (state) { + // Do nothing + }; + /** + * Bind data to effect. Will only be called for blocks with isBindable === true + * @param effect defines the effect to bind data to + * @param nodeMaterial defines the hosting NodeMaterial + * @param mesh defines the mesh that will be rendered + */ + NodeMaterialBlock.prototype.bind = function (effect, nodeMaterial, mesh) { + // Do nothing + }; + NodeMaterialBlock.prototype._declareOutput = function (output, state) { + if (output.isVarying) { + return "" + output.associatedVariableName; + } + return state._getGLType(output.type) + " " + output.associatedVariableName; + }; + NodeMaterialBlock.prototype._writeVariable = function (currentPoint) { + var connectionPoint = currentPoint.connectedPoint; + return "" + currentPoint.associatedVariableName + (connectionPoint.swizzle ? "." + connectionPoint.swizzle : ""); + }; + NodeMaterialBlock.prototype._writeFloat = function (value) { + var stringVersion = value.toString(); + if (stringVersion.indexOf(".") === -1) { + stringVersion += ".0"; + } + return "" + stringVersion; + }; + /** + * Gets the current class name e.g. "NodeMaterialBlock" + * @returns the class name + */ + NodeMaterialBlock.prototype.getClassName = function () { + return "NodeMaterialBlock"; + }; + /** + * Register a new input. Must be called inside a block constructor + * @param name defines the connection point name + * @param type defines the connection point type + * @param isOptional defines a boolean indicating that this input can be omitted + * @param target defines the target to use to limit the connection point (will be VetexAndFragment by default) + * @returns the current block + */ + NodeMaterialBlock.prototype.registerInput = function (name, type, isOptional, target) { + if (isOptional === void 0) { isOptional = false; } + var point = new _nodeMaterialBlockConnectionPoint__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialConnectionPoint"](name, this); + point.type = type; + point.isOptional = isOptional; + if (target) { + point.target = target; + } + this._inputs.push(point); + return this; + }; + /** + * Register a new output. Must be called inside a block constructor + * @param name defines the connection point name + * @param type defines the connection point type + * @param target defines the target to use to limit the connection point (will be VetexAndFragment by default) + * @returns the current block + */ + NodeMaterialBlock.prototype.registerOutput = function (name, type, target) { + var point = new _nodeMaterialBlockConnectionPoint__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialConnectionPoint"](name, this); + point.type = type; + if (target) { + point.target = target; + } + this._outputs.push(point); + return this; + }; + /** + * Will return the first available input e.g. the first one which is not an uniform or an attribute + * @param forOutput defines an optional connection point to check compatibility with + * @returns the first available input or null + */ + NodeMaterialBlock.prototype.getFirstAvailableInput = function (forOutput) { + if (forOutput === void 0) { forOutput = null; } + for (var _i = 0, _a = this._inputs; _i < _a.length; _i++) { + var input = _a[_i]; + if (!input.isUniform && !input.isAttribute && !input.connectedPoint) { + if (!forOutput || (forOutput.type & input.type) !== 0) { + return input; + } + } + } + return null; + }; + /** + * Will return the first available output e.g. the first one which is not yet connected and not a varying + * @param forBlock defines an optional block to check compatibility with + * @returns the first available input or null + */ + NodeMaterialBlock.prototype.getFirstAvailableOutput = function (forBlock) { + if (forBlock === void 0) { forBlock = null; } + for (var _i = 0, _a = this._outputs; _i < _a.length; _i++) { + var output = _a[_i]; + if (!forBlock || !forBlock.target || (forBlock.target & output.target) !== 0) { + return output; + } + } + return null; + }; + /** + * Connect current block with another block + * @param other defines the block to connect with + * @param options define the various options to help pick the right connections + * @returns the current block + */ + NodeMaterialBlock.prototype.connectTo = function (other, options) { + if (this._outputs.length === 0) { + return; + } + var output = options && options.output ? this.getOutputByName(options.output) : this.getFirstAvailableOutput(other); + var input = options && options.input ? other.getInputByName(options.input) : other.getFirstAvailableInput(output); + if (output && input) { + output.swizzle = options ? options.outputSwizzle || "" : ""; + output.connectTo(input); + } + else { + throw "Unable to find a compatible match"; + } + return this; + }; + NodeMaterialBlock.prototype._buildBlock = function (state) { + // Empty. Must be defined by child nodes + }; + /** + * Add potential fallbacks if shader compilation fails + * @param mesh defines the mesh to be rendered + * @param fallbacks defines the current prioritized list of fallbacks + */ + NodeMaterialBlock.prototype.provideFallbacks = function (mesh, fallbacks) { + // Do nothing + }; + /** + * Update defines for shader compilation + * @param mesh defines the mesh to be rendered + * @param nodeMaterial defines the node material requesting the update + * @param defines defines the material defines to update + * @param useInstances specifies that instances should be used + */ + NodeMaterialBlock.prototype.prepareDefines = function (mesh, nodeMaterial, defines, useInstances) { + if (useInstances === void 0) { useInstances = false; } + // Do nothing + }; + /** + * Lets the block try to connect some inputs automatically + */ + NodeMaterialBlock.prototype.autoConfigure = function () { + // Do nothing + }; + /** + * Function called when a block is declared as repeatable content generator + * @param vertexShaderState defines the current compilation state for the vertex shader + * @param fragmentShaderState defines the current compilation state for the fragment shader + * @param mesh defines the mesh to be rendered + * @param defines defines the material defines to update + */ + NodeMaterialBlock.prototype.replaceRepeatableContent = function (vertexShaderState, fragmentShaderState, mesh, defines) { + // Do nothing + }; + /** + * Checks if the block is ready + * @param mesh defines the mesh to be rendered + * @param nodeMaterial defines the node material requesting the update + * @param defines defines the material defines to update + * @param useInstances specifies that instances should be used + * @returns true if the block is ready + */ + NodeMaterialBlock.prototype.isReady = function (mesh, nodeMaterial, defines, useInstances) { + if (useInstances === void 0) { useInstances = false; } + return true; + }; + /** + * Compile the current node and generate the shader code + * @param state defines the current compilation state (uniforms, samplers, current string) + * @returns the current block + */ + NodeMaterialBlock.prototype.build = function (state) { + if (this._buildId === state.sharedData.buildId) { + return; + } + // Check if "parent" blocks are compiled + for (var _i = 0, _a = this._inputs; _i < _a.length; _i++) { + var input = _a[_i]; + if (!input.connectedPoint) { + if (!input.isOptional && !input.isAttribute && !input.isUniform) { // Emit a warning + state.sharedData.checks.notConnectedNonOptionalInputs.push(input); + } + continue; + } + if ((input.target & this.target) === 0) { + continue; + } + if ((input.target & state.target) === 0) { + continue; + } + var block_1 = input.connectedPoint.ownerBlock; + if (block_1 && block_1 !== this && block_1.buildId !== state.sharedData.buildId) { + block_1.build(state); + } + } + if (this._buildId === state.sharedData.buildId) { + return; // Need to check again as inputs can be connected multiple time to this endpoint + } + // Logs + if (state.sharedData.verbose) { + console.log((state.target === _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlockTargets"].Vertex ? "Vertex shader" : "Fragment shader") + ": Building " + this.name + " [" + this.getClassName() + "]"); + } + /** Prepare outputs */ + for (var _b = 0, _c = this._outputs; _b < _c.length; _b++) { + var output = _c[_b]; + if ((output.target & this.target) === 0) { + continue; + } + if ((output.target & state.target) === 0) { + continue; + } + output.associatedVariableName = state._getFreeVariableName(output.name); + state._emitVaryings(output); + } + // Build + for (var _d = 0, _e = this._inputs; _d < _e.length; _d++) { + var input = _e[_d]; + if ((input.target & this.target) === 0) { + continue; + } + if ((input.target & state.target) === 0) { + continue; + } + state._emitUniformOrAttributes(input); + } + // Checks final outputs + if (this.isFinalMerger) { + switch (state.target) { + case _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlockTargets"].Vertex: + state.sharedData.checks.emitVertex = true; + break; + case _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlockTargets"].Fragment: + state.sharedData.checks.emitFragment = true; + break; + } + } + if (state.sharedData.emitComments) { + state.compilationString += "\r\n//" + this.name + "\r\n"; + } + this._buildBlock(state); + this._buildId = state.sharedData.buildId; + // Compile connected blocks + for (var _f = 0, _g = this._outputs; _f < _g.length; _f++) { + var output = _g[_f]; + if ((output.target & state.target) === 0) { + continue; + } + for (var _h = 0, _j = output.connectedBlocks; _h < _j.length; _h++) { + var block = _j[_h]; + if (block && (block.target & state.target) !== 0) { + block.build(state); + } + } + } + return this; + }; + return NodeMaterialBlock; +}()); + + + +/***/ }), + +/***/ "./Materials/Node/nodeMaterialBlockConnectionPoint.ts": +/*!************************************************************!*\ + !*** ./Materials/Node/nodeMaterialBlockConnectionPoint.ts ***! + \************************************************************/ +/*! exports provided: NodeMaterialConnectionPoint */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialConnectionPoint", function() { return NodeMaterialConnectionPoint; }); +/* harmony import */ var _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/nodeMaterialBlockConnectionPointTypes.ts"); +/* harmony import */ var _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./nodeMaterialBlockTargets */ "./Materials/Node/nodeMaterialBlockTargets.ts"); +/* harmony import */ var _nodeMaterialWellKnownValues__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./nodeMaterialWellKnownValues */ "./Materials/Node/nodeMaterialWellKnownValues.ts"); +/* harmony import */ var _NodeMaterialBlockConnectionPointMode__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./NodeMaterialBlockConnectionPointMode */ "./Materials/Node/NodeMaterialBlockConnectionPointMode.ts"); + + + + +/** + * Defines a connection point for a block + */ +var NodeMaterialConnectionPoint = /** @class */ (function () { + /** + * Creates a new connection point + * @param name defines the connection point name + * @param ownerBlock defines the block hosting this connection point + */ + function NodeMaterialConnectionPoint(name, ownerBlock) { + this._endpoints = new Array(); + this._mode = _NodeMaterialBlockConnectionPointMode__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointMode"].Undefined; + /** @hidden */ + this._wellKnownValue = null; + /** @hidden */ + this._needToEmitVarying = true; + /** + * Gets or sets the connection point type (default is float) + */ + this.type = _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Float; + /** Gets or sets the target of that connection point */ + this.target = _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlockTargets"].VertexAndFragment; + this._ownerBlock = ownerBlock; + this.name = name; + } + Object.defineProperty(NodeMaterialConnectionPoint.prototype, "value", { + /** + * Gets or sets the value of that point. + * Please note that this value will be ignored if valueCallback is defined + */ + get: function () { + return this._storedValue; + }, + set: function (value) { + this._storedValue = value; + this._mode = _NodeMaterialBlockConnectionPointMode__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointMode"].Uniform; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(NodeMaterialConnectionPoint.prototype, "valueCallback", { + /** + * Gets or sets a callback used to get the value of that point. + * Please note that setting this value will force the connection point to ignore the value property + */ + get: function () { + return this._valueCallback; + }, + set: function (value) { + this._valueCallback = value; + this._mode = _NodeMaterialBlockConnectionPointMode__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointMode"].Uniform; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(NodeMaterialConnectionPoint.prototype, "associatedVariableName", { + /** + * Gets or sets the associated variable name in the shader + */ + get: function () { + if (!this._associatedVariableName && this._connectedPoint) { + return this._connectedPoint.associatedVariableName; + } + return this._associatedVariableName; + }, + set: function (value) { + this._associatedVariableName = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(NodeMaterialConnectionPoint.prototype, "isUniform", { + /** + * Gets or sets a boolean indicating that this connection point is coming from an uniform. + * In this case the connection point name must be the name of the uniform to use. + * Can only be set on inputs + */ + get: function () { + return this._mode === _NodeMaterialBlockConnectionPointMode__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointMode"].Uniform; + }, + set: function (value) { + this._mode = value ? _NodeMaterialBlockConnectionPointMode__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointMode"].Uniform : _NodeMaterialBlockConnectionPointMode__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointMode"].Undefined; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(NodeMaterialConnectionPoint.prototype, "isAttribute", { + /** + * Gets or sets a boolean indicating that this connection point is coming from an attribute. + * In this case the connection point name must be the name of the attribute to use + * Can only be set on inputs + */ + get: function () { + return this._mode === _NodeMaterialBlockConnectionPointMode__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointMode"].Attribute; + }, + set: function (value) { + this._mode = value ? _NodeMaterialBlockConnectionPointMode__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointMode"].Attribute : _NodeMaterialBlockConnectionPointMode__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointMode"].Undefined; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(NodeMaterialConnectionPoint.prototype, "isVarying", { + /** + * Gets or sets a boolean indicating that this connection point is generating a varying variable. + * Can only be set on exit points + */ + get: function () { + return this._mode === _NodeMaterialBlockConnectionPointMode__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointMode"].Varying; + }, + set: function (value) { + this._mode = value ? _NodeMaterialBlockConnectionPointMode__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointMode"].Varying : _NodeMaterialBlockConnectionPointMode__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointMode"].Undefined; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(NodeMaterialConnectionPoint.prototype, "connectedPoint", { + /** Get the other side of the connection (if any) */ + get: function () { + return this._connectedPoint; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(NodeMaterialConnectionPoint.prototype, "ownerBlock", { + /** Get the block that owns this connection point */ + get: function () { + return this._ownerBlock; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(NodeMaterialConnectionPoint.prototype, "sourceBlock", { + /** Get the block connected on the other side of this connection (if any) */ + get: function () { + if (!this._connectedPoint) { + return null; + } + return this._connectedPoint.ownerBlock; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(NodeMaterialConnectionPoint.prototype, "connectedBlocks", { + /** Get the block connected on the endpoints of this connection (if any) */ + get: function () { + if (this._endpoints.length === 0) { + return []; + } + return this._endpoints.map(function (e) { return e.ownerBlock; }); + }, + enumerable: true, + configurable: true + }); + /** + * Gets the current class name e.g. "NodeMaterialConnectionPoint" + * @returns the class name + */ + NodeMaterialConnectionPoint.prototype.getClassName = function () { + return "NodeMaterialConnectionPoint"; + }; + /** + * Set the source of this connection point to a vertex attribute + * @param attributeName defines the attribute name (position, uv, normal, etc...). If not specified it will take the connection point name + * @returns the current connection point + */ + NodeMaterialConnectionPoint.prototype.setAsAttribute = function (attributeName) { + if (attributeName) { + this.name = attributeName; + } + this._mode = _NodeMaterialBlockConnectionPointMode__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointMode"].Attribute; + return this; + }; + /** + * Set the source of this connection point to a well known value + * @param value define the well known value to use (world, view, etc...) or null to switch to manual value + * @returns the current connection point + */ + NodeMaterialConnectionPoint.prototype.setAsWellKnownValue = function (value) { + this.wellKnownValue = value; + return this; + }; + Object.defineProperty(NodeMaterialConnectionPoint.prototype, "isWellKnownValue", { + /** + * Gets a boolean indicating that the current connection point is a well known value + */ + get: function () { + return this._wellKnownValue != null; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(NodeMaterialConnectionPoint.prototype, "wellKnownValue", { + /** + * Gets or sets the current well known value or null if not defined as well know value + */ + get: function () { + return this._wellKnownValue; + }, + set: function (value) { + this._mode = _NodeMaterialBlockConnectionPointMode__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointMode"].Uniform; + this._wellKnownValue = value; + }, + enumerable: true, + configurable: true + }); + NodeMaterialConnectionPoint.prototype._getTypeLength = function (type) { + switch (type) { + case _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Float: + return 1; + case _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Vector2: + return 2; + case _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Vector3: + case _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Color3: + return 3; + case _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Vector4: + case _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Color4: + return 3; + } + return -1; + }; + /** + * Connect this point to another connection point + * @param connectionPoint defines the other connection point + * @returns the current connection point + */ + NodeMaterialConnectionPoint.prototype.connectTo = function (connectionPoint) { + if ((this.type & connectionPoint.type) === 0) { + var fail = true; + // Check swizzle + if (this.swizzle) { + var swizzleLength = this.swizzle.length; + var connectionLength = this._getTypeLength(connectionPoint.type); + if (swizzleLength === connectionLength) { + fail = false; + } + } + if (fail) { + throw "Cannot connect two different connection types."; + } + } + this._endpoints.push(connectionPoint); + connectionPoint._connectedPoint = this; + return this; + }; + /** + * Disconnect this point from one of his endpoint + * @param endpoint defines the other connection point + * @returns the current connection point + */ + NodeMaterialConnectionPoint.prototype.disconnectFrom = function (endpoint) { + var index = this._endpoints.indexOf(endpoint); + if (index === -1) { + return this; + } + this._endpoints.splice(index, 1); + endpoint._connectedPoint = null; + return this; + }; + /** + * When connection point is an uniform, this function will send its value to the effect + * @param effect defines the effect to transmit value to + * @param world defines the world matrix + * @param worldView defines the worldxview matrix + * @param worldViewProjection defines the worldxviewxprojection matrix + */ + NodeMaterialConnectionPoint.prototype.transmitWorld = function (effect, world, worldView, worldViewProjection) { + if (!this._wellKnownValue) { + return; + } + var variableName = this.associatedVariableName; + switch (this._wellKnownValue) { + case _nodeMaterialWellKnownValues__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialWellKnownValues"].World: + effect.setMatrix(variableName, world); + break; + case _nodeMaterialWellKnownValues__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialWellKnownValues"].WorldView: + effect.setMatrix(variableName, worldView); + break; + case _nodeMaterialWellKnownValues__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialWellKnownValues"].WorldViewProjection: + effect.setMatrix(variableName, worldViewProjection); + break; + } + }; + /** + * When connection point is an uniform, this function will send its value to the effect + * @param effect defines the effect to transmit value to + * @param scene defines the hosting scene + */ + NodeMaterialConnectionPoint.prototype.transmit = function (effect, scene) { + var variableName = this.associatedVariableName; + if (this._wellKnownValue) { + switch (this._wellKnownValue) { + case _nodeMaterialWellKnownValues__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialWellKnownValues"].World: + case _nodeMaterialWellKnownValues__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialWellKnownValues"].WorldView: + case _nodeMaterialWellKnownValues__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialWellKnownValues"].WorldViewProjection: + return; + case _nodeMaterialWellKnownValues__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialWellKnownValues"].View: + effect.setMatrix(variableName, scene.getViewMatrix()); + break; + case _nodeMaterialWellKnownValues__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialWellKnownValues"].Projection: + effect.setMatrix(variableName, scene.getProjectionMatrix()); + break; + case _nodeMaterialWellKnownValues__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialWellKnownValues"].ViewProjection: + effect.setMatrix(variableName, scene.getTransformMatrix()); + break; + } + return; + } + var value = this._valueCallback ? this._valueCallback() : this._storedValue; + if (value === null) { + return; + } + switch (this.type) { + case _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Float: + effect.setFloat(variableName, value); + break; + case _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Int: + effect.setInt(variableName, value); + break; + case _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Color3: + effect.setColor3(variableName, value); + break; + case _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Color4: + effect.setDirectColor4(variableName, value); + break; + case _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Vector2: + effect.setVector2(variableName, value); + break; + case _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Vector3: + effect.setVector3(variableName, value); + break; + case _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Color3OrColor4: + effect.setFloat4(variableName, value.r, value.g, value.b, value.a || 1.0); + break; + case _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Vector4OrColor4: + case _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Vector4: + effect.setVector4(variableName, value); + break; + case _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Matrix: + effect.setMatrix(variableName, value); + break; + case _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Texture: + case _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Texture3D: + effect.setTexture(variableName, value); + break; + } + }; + return NodeMaterialConnectionPoint; +}()); + + + +/***/ }), + +/***/ "./Materials/Node/nodeMaterialBlockConnectionPointTypes.ts": +/*!*****************************************************************!*\ + !*** ./Materials/Node/nodeMaterialBlockConnectionPointTypes.ts ***! + \*****************************************************************/ +/*! exports provided: NodeMaterialBlockConnectionPointTypes */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialBlockConnectionPointTypes", function() { return NodeMaterialBlockConnectionPointTypes; }); +/** + * Defines the kind of connection point for node based material + */ +var NodeMaterialBlockConnectionPointTypes; +(function (NodeMaterialBlockConnectionPointTypes) { + /** Float */ + NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["Float"] = 1] = "Float"; + /** Int */ + NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["Int"] = 2] = "Int"; + /** Vector2 */ + NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["Vector2"] = 4] = "Vector2"; + /** Vector3 */ + NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["Vector3"] = 8] = "Vector3"; + /** Vector4 */ + NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["Vector4"] = 16] = "Vector4"; + /** Color3 */ + NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["Color3"] = 32] = "Color3"; + /** Color4 */ + NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["Color4"] = 64] = "Color4"; + /** Matrix */ + NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["Matrix"] = 128] = "Matrix"; + /** Texture */ + NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["Texture"] = 256] = "Texture"; + /** Texture3D */ + NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["Texture3D"] = 512] = "Texture3D"; + /** Vector3 or Color3 */ + NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["Vector3OrColor3"] = 40] = "Vector3OrColor3"; + /** Vector3 or Vector4 */ + NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["Vector3OrVector4"] = 24] = "Vector3OrVector4"; + /** Vector4 or Color4 */ + NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["Vector4OrColor4"] = 80] = "Vector4OrColor4"; + /** Color3 or Color4 */ + NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["Color3OrColor4"] = 96] = "Color3OrColor4"; + /** Vector3 or Color3 */ + NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["Vector3OrColor3OrVector4OrColor4"] = 120] = "Vector3OrColor3OrVector4OrColor4"; +})(NodeMaterialBlockConnectionPointTypes || (NodeMaterialBlockConnectionPointTypes = {})); + + +/***/ }), + +/***/ "./Materials/Node/nodeMaterialBlockTargets.ts": +/*!****************************************************!*\ + !*** ./Materials/Node/nodeMaterialBlockTargets.ts ***! + \****************************************************/ +/*! exports provided: NodeMaterialBlockTargets */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialBlockTargets", function() { return NodeMaterialBlockTargets; }); +/** + * Enum used to define the target of a block + */ +var NodeMaterialBlockTargets; +(function (NodeMaterialBlockTargets) { + /** Vertex shader */ + NodeMaterialBlockTargets[NodeMaterialBlockTargets["Vertex"] = 1] = "Vertex"; + /** Fragment shader */ + NodeMaterialBlockTargets[NodeMaterialBlockTargets["Fragment"] = 2] = "Fragment"; + /** Vertex and Fragment */ + NodeMaterialBlockTargets[NodeMaterialBlockTargets["VertexAndFragment"] = 3] = "VertexAndFragment"; +})(NodeMaterialBlockTargets || (NodeMaterialBlockTargets = {})); + + +/***/ }), + +/***/ "./Materials/Node/nodeMaterialBuildState.ts": +/*!**************************************************!*\ + !*** ./Materials/Node/nodeMaterialBuildState.ts ***! + \**************************************************/ +/*! exports provided: NodeMaterialBuildState */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialBuildState", function() { return NodeMaterialBuildState; }); +/* harmony import */ var _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/nodeMaterialBlockConnectionPointTypes.ts"); +/* harmony import */ var _nodeMaterialWellKnownValues__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./nodeMaterialWellKnownValues */ "./Materials/Node/nodeMaterialWellKnownValues.ts"); +/* harmony import */ var _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./nodeMaterialBlockTargets */ "./Materials/Node/nodeMaterialBlockTargets.ts"); +/* harmony import */ var _effect__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../effect */ "./Materials/effect.ts"); + + + + +/** + * Class used to store node based material build state + */ +var NodeMaterialBuildState = /** @class */ (function () { + function NodeMaterialBuildState() { + /** + * Gets the list of emitted attributes + */ + this.attributes = new Array(); + /** + * Gets the list of emitted uniforms + */ + this.uniforms = new Array(); + /** + * Gets the list of emitted samplers + */ + this.samplers = new Array(); + /** + * Gets the list of emitted functions + */ + this.functions = {}; + this._attributeDeclaration = ""; + this._uniformDeclaration = ""; + this._samplerDeclaration = ""; + this._varyingTransfer = ""; + this._repeatableContentAnchorIndex = 0; + /** @hidden */ + this._builtCompilationString = ""; + /** + * Gets the emitted compilation strings + */ + this.compilationString = ""; + } + /** + * Finalize the compilation strings + * @param state defines the current compilation state + */ + NodeMaterialBuildState.prototype.finalize = function (state) { + var emitComments = state.sharedData.emitComments; + var isFragmentMode = (this.target === _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockTargets"].Fragment); + this.compilationString = "\r\n" + (emitComments ? "//Entry point\r\n" : "") + "void main(void) {\r\n" + this.compilationString; + var functionCode = ""; + for (var functionName in this.functions) { + functionCode += this.functions[functionName] + "\r\n"; + } + this.compilationString = "\r\n" + functionCode + "\r\n" + this.compilationString; + if (!isFragmentMode && this._varyingTransfer) { + this.compilationString = this.compilationString + "\r\n" + this._varyingTransfer; + } + this.compilationString = this.compilationString + "\r\n}"; + if (this.sharedData.varyingDeclaration) { + this.compilationString = "\r\n" + (emitComments ? "//Varyings\r\n" : "") + this.sharedData.varyingDeclaration + "\r\n" + this.compilationString; + } + if (this._samplerDeclaration) { + this.compilationString = "\r\n" + (emitComments ? "//Samplers\r\n" : "") + this._samplerDeclaration + "\r\n" + this.compilationString; + } + if (this._uniformDeclaration) { + this.compilationString = "\r\n" + (emitComments ? "//Uniforms\r\n" : "") + this._uniformDeclaration + "\r\n" + this.compilationString; + } + if (this._attributeDeclaration && !isFragmentMode) { + this.compilationString = "\r\n" + (emitComments ? "//Attributes\r\n" : "") + this._attributeDeclaration + "\r\n" + this.compilationString; + } + this._builtCompilationString = this.compilationString; + }; + Object.defineProperty(NodeMaterialBuildState.prototype, "_repeatableContentAnchor", { + /** @hidden */ + get: function () { + return "###___ANCHOR" + this._repeatableContentAnchorIndex++ + "___###"; + }, + enumerable: true, + configurable: true + }); + /** @hidden */ + NodeMaterialBuildState.prototype._getFreeVariableName = function (prefix) { + if (this.sharedData.variableNames[prefix] === undefined) { + this.sharedData.variableNames[prefix] = 0; + // Check reserved words + if (prefix === "output" || prefix === "texture") { + return prefix + this.sharedData.variableNames[prefix]; + } + return prefix; + } + else { + this.sharedData.variableNames[prefix]++; + } + return prefix + this.sharedData.variableNames[prefix]; + }; + /** @hidden */ + NodeMaterialBuildState.prototype._getFreeDefineName = function (prefix) { + if (this.sharedData.defineNames[prefix] === undefined) { + this.sharedData.defineNames[prefix] = 0; + } + else { + this.sharedData.defineNames[prefix]++; + } + return prefix + this.sharedData.defineNames[prefix]; + }; + /** @hidden */ + NodeMaterialBuildState.prototype._excludeVariableName = function (name) { + this.sharedData.variableNames[name] = 0; + }; + /** @hidden */ + NodeMaterialBuildState.prototype._getGLType = function (type) { + switch (type) { + case _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Float: + return "float"; + case _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Int: + return "int"; + case _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Vector2: + return "vec2"; + case _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Color3: + case _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Vector3: + case _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Vector3OrColor3: + return "vec3"; + case _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Color4: + case _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Vector4: + case _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Vector4OrColor4: + case _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Vector3OrVector4: + case _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Color3OrColor4: + return "vec4"; + case _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Matrix: + return "mat4"; + case _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Texture: + return "sampler2D"; + case _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Texture3D: + return "sampler3D"; + } + return ""; + }; + /** @hidden */ + NodeMaterialBuildState.prototype._emitFunction = function (name, code, comments) { + if (this.functions[name]) { + return; + } + if (this.sharedData.emitComments) { + code = comments + "\r\n" + code; + } + this.functions[name] = code; + }; + /** @hidden */ + NodeMaterialBuildState.prototype._emitCodeFromInclude = function (includeName, comments, options) { + var code = _effect__WEBPACK_IMPORTED_MODULE_3__["Effect"].IncludesShadersStore[includeName] + "\r\n"; + if (this.sharedData.emitComments) { + code = comments + "\r\n" + code; + } + if (!options) { + return code; + } + if (options.replaceStrings) { + for (var index = 0; index < options.replaceStrings.length; index++) { + var replaceString = options.replaceStrings[index]; + code = code.replace(replaceString.search, replaceString.replace); + } + } + return code; + }; + /** @hidden */ + NodeMaterialBuildState.prototype._emitFunctionFromInclude = function (includeName, comments, options) { + if (this.functions[includeName]) { + return; + } + if (!options || (!options.removeAttributes && !options.removeUniforms && !options.removeVaryings && !options.removeIfDef && !options.replaceStrings)) { + if (options && options.repeatKey) { + this.functions[includeName] = "#include<" + includeName + ">[0.." + options.repeatKey + "]\r\n"; + } + else { + this.functions[includeName] = "#include<" + includeName + ">\r\n"; + } + if (this.sharedData.emitComments) { + this.functions[includeName] = comments + "\r\n" + this.functions[includeName]; + } + return; + } + this.functions[includeName] = _effect__WEBPACK_IMPORTED_MODULE_3__["Effect"].IncludesShadersStore[includeName]; + if (this.sharedData.emitComments) { + this.functions[includeName] = comments + "\r\n" + this.functions[includeName]; + } + if (options.removeIfDef) { + this.functions[includeName] = this.functions[includeName].replace(/^\s*?#ifdef.+$/gm, ""); + this.functions[includeName] = this.functions[includeName].replace(/^\s*?#endif.*$/gm, ""); + this.functions[includeName] = this.functions[includeName].replace(/^\s*?#else.*$/gm, ""); + this.functions[includeName] = this.functions[includeName].replace(/^\s*?#elif.*$/gm, ""); + } + if (options.removeAttributes) { + this.functions[includeName] = this.functions[includeName].replace(/^\s*?attribute.+$/gm, ""); + } + if (options.removeUniforms) { + this.functions[includeName] = this.functions[includeName].replace(/^\s*?uniform.+$/gm, ""); + } + if (options.removeVaryings) { + this.functions[includeName] = this.functions[includeName].replace(/^\s*?varying.+$/gm, ""); + } + if (options.replaceStrings) { + for (var index = 0; index < options.replaceStrings.length; index++) { + var replaceString = options.replaceStrings[index]; + this.functions[includeName] = this.functions[includeName].replace(replaceString.search, replaceString.replace); + } + } + }; + /** @hidden */ + NodeMaterialBuildState.prototype._emitVaryings = function (point, define, force, fromFragment, replacementName) { + if (define === void 0) { define = ""; } + if (force === void 0) { force = false; } + if (fromFragment === void 0) { fromFragment = false; } + if (replacementName === void 0) { replacementName = ""; } + var name = replacementName || point.associatedVariableName; + if (point.isVarying || force) { + if (this.sharedData.varyings.indexOf(name) !== -1) { + return; + } + this.sharedData.varyings.push(name); + if (define) { + this.sharedData.varyingDeclaration += "#ifdef " + define + "\r\n"; + } + this.sharedData.varyingDeclaration += "varying " + this._getGLType(point.type) + " " + name + ";\r\n"; + if (define) { + this.sharedData.varyingDeclaration += "#endif\r\n"; + } + if (this.target === _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockTargets"].Vertex && fromFragment) { + if (define) { + this.sharedData.varyingDeclaration += "#ifdef " + define + "\r\n"; + } + this._varyingTransfer += name + " = " + point.name + ";\r\n"; + if (define) { + this.sharedData.varyingDeclaration += "#endif\r\n"; + } + } + } + }; + NodeMaterialBuildState.prototype._emitDefine = function (define) { + if (define[0] === "!") { + return "#ifndef " + define.substring(1) + "\r\n"; + } + return "#ifdef " + define + "\r\n"; + }; + /** @hidden */ + NodeMaterialBuildState.prototype._emitUniformOrAttributes = function (point, define) { + define = define || point.define; + // Samplers + if (point.type === _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Texture) { + point.name = this._getFreeVariableName(point.name); + point.associatedVariableName = point.name; + if (this.samplers.indexOf(point.name) !== -1) { + return; + } + this.samplers.push(point.name); + if (define) { + this._uniformDeclaration += this._emitDefine(define); + } + this._samplerDeclaration += "uniform " + this._getGLType(point.type) + " " + point.name + ";\r\n"; + if (define) { + this._uniformDeclaration += "#endif\r\n"; + } + this.sharedData.uniformConnectionPoints.push(point); + return; + } + if (!point.isUniform && !point.isAttribute) { + return; + } + // Uniforms + if (point.isUniform) { + if (!point.associatedVariableName) { + point.associatedVariableName = this._getFreeVariableName(point.name); + } + if (this.uniforms.indexOf(point.associatedVariableName) !== -1) { + return; + } + this.uniforms.push(point.associatedVariableName); + if (define) { + this._uniformDeclaration += this._emitDefine(define); + } + this._uniformDeclaration += "uniform " + this._getGLType(point.type) + " " + point.associatedVariableName + ";\r\n"; + if (define) { + this._uniformDeclaration += "#endif\r\n"; + } + // well known + var hints = this.sharedData.hints; + if (point._wellKnownValue !== null) { + switch (point._wellKnownValue) { + case _nodeMaterialWellKnownValues__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialWellKnownValues"].WorldView: + hints.needWorldViewMatrix = true; + break; + case _nodeMaterialWellKnownValues__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialWellKnownValues"].WorldViewProjection: + hints.needWorldViewProjectionMatrix = true; + break; + } + } + this.sharedData.uniformConnectionPoints.push(point); + return; + } + // Attribute + if (point.isAttribute) { + point.associatedVariableName = point.name; + if (this.target === _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockTargets"].Fragment) { // Attribute for fragment need to be carried over by varyings + this._vertexState._emitUniformOrAttributes(point); + if (point._needToEmitVarying) { + this._vertexState._emitVaryings(point, undefined, true, true, "v" + point.associatedVariableName); + point.associatedVariableName = "v" + point.associatedVariableName; + } + return; + } + if (this.attributes.indexOf(point.associatedVariableName) !== -1) { + return; + } + this.attributes.push(point.associatedVariableName); + if (define) { + this._attributeDeclaration += this._emitDefine(define); + } + this._attributeDeclaration += "attribute " + this._getGLType(point.type) + " " + point.associatedVariableName + ";\r\n"; + if (define) { + this._attributeDeclaration += "#endif\r\n"; + } + } + }; + return NodeMaterialBuildState; +}()); + + + +/***/ }), + +/***/ "./Materials/Node/nodeMaterialBuildStateSharedData.ts": +/*!************************************************************!*\ + !*** ./Materials/Node/nodeMaterialBuildStateSharedData.ts ***! + \************************************************************/ +/*! exports provided: NodeMaterialBuildStateSharedData */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialBuildStateSharedData", function() { return NodeMaterialBuildStateSharedData; }); +/** + * Class used to store shared data between 2 NodeMaterialBuildState + */ +var NodeMaterialBuildStateSharedData = /** @class */ (function () { + /** Creates a new shared data */ + function NodeMaterialBuildStateSharedData() { + /** + * Gets the list of emitted varyings + */ + this.varyings = new Array(); + /** + * Gets the varying declaration string + */ + this.varyingDeclaration = ""; + /** + * Uniform connection points + */ + this.uniformConnectionPoints = new Array(); + /** + * Bindable blocks (Blocks that need to set data to the effect) + */ + this.bindableBlocks = new Array(); + /** + * List of blocks that can provide a compilation fallback + */ + this.blocksWithFallbacks = new Array(); + /** + * List of blocks that can provide a define update + */ + this.blocksWithDefines = new Array(); + /** + * List of blocks that can provide a repeatable content + */ + this.repeatableContentBlocks = new Array(); + /** + * List of blocks that can block the isReady function for the material + */ + this.blockingBlocks = new Array(); + /** List of emitted variables */ + this.variableNames = {}; + /** List of emitted defines */ + this.defineNames = {}; + /** + * Gets the compilation hints emitted at compilation time + */ + this.hints = { + needWorldViewMatrix: false, + needWorldViewProjectionMatrix: false, + needAlphaBlending: false, + needAlphaTesting: false + }; + /** + * List of compilation checks + */ + this.checks = { + emitVertex: false, + emitFragment: false, + notConnectedNonOptionalInputs: new Array() + }; + // Exclude usual attributes from free variable names + this.variableNames["position"] = 0; + this.variableNames["normal"] = 0; + this.variableNames["tangent"] = 0; + this.variableNames["uv"] = 0; + this.variableNames["uv2"] = 0; + this.variableNames["uv3"] = 0; + this.variableNames["uv4"] = 0; + this.variableNames["uv4"] = 0; + this.variableNames["uv5"] = 0; + this.variableNames["uv6"] = 0; + this.variableNames["color"] = 0; + this.variableNames["matricesIndices"] = 0; + this.variableNames["matricesWeights"] = 0; + this.variableNames["matricesIndicesExtra"] = 0; + this.variableNames["matricesWeightsExtra"] = 0; + // Exclude defines + this.defineNames["MAINUV0"] = 0; + this.defineNames["MAINUV1"] = 0; + this.defineNames["MAINUV2"] = 0; + this.defineNames["MAINUV3"] = 0; + this.defineNames["MAINUV4"] = 0; + this.defineNames["MAINUV5"] = 0; + this.defineNames["MAINUV6"] = 0; + this.defineNames["MAINUV7"] = 0; + } + /** + * Emits console errors and exceptions if there is a failing check + */ + NodeMaterialBuildStateSharedData.prototype.emitErrors = function () { + var shouldThrowError = false; + if (!this.checks.emitVertex) { + shouldThrowError = true; + console.error("NodeMaterial does not have a vertex output. You need to at least add a block that generates a glPosition value."); + } + if (!this.checks.emitFragment) { + shouldThrowError = true; + console.error("NodeMaterial does not have a fragment output. You need to at least add a block that generates a glFragColor value."); + } + for (var _i = 0, _a = this.checks.notConnectedNonOptionalInputs; _i < _a.length; _i++) { + var notConnectedInput = _a[_i]; + shouldThrowError = true; + console.error("input " + notConnectedInput.name + " from block " + notConnectedInput.ownerBlock.name + "[" + notConnectedInput.ownerBlock.getClassName() + "] is not connected and is not optional."); + } + if (shouldThrowError) { + throw "Build of NodeMaterial failed."; + } + }; + return NodeMaterialBuildStateSharedData; +}()); + + + +/***/ }), + +/***/ "./Materials/Node/nodeMaterialWellKnownValues.ts": +/*!*******************************************************!*\ + !*** ./Materials/Node/nodeMaterialWellKnownValues.ts ***! + \*******************************************************/ +/*! exports provided: NodeMaterialWellKnownValues */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialWellKnownValues", function() { return NodeMaterialWellKnownValues; }); +/** + * Enum used to define well known values e.g. values automatically provided by the system + */ +var NodeMaterialWellKnownValues; +(function (NodeMaterialWellKnownValues) { + /** World */ + NodeMaterialWellKnownValues[NodeMaterialWellKnownValues["World"] = 1] = "World"; + /** View */ + NodeMaterialWellKnownValues[NodeMaterialWellKnownValues["View"] = 2] = "View"; + /** Projection */ + NodeMaterialWellKnownValues[NodeMaterialWellKnownValues["Projection"] = 3] = "Projection"; + /** ViewProjection */ + NodeMaterialWellKnownValues[NodeMaterialWellKnownValues["ViewProjection"] = 4] = "ViewProjection"; + /** WorldView */ + NodeMaterialWellKnownValues[NodeMaterialWellKnownValues["WorldView"] = 5] = "WorldView"; + /** WorldViewProjection */ + NodeMaterialWellKnownValues[NodeMaterialWellKnownValues["WorldViewProjection"] = 6] = "WorldViewProjection"; + /** Will be filled by the block itself */ + NodeMaterialWellKnownValues[NodeMaterialWellKnownValues["Automatic"] = 7] = "Automatic"; +})(NodeMaterialWellKnownValues || (NodeMaterialWellKnownValues = {})); + + +/***/ }), + +/***/ "./Materials/PBR/index.ts": +/*!********************************!*\ + !*** ./Materials/PBR/index.ts ***! + \********************************/ +/*! exports provided: PBRMaterialDefines, PBRBaseMaterial, PBRBaseSimpleMaterial, PBRMaterial, PBRMetallicRoughnessMaterial, PBRSpecularGlossinessMaterial */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./pbrBaseMaterial */ "./Materials/PBR/pbrBaseMaterial.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRMaterialDefines", function() { return _pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_0__["PBRMaterialDefines"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRBaseMaterial", function() { return _pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_0__["PBRBaseMaterial"]; }); + +/* harmony import */ var _pbrBaseSimpleMaterial__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./pbrBaseSimpleMaterial */ "./Materials/PBR/pbrBaseSimpleMaterial.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRBaseSimpleMaterial", function() { return _pbrBaseSimpleMaterial__WEBPACK_IMPORTED_MODULE_1__["PBRBaseSimpleMaterial"]; }); + +/* harmony import */ var _pbrMaterial__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./pbrMaterial */ "./Materials/PBR/pbrMaterial.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRMaterial", function() { return _pbrMaterial__WEBPACK_IMPORTED_MODULE_2__["PBRMaterial"]; }); + +/* harmony import */ var _pbrMetallicRoughnessMaterial__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./pbrMetallicRoughnessMaterial */ "./Materials/PBR/pbrMetallicRoughnessMaterial.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRMetallicRoughnessMaterial", function() { return _pbrMetallicRoughnessMaterial__WEBPACK_IMPORTED_MODULE_3__["PBRMetallicRoughnessMaterial"]; }); + +/* harmony import */ var _pbrSpecularGlossinessMaterial__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./pbrSpecularGlossinessMaterial */ "./Materials/PBR/pbrSpecularGlossinessMaterial.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRSpecularGlossinessMaterial", function() { return _pbrSpecularGlossinessMaterial__WEBPACK_IMPORTED_MODULE_4__["PBRSpecularGlossinessMaterial"]; }); + + + + + + + + +/***/ }), + +/***/ "./Materials/PBR/pbrAnisotropicConfiguration.ts": +/*!******************************************************!*\ + !*** ./Materials/PBR/pbrAnisotropicConfiguration.ts ***! + \******************************************************/ +/*! exports provided: PBRAnisotropicConfiguration */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PBRAnisotropicConfiguration", function() { return PBRAnisotropicConfiguration; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _Meshes_buffer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Meshes/buffer */ "./Meshes/buffer.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Materials_materialFlags__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Materials/materialFlags */ "./Materials/materialFlags.ts"); +/* harmony import */ var _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Materials/materialHelper */ "./Materials/materialHelper.ts"); + + + + + + +/** + * Define the code related to the anisotropic parameters of the pbr material. + */ +var PBRAnisotropicConfiguration = /** @class */ (function () { + /** + * Instantiate a new istance of anisotropy configuration. + * @param markAllSubMeshesAsTexturesDirty Callback to flag the material to dirty + */ + function PBRAnisotropicConfiguration(markAllSubMeshesAsTexturesDirty) { + this._isEnabled = false; + /** + * Defines if the anisotropy is enabled in the material. + */ + this.isEnabled = false; + /** + * Defines the anisotropy strength (between 0 and 1) it defaults to 1. + */ + this.intensity = 1; + /** + * Defines if the effect is along the tangents, bitangents or in between. + * By default, the effect is "strectching" the highlights along the tangents. + */ + this.direction = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector2"](1, 0); + this._texture = null; + /** + * Stores the anisotropy values in a texture. + * rg is direction (like normal from -1 to 1) + * b is a intensity + */ + this.texture = null; + this._internalMarkAllSubMeshesAsTexturesDirty = markAllSubMeshesAsTexturesDirty; + } + /** @hidden */ + PBRAnisotropicConfiguration.prototype._markAllSubMeshesAsTexturesDirty = function () { + this._internalMarkAllSubMeshesAsTexturesDirty(); + }; + /** + * Specifies that the submesh is ready to be used. + * @param defines the list of "defines" to update. + * @param scene defines the scene the material belongs to. + * @returns - boolean indicating that the submesh is ready or not. + */ + PBRAnisotropicConfiguration.prototype.isReadyForSubMesh = function (defines, scene) { + if (defines._areTexturesDirty) { + if (scene.texturesEnabled) { + if (this._texture && _Materials_materialFlags__WEBPACK_IMPORTED_MODULE_4__["MaterialFlags"].AnisotropicTextureEnabled) { + if (!this._texture.isReadyOrNotBlocking()) { + return false; + } + } + } + } + return true; + }; + /** + * Checks to see if a texture is used in the material. + * @param defines the list of "defines" to update. + * @param mesh the mesh we are preparing the defines for. + * @param scene defines the scene the material belongs to. + */ + PBRAnisotropicConfiguration.prototype.prepareDefines = function (defines, mesh, scene) { + if (this._isEnabled) { + defines.ANISOTROPIC = this._isEnabled; + if (this._isEnabled && !mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_2__["VertexBuffer"].TangentKind)) { + defines._needUVs = true; + defines.MAINUV1 = true; + } + if (defines._areTexturesDirty) { + if (scene.texturesEnabled) { + if (this._texture && _Materials_materialFlags__WEBPACK_IMPORTED_MODULE_4__["MaterialFlags"].AnisotropicTextureEnabled) { + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_5__["MaterialHelper"].PrepareDefinesForMergedUV(this._texture, defines, "ANISOTROPIC_TEXTURE"); + } + else { + defines.ANISOTROPIC_TEXTURE = false; + } + } + } + } + else { + defines.ANISOTROPIC = false; + defines.ANISOTROPIC_TEXTURE = false; + } + }; + /** + * Binds the material data. + * @param uniformBuffer defines the Uniform buffer to fill in. + * @param scene defines the scene the material belongs to. + * @param isFrozen defines wether the material is frozen or not. + */ + PBRAnisotropicConfiguration.prototype.bindForSubMesh = function (uniformBuffer, scene, isFrozen) { + if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) { + if (this._texture && _Materials_materialFlags__WEBPACK_IMPORTED_MODULE_4__["MaterialFlags"].AnisotropicTextureEnabled) { + uniformBuffer.updateFloat2("vAnisotropyInfos", this._texture.coordinatesIndex, this._texture.level); + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_5__["MaterialHelper"].BindTextureMatrix(this._texture, uniformBuffer, "anisotropy"); + } + // Anisotropy + uniformBuffer.updateFloat3("vAnisotropy", this.direction.x, this.direction.y, this.intensity); + } + // Textures + if (scene.texturesEnabled) { + if (this._texture && _Materials_materialFlags__WEBPACK_IMPORTED_MODULE_4__["MaterialFlags"].AnisotropicTextureEnabled) { + uniformBuffer.setTexture("anisotropySampler", this._texture); + } + } + }; + /** + * Checks to see if a texture is used in the material. + * @param texture - Base texture to use. + * @returns - Boolean specifying if a texture is used in the material. + */ + PBRAnisotropicConfiguration.prototype.hasTexture = function (texture) { + if (this._texture === texture) { + return true; + } + return false; + }; + /** + * Returns an array of the actively used textures. + * @param activeTextures Array of BaseTextures + */ + PBRAnisotropicConfiguration.prototype.getActiveTextures = function (activeTextures) { + if (this._texture) { + activeTextures.push(this._texture); + } + }; + /** + * Returns the animatable textures. + * @param animatables Array of animatable textures. + */ + PBRAnisotropicConfiguration.prototype.getAnimatables = function (animatables) { + if (this._texture && this._texture.animations && this._texture.animations.length > 0) { + animatables.push(this._texture); + } + }; + /** + * Disposes the resources of the material. + * @param forceDisposeTextures - Forces the disposal of all textures. + */ + PBRAnisotropicConfiguration.prototype.dispose = function (forceDisposeTextures) { + if (forceDisposeTextures) { + if (this._texture) { + this._texture.dispose(); + } + } + }; + /** + * Get the current class name of the texture useful for serialization or dynamic coding. + * @returns "PBRAnisotropicConfiguration" + */ + PBRAnisotropicConfiguration.prototype.getClassName = function () { + return "PBRAnisotropicConfiguration"; + }; + /** + * Add fallbacks to the effect fallbacks list. + * @param defines defines the Base texture to use. + * @param fallbacks defines the current fallback list. + * @param currentRank defines the current fallback rank. + * @returns the new fallback rank. + */ + PBRAnisotropicConfiguration.AddFallbacks = function (defines, fallbacks, currentRank) { + if (defines.ANISOTROPIC) { + fallbacks.addFallback(currentRank++, "ANISOTROPIC"); + } + return currentRank; + }; + /** + * Add the required uniforms to the current list. + * @param uniforms defines the current uniform list. + */ + PBRAnisotropicConfiguration.AddUniforms = function (uniforms) { + uniforms.push("vAnisotropy", "vAnisotropyInfos", "anisotropyMatrix"); + }; + /** + * Add the required uniforms to the current buffer. + * @param uniformBuffer defines the current uniform buffer. + */ + PBRAnisotropicConfiguration.PrepareUniformBuffer = function (uniformBuffer) { + uniformBuffer.addUniform("vAnisotropy", 3); + uniformBuffer.addUniform("vAnisotropyInfos", 2); + uniformBuffer.addUniform("anisotropyMatrix", 16); + }; + /** + * Add the required samplers to the current list. + * @param samplers defines the current sampler list. + */ + PBRAnisotropicConfiguration.AddSamplers = function (samplers) { + samplers.push("anisotropySampler"); + }; + /** + * Makes a duplicate of the current configuration into another one. + * @param anisotropicConfiguration define the config where to copy the info + */ + PBRAnisotropicConfiguration.prototype.copyTo = function (anisotropicConfiguration) { + _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Clone(function () { return anisotropicConfiguration; }, this); + }; + /** + * Serializes this anisotropy configuration. + * @returns - An object with the serialized config. + */ + PBRAnisotropicConfiguration.prototype.serialize = function () { + return _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(this); + }; + /** + * Parses a anisotropy Configuration from a serialized object. + * @param source - Serialized object. + */ + PBRAnisotropicConfiguration.prototype.parse = function (source) { + var _this = this; + _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(function () { return _this; }, source, null); + }; + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], PBRAnisotropicConfiguration.prototype, "_isEnabled", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRAnisotropicConfiguration.prototype, "isEnabled", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], PBRAnisotropicConfiguration.prototype, "intensity", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsVector2"])() + ], PBRAnisotropicConfiguration.prototype, "direction", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])() + ], PBRAnisotropicConfiguration.prototype, "_texture", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRAnisotropicConfiguration.prototype, "texture", void 0); + return PBRAnisotropicConfiguration; +}()); + + + +/***/ }), + +/***/ "./Materials/PBR/pbrBRDFConfiguration.ts": +/*!***********************************************!*\ + !*** ./Materials/PBR/pbrBRDFConfiguration.ts ***! + \***********************************************/ +/*! exports provided: PBRBRDFConfiguration */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PBRBRDFConfiguration", function() { return PBRBRDFConfiguration; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); + + +/** + * Define the code related to the BRDF parameters of the pbr material. + */ +var PBRBRDFConfiguration = /** @class */ (function () { + /** + * Instantiate a new istance of clear coat configuration. + * @param markAllSubMeshesAsMiscDirty Callback to flag the material to dirty + */ + function PBRBRDFConfiguration(markAllSubMeshesAsMiscDirty) { + this._useEnergyConservation = PBRBRDFConfiguration.DEFAULT_USE_ENERGY_CONSERVATION; + /** + * Defines if the material uses energy conservation. + */ + this.useEnergyConservation = PBRBRDFConfiguration.DEFAULT_USE_ENERGY_CONSERVATION; + this._useSmithVisibilityHeightCorrelated = PBRBRDFConfiguration.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED; + /** + * LEGACY Mode set to false + * Defines if the material uses height smith correlated visibility term. + * If you intent to not use our default BRDF, you need to load a separate BRDF Texture for the PBR + * You can either load https://assets.babylonjs.com/environments/uncorrelatedBRDF.png + * or https://assets.babylonjs.com/environments/uncorrelatedBRDF.dds to have more precision + * Not relying on height correlated will also disable energy conservation. + */ + this.useSmithVisibilityHeightCorrelated = PBRBRDFConfiguration.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED; + this._useSphericalHarmonics = PBRBRDFConfiguration.DEFAULT_USE_SPHERICAL_HARMONICS; + /** + * LEGACY Mode set to false + * Defines if the material uses spherical harmonics vs spherical polynomials for the + * diffuse part of the IBL. + * The harmonics despite a tiny bigger cost has been proven to provide closer results + * to the ground truth. + */ + this.useSphericalHarmonics = PBRBRDFConfiguration.DEFAULT_USE_SPHERICAL_HARMONICS; + this._internalMarkAllSubMeshesAsMiscDirty = markAllSubMeshesAsMiscDirty; + } + /** @hidden */ + PBRBRDFConfiguration.prototype._markAllSubMeshesAsMiscDirty = function () { + this._internalMarkAllSubMeshesAsMiscDirty(); + }; + /** + * Checks to see if a texture is used in the material. + * @param defines the list of "defines" to update. + */ + PBRBRDFConfiguration.prototype.prepareDefines = function (defines) { + defines.BRDF_V_HEIGHT_CORRELATED = this._useSmithVisibilityHeightCorrelated; + defines.MS_BRDF_ENERGY_CONSERVATION = this._useEnergyConservation && this._useSmithVisibilityHeightCorrelated; + defines.SPHERICAL_HARMONICS = this._useSphericalHarmonics; + }; + /** + * Get the current class name of the texture useful for serialization or dynamic coding. + * @returns "PBRClearCoatConfiguration" + */ + PBRBRDFConfiguration.prototype.getClassName = function () { + return "PBRBRDFConfiguration"; + }; + /** + * Makes a duplicate of the current configuration into another one. + * @param brdfConfiguration define the config where to copy the info + */ + PBRBRDFConfiguration.prototype.copyTo = function (brdfConfiguration) { + _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Clone(function () { return brdfConfiguration; }, this); + }; + /** + * Serializes this BRDF configuration. + * @returns - An object with the serialized config. + */ + PBRBRDFConfiguration.prototype.serialize = function () { + return _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(this); + }; + /** + * Parses a BRDF Configuration from a serialized object. + * @param source - Serialized object. + */ + PBRBRDFConfiguration.prototype.parse = function (source) { + var _this = this; + _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(function () { return _this; }, source, null); + }; + /** + * Default value used for the energy conservation. + * This should only be changed to adapt to the type of texture in scene.environmentBRDFTexture. + */ + PBRBRDFConfiguration.DEFAULT_USE_ENERGY_CONSERVATION = true; + /** + * Default value used for the Smith Visibility Height Correlated mode. + * This should only be changed to adapt to the type of texture in scene.environmentBRDFTexture. + */ + PBRBRDFConfiguration.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED = true; + /** + * Default value used for the IBL diffuse part. + * This can help switching back to the polynomials mode globally which is a tiny bit + * less GPU intensive at the drawback of a lower quality. + */ + PBRBRDFConfiguration.DEFAULT_USE_SPHERICAL_HARMONICS = true; + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], PBRBRDFConfiguration.prototype, "_useEnergyConservation", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsMiscDirty") + ], PBRBRDFConfiguration.prototype, "useEnergyConservation", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], PBRBRDFConfiguration.prototype, "_useSmithVisibilityHeightCorrelated", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsMiscDirty") + ], PBRBRDFConfiguration.prototype, "useSmithVisibilityHeightCorrelated", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], PBRBRDFConfiguration.prototype, "_useSphericalHarmonics", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsMiscDirty") + ], PBRBRDFConfiguration.prototype, "useSphericalHarmonics", void 0); + return PBRBRDFConfiguration; +}()); + + + +/***/ }), + +/***/ "./Materials/PBR/pbrBaseMaterial.ts": +/*!******************************************!*\ + !*** ./Materials/PBR/pbrBaseMaterial.ts ***! + \******************************************/ +/*! exports provided: PBRMaterialDefines, PBRBaseMaterial */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PBRMaterialDefines", function() { return PBRMaterialDefines; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PBRBaseMaterial", function() { return PBRBaseMaterial; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/logger */ "./Misc/logger.ts"); +/* harmony import */ var _Misc_smartArray__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Misc/smartArray */ "./Misc/smartArray.ts"); +/* harmony import */ var _Misc_brdfTextureTools__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Misc/brdfTextureTools */ "./Misc/brdfTextureTools.ts"); +/* harmony import */ var _scene__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../scene */ "./scene.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Meshes_buffer__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../Meshes/buffer */ "./Meshes/buffer.ts"); +/* harmony import */ var _pbrClearCoatConfiguration__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./pbrClearCoatConfiguration */ "./Materials/PBR/pbrClearCoatConfiguration.ts"); +/* harmony import */ var _pbrAnisotropicConfiguration__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./pbrAnisotropicConfiguration */ "./Materials/PBR/pbrAnisotropicConfiguration.ts"); +/* harmony import */ var _pbrBRDFConfiguration__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./pbrBRDFConfiguration */ "./Materials/PBR/pbrBRDFConfiguration.ts"); +/* harmony import */ var _pbrSheenConfiguration__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./pbrSheenConfiguration */ "./Materials/PBR/pbrSheenConfiguration.ts"); +/* harmony import */ var _pbrSubSurfaceConfiguration__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./pbrSubSurfaceConfiguration */ "./Materials/PBR/pbrSubSurfaceConfiguration.ts"); +/* harmony import */ var _Materials_imageProcessingConfiguration__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../../Materials/imageProcessingConfiguration */ "./Materials/imageProcessingConfiguration.ts"); +/* harmony import */ var _Materials_effect__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../../Materials/effect */ "./Materials/effect.ts"); +/* harmony import */ var _Materials_materialDefines__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../../Materials/materialDefines */ "./Materials/materialDefines.ts"); +/* harmony import */ var _Materials_pushMaterial__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../../Materials/pushMaterial */ "./Materials/pushMaterial.ts"); +/* harmony import */ var _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../../Materials/materialHelper */ "./Materials/materialHelper.ts"); +/* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../../Materials/Textures/texture */ "./Materials/Textures/texture.ts"); +/* harmony import */ var _materialFlags__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../materialFlags */ "./Materials/materialFlags.ts"); +/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../../Engines/constants */ "./Engines/constants.ts"); +/* harmony import */ var _Shaders_pbr_fragment__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ../../Shaders/pbr.fragment */ "./Shaders/pbr.fragment.ts"); +/* harmony import */ var _Shaders_pbr_vertex__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ../../Shaders/pbr.vertex */ "./Shaders/pbr.vertex.ts"); + + + + + + + + + + + + + + + + + + + + + + + +/** + * Manages the defines for the PBR Material. + * @hidden + */ +var PBRMaterialDefines = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PBRMaterialDefines, _super); + /** + * Initializes the PBR Material defines. + */ + function PBRMaterialDefines() { + var _this = _super.call(this) || this; + _this.PBR = true; + _this.MAINUV1 = false; + _this.MAINUV2 = false; + _this.UV1 = false; + _this.UV2 = false; + _this.ALBEDO = false; + _this.ALBEDODIRECTUV = 0; + _this.VERTEXCOLOR = false; + _this.AMBIENT = false; + _this.AMBIENTDIRECTUV = 0; + _this.AMBIENTINGRAYSCALE = false; + _this.OPACITY = false; + _this.VERTEXALPHA = false; + _this.OPACITYDIRECTUV = 0; + _this.OPACITYRGB = false; + _this.ALPHATEST = false; + _this.DEPTHPREPASS = false; + _this.ALPHABLEND = false; + _this.ALPHAFROMALBEDO = false; + _this.ALPHATESTVALUE = "0.5"; + _this.SPECULAROVERALPHA = false; + _this.RADIANCEOVERALPHA = false; + _this.ALPHAFRESNEL = false; + _this.LINEARALPHAFRESNEL = false; + _this.PREMULTIPLYALPHA = false; + _this.EMISSIVE = false; + _this.EMISSIVEDIRECTUV = 0; + _this.REFLECTIVITY = false; + _this.REFLECTIVITYDIRECTUV = 0; + _this.SPECULARTERM = false; + _this.MICROSURFACEFROMREFLECTIVITYMAP = false; + _this.MICROSURFACEAUTOMATIC = false; + _this.LODBASEDMICROSFURACE = false; + _this.MICROSURFACEMAP = false; + _this.MICROSURFACEMAPDIRECTUV = 0; + _this.METALLICWORKFLOW = false; + _this.ROUGHNESSSTOREINMETALMAPALPHA = false; + _this.ROUGHNESSSTOREINMETALMAPGREEN = false; + _this.METALLNESSSTOREINMETALMAPBLUE = false; + _this.AOSTOREINMETALMAPRED = false; + _this.ENVIRONMENTBRDF = false; + _this.ENVIRONMENTBRDF_RGBD = false; + _this.NORMAL = false; + _this.TANGENT = false; + _this.BUMP = false; + _this.BUMPDIRECTUV = 0; + _this.OBJECTSPACE_NORMALMAP = false; + _this.PARALLAX = false; + _this.PARALLAXOCCLUSION = false; + _this.NORMALXYSCALE = true; + _this.LIGHTMAP = false; + _this.LIGHTMAPDIRECTUV = 0; + _this.USELIGHTMAPASSHADOWMAP = false; + _this.GAMMALIGHTMAP = false; + _this.REFLECTION = false; + _this.REFLECTIONMAP_3D = false; + _this.REFLECTIONMAP_SPHERICAL = false; + _this.REFLECTIONMAP_PLANAR = false; + _this.REFLECTIONMAP_CUBIC = false; + _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false; + _this.REFLECTIONMAP_PROJECTION = false; + _this.REFLECTIONMAP_SKYBOX = false; + _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false; + _this.REFLECTIONMAP_EXPLICIT = false; + _this.REFLECTIONMAP_EQUIRECTANGULAR = false; + _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false; + _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false; + _this.INVERTCUBICMAP = false; + _this.USESPHERICALFROMREFLECTIONMAP = false; + _this.USEIRRADIANCEMAP = false; + _this.SPHERICAL_HARMONICS = false; + _this.USESPHERICALINVERTEX = false; + _this.REFLECTIONMAP_OPPOSITEZ = false; + _this.LODINREFLECTIONALPHA = false; + _this.GAMMAREFLECTION = false; + _this.RGBDREFLECTION = false; + _this.LINEARSPECULARREFLECTION = false; + _this.RADIANCEOCCLUSION = false; + _this.HORIZONOCCLUSION = false; + _this.INSTANCES = false; + _this.NUM_BONE_INFLUENCERS = 0; + _this.BonesPerMesh = 0; + _this.BONETEXTURE = false; + _this.NONUNIFORMSCALING = false; + _this.MORPHTARGETS = false; + _this.MORPHTARGETS_NORMAL = false; + _this.MORPHTARGETS_TANGENT = false; + _this.NUM_MORPH_INFLUENCERS = 0; + _this.IMAGEPROCESSING = false; + _this.VIGNETTE = false; + _this.VIGNETTEBLENDMODEMULTIPLY = false; + _this.VIGNETTEBLENDMODEOPAQUE = false; + _this.TONEMAPPING = false; + _this.TONEMAPPING_ACES = false; + _this.CONTRAST = false; + _this.COLORCURVES = false; + _this.COLORGRADING = false; + _this.COLORGRADING3D = false; + _this.SAMPLER3DGREENDEPTH = false; + _this.SAMPLER3DBGRMAP = false; + _this.IMAGEPROCESSINGPOSTPROCESS = false; + _this.EXPOSURE = false; + _this.MULTIVIEW = false; + _this.USEPHYSICALLIGHTFALLOFF = false; + _this.USEGLTFLIGHTFALLOFF = false; + _this.TWOSIDEDLIGHTING = false; + _this.SHADOWFLOAT = false; + _this.CLIPPLANE = false; + _this.CLIPPLANE2 = false; + _this.CLIPPLANE3 = false; + _this.CLIPPLANE4 = false; + _this.POINTSIZE = false; + _this.FOG = false; + _this.LOGARITHMICDEPTH = false; + _this.FORCENORMALFORWARD = false; + _this.SPECULARAA = false; + _this.CLEARCOAT = false; + _this.CLEARCOAT_DEFAULTIOR = false; + _this.CLEARCOAT_TEXTURE = false; + _this.CLEARCOAT_TEXTUREDIRECTUV = 0; + _this.CLEARCOAT_BUMP = false; + _this.CLEARCOAT_BUMPDIRECTUV = 0; + _this.CLEARCOAT_TINT = false; + _this.CLEARCOAT_TINT_TEXTURE = false; + _this.CLEARCOAT_TINT_TEXTUREDIRECTUV = 0; + _this.ANISOTROPIC = false; + _this.ANISOTROPIC_TEXTURE = false; + _this.ANISOTROPIC_TEXTUREDIRECTUV = 0; + _this.BRDF_V_HEIGHT_CORRELATED = false; + _this.MS_BRDF_ENERGY_CONSERVATION = false; + _this.SHEEN = false; + _this.SHEEN_TEXTURE = false; + _this.SHEEN_TEXTUREDIRECTUV = 0; + _this.SHEEN_LINKWITHALBEDO = false; + _this.SUBSURFACE = false; + _this.SS_REFRACTION = false; + _this.SS_TRANSLUCENCY = false; + _this.SS_SCATERRING = false; + _this.SS_THICKNESSANDMASK_TEXTURE = false; + _this.SS_THICKNESSANDMASK_TEXTUREDIRECTUV = 0; + _this.SS_REFRACTIONMAP_3D = false; + _this.SS_REFRACTIONMAP_OPPOSITEZ = false; + _this.SS_LODINREFRACTIONALPHA = false; + _this.SS_GAMMAREFRACTION = false; + _this.SS_RGBDREFRACTION = false; + _this.SS_LINEARSPECULARREFRACTION = false; + _this.SS_LINKREFRACTIONTOTRANSPARENCY = false; + _this.SS_MASK_FROM_THICKNESS_TEXTURE = false; + _this.UNLIT = false; + _this.DEBUGMODE = 0; + _this.rebuild(); + return _this; + } + /** + * Resets the PBR Material defines. + */ + PBRMaterialDefines.prototype.reset = function () { + _super.prototype.reset.call(this); + this.ALPHATESTVALUE = "0.5"; + this.PBR = true; + }; + return PBRMaterialDefines; +}(_Materials_materialDefines__WEBPACK_IMPORTED_MODULE_15__["MaterialDefines"])); + +/** + * The Physically based material base class of BJS. + * + * This offers the main features of a standard PBR material. + * For more information, please refer to the documentation : + * https://doc.babylonjs.com/how_to/physically_based_rendering + */ +var PBRBaseMaterial = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PBRBaseMaterial, _super); + /** + * Instantiates a new PBRMaterial instance. + * + * @param name The material name + * @param scene The scene the material will be use in. + */ + function PBRBaseMaterial(name, scene) { + var _this = _super.call(this, name, scene) || this; + /** + * Intensity of the direct lights e.g. the four lights available in your scene. + * This impacts both the direct diffuse and specular highlights. + */ + _this._directIntensity = 1.0; + /** + * Intensity of the emissive part of the material. + * This helps controlling the emissive effect without modifying the emissive color. + */ + _this._emissiveIntensity = 1.0; + /** + * Intensity of the environment e.g. how much the environment will light the object + * either through harmonics for rough material or through the refelction for shiny ones. + */ + _this._environmentIntensity = 1.0; + /** + * This is a special control allowing the reduction of the specular highlights coming from the + * four lights of the scene. Those highlights may not be needed in full environment lighting. + */ + _this._specularIntensity = 1.0; + /** + * This stores the direct, emissive, environment, and specular light intensities into a Vector4. + */ + _this._lightingInfos = new _Maths_math__WEBPACK_IMPORTED_MODULE_6__["Vector4"](_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity); + /** + * Debug Control allowing disabling the bump map on this material. + */ + _this._disableBumpMap = false; + /** + * AKA Diffuse Texture in standard nomenclature. + */ + _this._albedoTexture = null; + /** + * AKA Occlusion Texture in other nomenclature. + */ + _this._ambientTexture = null; + /** + * AKA Occlusion Texture Intensity in other nomenclature. + */ + _this._ambientTextureStrength = 1.0; + /** + * Defines how much the AO map is occluding the analytical lights (point spot...). + * 1 means it completely occludes it + * 0 mean it has no impact + */ + _this._ambientTextureImpactOnAnalyticalLights = PBRBaseMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS; + /** + * Stores the alpha values in a texture. + */ + _this._opacityTexture = null; + /** + * Stores the reflection values in a texture. + */ + _this._reflectionTexture = null; + /** + * Stores the emissive values in a texture. + */ + _this._emissiveTexture = null; + /** + * AKA Specular texture in other nomenclature. + */ + _this._reflectivityTexture = null; + /** + * Used to switch from specular/glossiness to metallic/roughness workflow. + */ + _this._metallicTexture = null; + /** + * Specifies the metallic scalar of the metallic/roughness workflow. + * Can also be used to scale the metalness values of the metallic texture. + */ + _this._metallic = null; + /** + * Specifies the roughness scalar of the metallic/roughness workflow. + * Can also be used to scale the roughness values of the metallic texture. + */ + _this._roughness = null; + /** + * Used to enable roughness/glossiness fetch from a separate channel depending on the current mode. + * Gray Scale represents roughness in metallic mode and glossiness in specular mode. + */ + _this._microSurfaceTexture = null; + /** + * Stores surface normal data used to displace a mesh in a texture. + */ + _this._bumpTexture = null; + /** + * Stores the pre-calculated light information of a mesh in a texture. + */ + _this._lightmapTexture = null; + /** + * The color of a material in ambient lighting. + */ + _this._ambientColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_6__["Color3"](0, 0, 0); + /** + * AKA Diffuse Color in other nomenclature. + */ + _this._albedoColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_6__["Color3"](1, 1, 1); + /** + * AKA Specular Color in other nomenclature. + */ + _this._reflectivityColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_6__["Color3"](1, 1, 1); + /** + * The color applied when light is reflected from a material. + */ + _this._reflectionColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_6__["Color3"](1, 1, 1); + /** + * The color applied when light is emitted from a material. + */ + _this._emissiveColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_6__["Color3"](0, 0, 0); + /** + * AKA Glossiness in other nomenclature. + */ + _this._microSurface = 0.9; + /** + * Specifies that the material will use the light map as a show map. + */ + _this._useLightmapAsShadowmap = false; + /** + * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal + * makes the reflect vector face the model (under horizon). + */ + _this._useHorizonOcclusion = true; + /** + * This parameters will enable/disable radiance occlusion by preventing the radiance to lit + * too much the area relying on ambient texture to define their ambient occlusion. + */ + _this._useRadianceOcclusion = true; + /** + * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending. + */ + _this._useAlphaFromAlbedoTexture = false; + /** + * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones). + * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind. + */ + _this._useSpecularOverAlpha = true; + /** + * Specifies if the reflectivity texture contains the glossiness information in its alpha channel. + */ + _this._useMicroSurfaceFromReflectivityMapAlpha = false; + /** + * Specifies if the metallic texture contains the roughness information in its alpha channel. + */ + _this._useRoughnessFromMetallicTextureAlpha = true; + /** + * Specifies if the metallic texture contains the roughness information in its green channel. + */ + _this._useRoughnessFromMetallicTextureGreen = false; + /** + * Specifies if the metallic texture contains the metallness information in its blue channel. + */ + _this._useMetallnessFromMetallicTextureBlue = false; + /** + * Specifies if the metallic texture contains the ambient occlusion information in its red channel. + */ + _this._useAmbientOcclusionFromMetallicTextureRed = false; + /** + * Specifies if the ambient texture contains the ambient occlusion information in its red channel only. + */ + _this._useAmbientInGrayScale = false; + /** + * In case the reflectivity map does not contain the microsurface information in its alpha channel, + * The material will try to infer what glossiness each pixel should be. + */ + _this._useAutoMicroSurfaceFromReflectivityMap = false; + /** + * Defines the falloff type used in this material. + * It by default is Physical. + */ + _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL; + /** + * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones). + * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind. + */ + _this._useRadianceOverAlpha = true; + /** + * Allows using an object space normal map (instead of tangent space). + */ + _this._useObjectSpaceNormalMap = false; + /** + * Allows using the bump map in parallax mode. + */ + _this._useParallax = false; + /** + * Allows using the bump map in parallax occlusion mode. + */ + _this._useParallaxOcclusion = false; + /** + * Controls the scale bias of the parallax mode. + */ + _this._parallaxScaleBias = 0.05; + /** + * If sets to true, disables all the lights affecting the material. + */ + _this._disableLighting = false; + /** + * Number of Simultaneous lights allowed on the material. + */ + _this._maxSimultaneousLights = 4; + /** + * If sets to true, x component of normal map value will be inverted (x = 1.0 - x). + */ + _this._invertNormalMapX = false; + /** + * If sets to true, y component of normal map value will be inverted (y = 1.0 - y). + */ + _this._invertNormalMapY = false; + /** + * If sets to true and backfaceCulling is false, normals will be flipped on the backside. + */ + _this._twoSidedLighting = false; + /** + * Defines the alpha limits in alpha test mode. + */ + _this._alphaCutOff = 0.4; + /** + * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations. + */ + _this._forceAlphaTest = false; + /** + * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested. + * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel) + */ + _this._useAlphaFresnel = false; + /** + * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested. + * And/Or occlude the blended part. (alpha stays linear to compute the fresnel) + */ + _this._useLinearAlphaFresnel = false; + /** + * The transparency mode of the material. + */ + _this._transparencyMode = null; + /** + * Specifies the environment BRDF texture used to comput the scale and offset roughness values + * from cos thetav and roughness: + * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf + */ + _this._environmentBRDFTexture = null; + /** + * Force the shader to compute irradiance in the fragment shader in order to take bump in account. + */ + _this._forceIrradianceInFragment = false; + /** + * Force normal to face away from face. + */ + _this._forceNormalForward = false; + /** + * Enables specular anti aliasing in the PBR shader. + * It will both interacts on the Geometry for analytical and IBL lighting. + * It also prefilter the roughness map based on the bump values. + */ + _this._enableSpecularAntiAliasing = false; + /** + * Keep track of the image processing observer to allow dispose and replace. + */ + _this._imageProcessingObserver = null; + /** + * Stores the available render targets. + */ + _this._renderTargets = new _Misc_smartArray__WEBPACK_IMPORTED_MODULE_3__["SmartArray"](16); + /** + * Sets the global ambient color for the material used in lighting calculations. + */ + _this._globalAmbientColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_6__["Color3"](0, 0, 0); + /** + * Enables the use of logarithmic depth buffers, which is good for wide depth buffers. + */ + _this._useLogarithmicDepth = false; + /** + * If set to true, no lighting calculations will be applied. + */ + _this._unlit = false; + _this._debugMode = 0; + /** + * @hidden + * This is reserved for the inspector. + * Defines the material debug mode. + * It helps seeing only some components of the material while troubleshooting. + */ + _this.debugMode = 0; + /** + * @hidden + * This is reserved for the inspector. + * Specify from where on screen the debug mode should start. + * The value goes from -1 (full screen) to 1 (not visible) + * It helps with side by side comparison against the final render + * This defaults to -1 + */ + _this.debugLimit = -1; + /** + * @hidden + * This is reserved for the inspector. + * As the default viewing range might not be enough (if the ambient is really small for instance) + * You can use the factor to better multiply the final value. + */ + _this.debugFactor = 1; + /** + * Defines the clear coat layer parameters for the material. + */ + _this.clearCoat = new _pbrClearCoatConfiguration__WEBPACK_IMPORTED_MODULE_8__["PBRClearCoatConfiguration"](_this._markAllSubMeshesAsTexturesDirty.bind(_this)); + /** + * Defines the anisotropic parameters for the material. + */ + _this.anisotropy = new _pbrAnisotropicConfiguration__WEBPACK_IMPORTED_MODULE_9__["PBRAnisotropicConfiguration"](_this._markAllSubMeshesAsTexturesDirty.bind(_this)); + /** + * Defines the BRDF parameters for the material. + */ + _this.brdf = new _pbrBRDFConfiguration__WEBPACK_IMPORTED_MODULE_10__["PBRBRDFConfiguration"](_this._markAllSubMeshesAsMiscDirty.bind(_this)); + /** + * Defines the Sheen parameters for the material. + */ + _this.sheen = new _pbrSheenConfiguration__WEBPACK_IMPORTED_MODULE_11__["PBRSheenConfiguration"](_this._markAllSubMeshesAsTexturesDirty.bind(_this)); + /** + * Defines the SubSurface parameters for the material. + */ + _this.subSurface = new _pbrSubSurfaceConfiguration__WEBPACK_IMPORTED_MODULE_12__["PBRSubSurfaceConfiguration"](_this._markAllSubMeshesAsTexturesDirty.bind(_this)); + // Setup the default processing configuration to the scene. + _this._attachImageProcessingConfiguration(null); + _this.getRenderTargetTextures = function () { + _this._renderTargets.reset(); + if (_materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) { + _this._renderTargets.push(_this._reflectionTexture); + } + _this.subSurface.fillRenderTargetTextures(_this._renderTargets); + return _this._renderTargets; + }; + _this._environmentBRDFTexture = _Misc_brdfTextureTools__WEBPACK_IMPORTED_MODULE_4__["BRDFTextureTools"].GetEnvironmentBRDFTexture(scene); + return _this; + } + /** + * Attaches a new image processing configuration to the PBR Material. + * @param configuration + */ + PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) { + var _this = this; + if (configuration === this._imageProcessingConfiguration) { + return; + } + // Detaches observer. + if (this._imageProcessingConfiguration && this._imageProcessingObserver) { + this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver); + } + // Pick the scene configuration if needed. + if (!configuration) { + this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration; + } + else { + this._imageProcessingConfiguration = configuration; + } + // Attaches observer. + if (this._imageProcessingConfiguration) { + this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function () { + _this._markAllSubMeshesAsImageProcessingDirty(); + }); + } + }; + Object.defineProperty(PBRBaseMaterial.prototype, "hasRenderTargetTextures", { + /** + * Gets a boolean indicating that current material needs to register RTT + */ + get: function () { + if (_materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) { + return true; + } + return this.subSurface.hasRenderTargetTextures(); + }, + enumerable: true, + configurable: true + }); + /** + * Gets the name of the material class. + */ + PBRBaseMaterial.prototype.getClassName = function () { + return "PBRBaseMaterial"; + }; + Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", { + /** + * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers. + */ + get: function () { + return this._useLogarithmicDepth; + }, + /** + * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers. + */ + set: function (value) { + this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", { + /** + * Gets the current transparency mode. + */ + get: function () { + return this._transparencyMode; + }, + /** + * Sets the transparency mode of the material. + * + * | Value | Type | Description | + * | ----- | ----------------------------------- | ----------- | + * | 0 | OPAQUE | | + * | 1 | ALPHATEST | | + * | 2 | ALPHABLEND | | + * | 3 | ALPHATESTANDBLEND | | + * + */ + set: function (value) { + if (this._transparencyMode === value) { + return; + } + this._transparencyMode = value; + this._forceAlphaTest = (value === PBRBaseMaterial.PBRMATERIAL_ALPHATESTANDBLEND); + this._markAllSubMeshesAsTexturesAndMiscDirty(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", { + /** + * Returns true if alpha blending should be disabled. + */ + get: function () { + return (this.subSurface.disableAlphaBlending || + this._transparencyMode === PBRBaseMaterial.PBRMATERIAL_OPAQUE || + this._transparencyMode === PBRBaseMaterial.PBRMATERIAL_ALPHATEST); + }, + enumerable: true, + configurable: true + }); + /** + * Specifies whether or not this material should be rendered in alpha blend mode. + */ + PBRBaseMaterial.prototype.needAlphaBlending = function () { + if (this._disableAlphaBlending) { + return false; + } + return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture(); + }; + /** + * Specifies if the mesh will require alpha blending. + * @param mesh - BJS mesh. + */ + PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) { + if (this._disableAlphaBlending && mesh.visibility >= 1.0) { + return false; + } + return _super.prototype.needAlphaBlendingForMesh.call(this, mesh); + }; + /** + * Specifies whether or not this material should be rendered in alpha test mode. + */ + PBRBaseMaterial.prototype.needAlphaTesting = function () { + if (this._forceAlphaTest) { + return true; + } + if (this.subSurface.disableAlphaBlending) { + return false; + } + return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === PBRBaseMaterial.PBRMATERIAL_ALPHATEST); + }; + /** + * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending. + */ + PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () { + return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== PBRBaseMaterial.PBRMATERIAL_OPAQUE; + }; + /** + * Gets the texture used for the alpha test. + */ + PBRBaseMaterial.prototype.getAlphaTestTexture = function () { + return this._albedoTexture; + }; + /** + * Specifies that the submesh is ready to be used. + * @param mesh - BJS mesh. + * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready. + * @param useInstances - Specifies that instances should be used. + * @returns - boolean indicating that the submesh is ready or not. + */ + PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) { + if (subMesh.effect && this.isFrozen) { + if (this._wasPreviouslyReady) { + return true; + } + } + if (!subMesh._materialDefines) { + subMesh._materialDefines = new PBRMaterialDefines(); + } + var defines = subMesh._materialDefines; + if (!this.checkReadyOnEveryCall && subMesh.effect) { + if (defines._renderId === this.getScene().getRenderId()) { + return true; + } + } + var scene = this.getScene(); + var engine = scene.getEngine(); + if (defines._areTexturesDirty) { + if (scene.texturesEnabled) { + if (this._albedoTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].DiffuseTextureEnabled) { + if (!this._albedoTexture.isReadyOrNotBlocking()) { + return false; + } + } + if (this._ambientTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].AmbientTextureEnabled) { + if (!this._ambientTexture.isReadyOrNotBlocking()) { + return false; + } + } + if (this._opacityTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].OpacityTextureEnabled) { + if (!this._opacityTexture.isReadyOrNotBlocking()) { + return false; + } + } + var reflectionTexture = this._getReflectionTexture(); + if (reflectionTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].ReflectionTextureEnabled) { + if (!reflectionTexture.isReadyOrNotBlocking()) { + return false; + } + if (reflectionTexture.irradianceTexture && !reflectionTexture.irradianceTexture.isReadyOrNotBlocking()) { + return false; + } + } + if (this._lightmapTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].LightmapTextureEnabled) { + if (!this._lightmapTexture.isReadyOrNotBlocking()) { + return false; + } + } + if (this._emissiveTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].EmissiveTextureEnabled) { + if (!this._emissiveTexture.isReadyOrNotBlocking()) { + return false; + } + } + if (_materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].SpecularTextureEnabled) { + if (this._metallicTexture) { + if (!this._metallicTexture.isReadyOrNotBlocking()) { + return false; + } + } + else if (this._reflectivityTexture) { + if (!this._reflectivityTexture.isReadyOrNotBlocking()) { + return false; + } + } + if (this._microSurfaceTexture) { + if (!this._microSurfaceTexture.isReadyOrNotBlocking()) { + return false; + } + } + } + if (engine.getCaps().standardDerivatives && this._bumpTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].BumpTextureEnabled && !this._disableBumpMap) { + // Bump texture cannot be not blocking. + if (!this._bumpTexture.isReady()) { + return false; + } + } + if (this._environmentBRDFTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].ReflectionTextureEnabled) { + // This is blocking. + if (!this._environmentBRDFTexture.isReady()) { + return false; + } + } + } + } + if (!this.subSurface.isReadyForSubMesh(defines, scene) || + !this.clearCoat.isReadyForSubMesh(defines, scene, engine, this._disableBumpMap) || + !this.sheen.isReadyForSubMesh(defines, scene) || + !this.anisotropy.isReadyForSubMesh(defines, scene)) { + return false; + } + if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) { + if (!this._imageProcessingConfiguration.isReady()) { + return false; + } + } + if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_7__["VertexBuffer"].NormalKind)) { + mesh.createNormals(true); + _Misc_logger__WEBPACK_IMPORTED_MODULE_2__["Logger"].Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name); + } + var previousEffect = subMesh.effect; + var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances); + if (effect) { + // Use previous effect while new one is compiling + if (this.allowShaderHotSwapping && previousEffect && !effect.isReady()) { + effect = previousEffect; + defines.markAsUnprocessed(); + } + else { + scene.resetCachedMaterial(); + subMesh.setEffect(effect, defines); + this.buildUniformLayout(); + } + } + if (!subMesh.effect || !subMesh.effect.isReady()) { + return false; + } + defines._renderId = scene.getRenderId(); + this._wasPreviouslyReady = true; + return true; + }; + /** + * Specifies if the material uses metallic roughness workflow. + * @returns boolean specifiying if the material uses metallic roughness workflow. + */ + PBRBaseMaterial.prototype.isMetallicWorkflow = function () { + if (this._metallic != null || this._roughness != null || this._metallicTexture) { + return true; + } + return false; + }; + PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) { + if (onCompiled === void 0) { onCompiled = null; } + if (onError === void 0) { onError = null; } + if (useInstances === void 0) { useInstances = null; } + if (useClipPlane === void 0) { useClipPlane = null; } + this._prepareDefines(mesh, defines, useInstances, useClipPlane); + if (!defines.isDirty) { + return null; + } + defines.markAsProcessed(); + var scene = this.getScene(); + var engine = scene.getEngine(); + // Fallbacks + var fallbacks = new _Materials_effect__WEBPACK_IMPORTED_MODULE_14__["EffectFallbacks"](); + var fallbackRank = 0; + if (defines.USESPHERICALINVERTEX) { + fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX"); + } + if (defines.FOG) { + fallbacks.addFallback(fallbackRank, "FOG"); + } + if (defines.SPECULARAA) { + fallbacks.addFallback(fallbackRank, "SPECULARAA"); + } + if (defines.POINTSIZE) { + fallbacks.addFallback(fallbackRank, "POINTSIZE"); + } + if (defines.LOGARITHMICDEPTH) { + fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH"); + } + if (defines.PARALLAX) { + fallbacks.addFallback(fallbackRank, "PARALLAX"); + } + if (defines.PARALLAXOCCLUSION) { + fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION"); + } + fallbackRank = _pbrAnisotropicConfiguration__WEBPACK_IMPORTED_MODULE_9__["PBRAnisotropicConfiguration"].AddFallbacks(defines, fallbacks, fallbackRank); + fallbackRank = _pbrAnisotropicConfiguration__WEBPACK_IMPORTED_MODULE_9__["PBRAnisotropicConfiguration"].AddFallbacks(defines, fallbacks, fallbackRank); + fallbackRank = _pbrSubSurfaceConfiguration__WEBPACK_IMPORTED_MODULE_12__["PBRSubSurfaceConfiguration"].AddFallbacks(defines, fallbacks, fallbackRank); + fallbackRank = _pbrSheenConfiguration__WEBPACK_IMPORTED_MODULE_11__["PBRSheenConfiguration"].AddFallbacks(defines, fallbacks, fallbackRank); + if (defines.ENVIRONMENTBRDF) { + fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF"); + } + if (defines.TANGENT) { + fallbacks.addFallback(fallbackRank++, "TANGENT"); + } + if (defines.BUMP) { + fallbacks.addFallback(fallbackRank++, "BUMP"); + } + fallbackRank = _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++); + if (defines.SPECULARTERM) { + fallbacks.addFallback(fallbackRank++, "SPECULARTERM"); + } + if (defines.USESPHERICALFROMREFLECTIONMAP) { + fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP"); + } + if (defines.USEIRRADIANCEMAP) { + fallbacks.addFallback(fallbackRank++, "USEIRRADIANCEMAP"); + } + if (defines.LIGHTMAP) { + fallbacks.addFallback(fallbackRank++, "LIGHTMAP"); + } + if (defines.NORMAL) { + fallbacks.addFallback(fallbackRank++, "NORMAL"); + } + if (defines.AMBIENT) { + fallbacks.addFallback(fallbackRank++, "AMBIENT"); + } + if (defines.EMISSIVE) { + fallbacks.addFallback(fallbackRank++, "EMISSIVE"); + } + if (defines.VERTEXCOLOR) { + fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR"); + } + if (defines.NUM_BONE_INFLUENCERS > 0) { + fallbacks.addCPUSkinningFallback(fallbackRank++, mesh); + } + if (defines.MORPHTARGETS) { + fallbacks.addFallback(fallbackRank++, "MORPHTARGETS"); + } + if (defines.MULTIVIEW) { + fallbacks.addFallback(0, "MULTIVIEW"); + } + //Attributes + var attribs = [_Meshes_buffer__WEBPACK_IMPORTED_MODULE_7__["VertexBuffer"].PositionKind]; + if (defines.NORMAL) { + attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_7__["VertexBuffer"].NormalKind); + } + if (defines.TANGENT) { + attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_7__["VertexBuffer"].TangentKind); + } + if (defines.UV1) { + attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_7__["VertexBuffer"].UVKind); + } + if (defines.UV2) { + attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_7__["VertexBuffer"].UV2Kind); + } + if (defines.VERTEXCOLOR) { + attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_7__["VertexBuffer"].ColorKind); + } + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].PrepareAttributesForBones(attribs, mesh, defines, fallbacks); + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].PrepareAttributesForInstances(attribs, defines); + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].PrepareAttributesForMorphTargets(attribs, mesh, defines); + var shaderName = "pbr"; + var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "visibility", "vReflectionColor", + "vFogInfos", "vFogColor", "pointSize", + "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos", + "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", + "mBones", + "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", + "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" + ]; + var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler", + "bumpSampler", "lightmapSampler", "opacitySampler", + "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh", "irradianceSampler", + "microSurfaceSampler", "environmentBrdfSampler", "boneSampler"]; + var uniformBuffers = ["Material", "Scene"]; + _pbrSubSurfaceConfiguration__WEBPACK_IMPORTED_MODULE_12__["PBRSubSurfaceConfiguration"].AddUniforms(uniforms); + _pbrSubSurfaceConfiguration__WEBPACK_IMPORTED_MODULE_12__["PBRSubSurfaceConfiguration"].AddSamplers(samplers); + _pbrClearCoatConfiguration__WEBPACK_IMPORTED_MODULE_8__["PBRClearCoatConfiguration"].AddUniforms(uniforms); + _pbrClearCoatConfiguration__WEBPACK_IMPORTED_MODULE_8__["PBRClearCoatConfiguration"].AddSamplers(samplers); + _pbrAnisotropicConfiguration__WEBPACK_IMPORTED_MODULE_9__["PBRAnisotropicConfiguration"].AddUniforms(uniforms); + _pbrAnisotropicConfiguration__WEBPACK_IMPORTED_MODULE_9__["PBRAnisotropicConfiguration"].AddSamplers(samplers); + _pbrSheenConfiguration__WEBPACK_IMPORTED_MODULE_11__["PBRSheenConfiguration"].AddUniforms(uniforms); + _pbrSheenConfiguration__WEBPACK_IMPORTED_MODULE_11__["PBRSheenConfiguration"].AddSamplers(samplers); + if (_Materials_imageProcessingConfiguration__WEBPACK_IMPORTED_MODULE_13__["ImageProcessingConfiguration"]) { + _Materials_imageProcessingConfiguration__WEBPACK_IMPORTED_MODULE_13__["ImageProcessingConfiguration"].PrepareUniforms(uniforms, defines); + _Materials_imageProcessingConfiguration__WEBPACK_IMPORTED_MODULE_13__["ImageProcessingConfiguration"].PrepareSamplers(samplers, defines); + } + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].PrepareUniformsAndSamplersList({ + uniformsNames: uniforms, + uniformBuffersNames: uniformBuffers, + samplers: samplers, + defines: defines, + maxSimultaneousLights: this._maxSimultaneousLights + }); + if (this.customShaderNameResolve) { + shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines); + } + var join = defines.toString(); + return engine.createEffect(shaderName, { + attributes: attribs, + uniformsNames: uniforms, + uniformBuffersNames: uniformBuffers, + samplers: samplers, + defines: join, + fallbacks: fallbacks, + onCompiled: onCompiled, + onError: onError, + indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS } + }, engine); + }; + PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) { + if (useInstances === void 0) { useInstances = null; } + if (useClipPlane === void 0) { useClipPlane = null; } + var scene = this.getScene(); + var engine = scene.getEngine(); + // Lights + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting); + defines._needNormals = true; + // Multiview + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].PrepareDefinesForMultiview(scene, defines); + // Textures + defines.METALLICWORKFLOW = this.isMetallicWorkflow(); + if (defines._areTexturesDirty) { + defines._needUVs = false; + if (scene.texturesEnabled) { + if (scene.getEngine().getCaps().textureLOD) { + defines.LODBASEDMICROSFURACE = true; + } + if (this._albedoTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].DiffuseTextureEnabled) { + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO"); + } + else { + defines.ALBEDO = false; + } + if (this._ambientTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].AmbientTextureEnabled) { + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT"); + defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale; + } + else { + defines.AMBIENT = false; + } + if (this._opacityTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].OpacityTextureEnabled) { + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY"); + defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB; + } + else { + defines.OPACITY = false; + } + var reflectionTexture = this._getReflectionTexture(); + if (reflectionTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].ReflectionTextureEnabled) { + defines.REFLECTION = true; + defines.GAMMAREFLECTION = reflectionTexture.gammaSpace; + defines.RGBDREFLECTION = reflectionTexture.isRGBD; + defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ; + defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha; + defines.LINEARSPECULARREFLECTION = reflectionTexture.linearSpecularLOD; + if (reflectionTexture.coordinatesMode === _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_18__["Texture"].INVCUBIC_MODE) { + defines.INVERTCUBICMAP = true; + } + defines.REFLECTIONMAP_3D = reflectionTexture.isCube; + defines.REFLECTIONMAP_CUBIC = false; + defines.REFLECTIONMAP_EXPLICIT = false; + defines.REFLECTIONMAP_PLANAR = false; + defines.REFLECTIONMAP_PROJECTION = false; + defines.REFLECTIONMAP_SKYBOX = false; + defines.REFLECTIONMAP_SPHERICAL = false; + defines.REFLECTIONMAP_EQUIRECTANGULAR = false; + defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false; + defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false; + defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false; + switch (reflectionTexture.coordinatesMode) { + case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_18__["Texture"].EXPLICIT_MODE: + defines.REFLECTIONMAP_EXPLICIT = true; + break; + case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_18__["Texture"].PLANAR_MODE: + defines.REFLECTIONMAP_PLANAR = true; + break; + case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_18__["Texture"].PROJECTION_MODE: + defines.REFLECTIONMAP_PROJECTION = true; + break; + case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_18__["Texture"].SKYBOX_MODE: + defines.REFLECTIONMAP_SKYBOX = true; + break; + case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_18__["Texture"].SPHERICAL_MODE: + defines.REFLECTIONMAP_SPHERICAL = true; + break; + case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_18__["Texture"].EQUIRECTANGULAR_MODE: + defines.REFLECTIONMAP_EQUIRECTANGULAR = true; + break; + case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_18__["Texture"].FIXED_EQUIRECTANGULAR_MODE: + defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true; + break; + case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_18__["Texture"].FIXED_EQUIRECTANGULAR_MIRRORED_MODE: + defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true; + break; + case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_18__["Texture"].CUBIC_MODE: + case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_18__["Texture"].INVCUBIC_MODE: + default: + defines.REFLECTIONMAP_CUBIC = true; + defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false; + break; + } + if (reflectionTexture.coordinatesMode !== _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_18__["Texture"].SKYBOX_MODE) { + if (reflectionTexture.irradianceTexture) { + defines.USEIRRADIANCEMAP = true; + defines.USESPHERICALFROMREFLECTIONMAP = false; + } + else if (reflectionTexture.sphericalPolynomial) { + defines.USESPHERICALFROMREFLECTIONMAP = true; + defines.USEIRRADIANCEMAP = false; + if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) { + defines.USESPHERICALINVERTEX = false; + } + else { + defines.USESPHERICALINVERTEX = true; + } + } + } + else { + defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity(); + } + } + else { + defines.REFLECTION = false; + defines.REFLECTIONMAP_3D = false; + defines.REFLECTIONMAP_SPHERICAL = false; + defines.REFLECTIONMAP_PLANAR = false; + defines.REFLECTIONMAP_CUBIC = false; + defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false; + defines.REFLECTIONMAP_PROJECTION = false; + defines.REFLECTIONMAP_SKYBOX = false; + defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false; + defines.REFLECTIONMAP_EXPLICIT = false; + defines.REFLECTIONMAP_EQUIRECTANGULAR = false; + defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false; + defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false; + defines.INVERTCUBICMAP = false; + defines.USESPHERICALFROMREFLECTIONMAP = false; + defines.USEIRRADIANCEMAP = false; + defines.USESPHERICALINVERTEX = false; + defines.REFLECTIONMAP_OPPOSITEZ = false; + defines.LODINREFLECTIONALPHA = false; + defines.GAMMAREFLECTION = false; + defines.RGBDREFLECTION = false; + defines.LINEARSPECULARREFLECTION = false; + } + if (this._lightmapTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].LightmapTextureEnabled) { + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP"); + defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap; + defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace; + } + else { + defines.LIGHTMAP = false; + } + if (this._emissiveTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].EmissiveTextureEnabled) { + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE"); + } + else { + defines.EMISSIVE = false; + } + if (_materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].SpecularTextureEnabled) { + if (this._metallicTexture) { + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY"); + defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha; + defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen; + defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue; + defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed; + } + else if (this._reflectivityTexture) { + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY"); + defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha; + defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap; + } + else { + defines.REFLECTIVITY = false; + } + if (this._microSurfaceTexture) { + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP"); + } + else { + defines.MICROSURFACEMAP = false; + } + } + else { + defines.REFLECTIVITY = false; + defines.MICROSURFACEMAP = false; + } + if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].BumpTextureEnabled && !this._disableBumpMap) { + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP"); + if (this._useParallax && this._albedoTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].DiffuseTextureEnabled) { + defines.PARALLAX = true; + defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion; + } + else { + defines.PARALLAX = false; + } + defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap; + } + else { + defines.BUMP = false; + } + if (this._environmentBRDFTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].ReflectionTextureEnabled) { + defines.ENVIRONMENTBRDF = true; + // Not actual true RGBD, only the B chanel is encoded as RGBD for sheen. + defines.ENVIRONMENTBRDF_RGBD = this._environmentBRDFTexture.isRGBD; + } + else { + defines.ENVIRONMENTBRDF = false; + defines.ENVIRONMENTBRDF_RGBD = false; + } + if (this._shouldUseAlphaFromAlbedoTexture()) { + defines.ALPHAFROMALBEDO = true; + } + else { + defines.ALPHAFROMALBEDO = false; + } + } + defines.SPECULAROVERALPHA = this._useSpecularOverAlpha; + if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) { + defines.USEPHYSICALLIGHTFALLOFF = false; + defines.USEGLTFLIGHTFALLOFF = false; + } + else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) { + defines.USEPHYSICALLIGHTFALLOFF = false; + defines.USEGLTFLIGHTFALLOFF = true; + } + else { + defines.USEPHYSICALLIGHTFALLOFF = true; + defines.USEGLTFLIGHTFALLOFF = false; + } + defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha; + if (!this.backFaceCulling && this._twoSidedLighting) { + defines.TWOSIDEDLIGHTING = true; + } + else { + defines.TWOSIDEDLIGHTING = false; + } + defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : ""); + defines.PREMULTIPLYALPHA = (this.alphaMode === _Engines_constants__WEBPACK_IMPORTED_MODULE_20__["Constants"].ALPHA_PREMULTIPLIED || this.alphaMode === _Engines_constants__WEBPACK_IMPORTED_MODULE_20__["Constants"].ALPHA_PREMULTIPLIED_PORTERDUFF); + defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh); + defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel; + defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel; + defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing; + } + if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) { + this._imageProcessingConfiguration.prepareDefines(defines); + } + defines.FORCENORMALFORWARD = this._forceNormalForward; + defines.RADIANCEOCCLUSION = this._useRadianceOcclusion; + defines.HORIZONOCCLUSION = this._useHorizonOcclusion; + // Misc. + if (defines._areMiscDirty) { + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines); + defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_7__["VertexBuffer"].NormalKind)); + defines.DEBUGMODE = this._debugMode; + } + // External config + this.subSurface.prepareDefines(defines, scene); + this.clearCoat.prepareDefines(defines, scene); + this.anisotropy.prepareDefines(defines, mesh, scene); + this.brdf.prepareDefines(defines); + this.sheen.prepareDefines(defines, scene); + // Values that need to be evaluated on every frame + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane); + // Attribs + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== PBRBaseMaterial.PBRMATERIAL_OPAQUE); + }; + /** + * Force shader compilation + */ + PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) { + var _this = this; + var localOptions = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({ clipPlane: false }, options); + var defines = new PBRMaterialDefines(); + var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane); + if (effect.isReady()) { + if (onCompiled) { + onCompiled(this); + } + } + else { + effect.onCompileObservable.add(function () { + if (onCompiled) { + onCompiled(_this); + } + }); + } + }; + /** + * Initializes the uniform buffer layout for the shader. + */ + PBRBaseMaterial.prototype.buildUniformLayout = function () { + // Order is important ! + var ubo = this._uniformBuffer; + ubo.addUniform("vAlbedoInfos", 2); + ubo.addUniform("vAmbientInfos", 4); + ubo.addUniform("vOpacityInfos", 2); + ubo.addUniform("vEmissiveInfos", 2); + ubo.addUniform("vLightmapInfos", 2); + ubo.addUniform("vReflectivityInfos", 3); + ubo.addUniform("vMicroSurfaceSamplerInfos", 2); + ubo.addUniform("vReflectionInfos", 2); + ubo.addUniform("vReflectionPosition", 3); + ubo.addUniform("vReflectionSize", 3); + ubo.addUniform("vBumpInfos", 3); + ubo.addUniform("albedoMatrix", 16); + ubo.addUniform("ambientMatrix", 16); + ubo.addUniform("opacityMatrix", 16); + ubo.addUniform("emissiveMatrix", 16); + ubo.addUniform("lightmapMatrix", 16); + ubo.addUniform("reflectivityMatrix", 16); + ubo.addUniform("microSurfaceSamplerMatrix", 16); + ubo.addUniform("bumpMatrix", 16); + ubo.addUniform("vTangentSpaceParams", 2); + ubo.addUniform("reflectionMatrix", 16); + ubo.addUniform("vReflectionColor", 3); + ubo.addUniform("vAlbedoColor", 4); + ubo.addUniform("vLightingIntensity", 4); + ubo.addUniform("vReflectionMicrosurfaceInfos", 3); + ubo.addUniform("pointSize", 1); + ubo.addUniform("vReflectivityColor", 4); + ubo.addUniform("vEmissiveColor", 3); + ubo.addUniform("visibility", 1); + _pbrClearCoatConfiguration__WEBPACK_IMPORTED_MODULE_8__["PBRClearCoatConfiguration"].PrepareUniformBuffer(ubo); + _pbrAnisotropicConfiguration__WEBPACK_IMPORTED_MODULE_9__["PBRAnisotropicConfiguration"].PrepareUniformBuffer(ubo); + _pbrSheenConfiguration__WEBPACK_IMPORTED_MODULE_11__["PBRSheenConfiguration"].PrepareUniformBuffer(ubo); + _pbrSubSurfaceConfiguration__WEBPACK_IMPORTED_MODULE_12__["PBRSubSurfaceConfiguration"].PrepareUniformBuffer(ubo); + ubo.create(); + }; + /** + * Unbinds the material from the mesh + */ + PBRBaseMaterial.prototype.unbind = function () { + if (this._activeEffect) { + var needFlag = false; + if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) { + this._activeEffect.setTexture("reflection2DSampler", null); + needFlag = true; + } + if (this.subSurface.unbind(this._activeEffect)) { + needFlag = true; + } + if (needFlag) { + this._markAllSubMeshesAsTexturesDirty(); + } + } + _super.prototype.unbind.call(this); + }; + /** + * Binds the submesh data. + * @param world - The world matrix. + * @param mesh - The BJS mesh. + * @param subMesh - A submesh of the BJS mesh. + */ + PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) { + var scene = this.getScene(); + var defines = subMesh._materialDefines; + if (!defines) { + return; + } + var effect = subMesh.effect; + if (!effect) { + return; + } + this._activeEffect = effect; + // Matrices + if (!defines.INSTANCES) { + this.bindOnlyWorldMatrix(world); + } + // Normal Matrix + if (defines.OBJECTSPACE_NORMALMAP) { + world.toNormalMatrix(this._normalMatrix); + this.bindOnlyNormalMatrix(this._normalMatrix); + } + var mustRebind = this._mustRebind(scene, effect, mesh.visibility); + // Bones + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].BindBonesParameters(mesh, this._activeEffect); + var reflectionTexture = null; + var ubo = this._uniformBuffer; + if (mustRebind) { + var engine = scene.getEngine(); + ubo.bindToEffect(effect, "Material"); + this.bindViewProjection(effect); + reflectionTexture = this._getReflectionTexture(); + if (!ubo.useUbo || !this.isFrozen || !ubo.isSync) { + // Texture uniforms + if (scene.texturesEnabled) { + if (this._albedoTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].DiffuseTextureEnabled) { + ubo.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level); + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].BindTextureMatrix(this._albedoTexture, ubo, "albedo"); + } + if (this._ambientTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].AmbientTextureEnabled) { + ubo.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights); + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].BindTextureMatrix(this._ambientTexture, ubo, "ambient"); + } + if (this._opacityTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].OpacityTextureEnabled) { + ubo.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level); + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].BindTextureMatrix(this._opacityTexture, ubo, "opacity"); + } + if (reflectionTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].ReflectionTextureEnabled) { + ubo.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix()); + ubo.updateFloat2("vReflectionInfos", reflectionTexture.level, 0); + if (reflectionTexture.boundingBoxSize) { + var cubeTexture = reflectionTexture; + ubo.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition); + ubo.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize); + } + if (!defines.USEIRRADIANCEMAP) { + var polynomials = reflectionTexture.sphericalPolynomial; + if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) { + if (defines.SPHERICAL_HARMONICS) { + var preScaledHarmonics = polynomials.preScaledHarmonics; + this._activeEffect.setVector3("vSphericalL00", preScaledHarmonics.l00); + this._activeEffect.setVector3("vSphericalL1_1", preScaledHarmonics.l1_1); + this._activeEffect.setVector3("vSphericalL10", preScaledHarmonics.l10); + this._activeEffect.setVector3("vSphericalL11", preScaledHarmonics.l11); + this._activeEffect.setVector3("vSphericalL2_2", preScaledHarmonics.l2_2); + this._activeEffect.setVector3("vSphericalL2_1", preScaledHarmonics.l2_1); + this._activeEffect.setVector3("vSphericalL20", preScaledHarmonics.l20); + this._activeEffect.setVector3("vSphericalL21", preScaledHarmonics.l21); + this._activeEffect.setVector3("vSphericalL22", preScaledHarmonics.l22); + } + else { + this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z); + this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z); + this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z); + this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z); + this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z); + this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z); + this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z); + this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z); + this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z); + } + } + } + ubo.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset); + } + if (this._emissiveTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].EmissiveTextureEnabled) { + ubo.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level); + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].BindTextureMatrix(this._emissiveTexture, ubo, "emissive"); + } + if (this._lightmapTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].LightmapTextureEnabled) { + ubo.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level); + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].BindTextureMatrix(this._lightmapTexture, ubo, "lightmap"); + } + if (_materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].SpecularTextureEnabled) { + if (this._metallicTexture) { + ubo.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength); + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].BindTextureMatrix(this._metallicTexture, ubo, "reflectivity"); + } + else if (this._reflectivityTexture) { + ubo.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0); + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].BindTextureMatrix(this._reflectivityTexture, ubo, "reflectivity"); + } + if (this._microSurfaceTexture) { + ubo.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level); + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].BindTextureMatrix(this._microSurfaceTexture, ubo, "microSurfaceSampler"); + } + } + if (this._bumpTexture && engine.getCaps().standardDerivatives && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].BumpTextureEnabled && !this._disableBumpMap) { + ubo.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias); + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].BindTextureMatrix(this._bumpTexture, ubo, "bump"); + if (scene._mirroredCameraPosition) { + ubo.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0); + } + else { + ubo.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0); + } + } + } + // Point size + if (this.pointsCloud) { + ubo.updateFloat("pointSize", this.pointSize); + } + // Colors + if (defines.METALLICWORKFLOW) { + _Maths_math__WEBPACK_IMPORTED_MODULE_6__["Tmp"].Color3[0].r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic; + _Maths_math__WEBPACK_IMPORTED_MODULE_6__["Tmp"].Color3[0].g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness; + ubo.updateColor4("vReflectivityColor", _Maths_math__WEBPACK_IMPORTED_MODULE_6__["Tmp"].Color3[0], 0); + } + else { + ubo.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface); + } + ubo.updateColor3("vEmissiveColor", _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].EmissiveTextureEnabled ? this._emissiveColor : _Maths_math__WEBPACK_IMPORTED_MODULE_6__["Color3"].BlackReadOnly); + ubo.updateColor3("vReflectionColor", this._reflectionColor); + ubo.updateColor4("vAlbedoColor", this._albedoColor, this.alpha); + // Visibility + ubo.updateFloat("visibility", mesh.visibility); + // Misc + this._lightingInfos.x = this._directIntensity; + this._lightingInfos.y = this._emissiveIntensity; + this._lightingInfos.z = this._environmentIntensity; + this._lightingInfos.w = this._specularIntensity; + ubo.updateVector4("vLightingIntensity", this._lightingInfos); + } + // Textures + if (scene.texturesEnabled) { + if (this._albedoTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].DiffuseTextureEnabled) { + ubo.setTexture("albedoSampler", this._albedoTexture); + } + if (this._ambientTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].AmbientTextureEnabled) { + ubo.setTexture("ambientSampler", this._ambientTexture); + } + if (this._opacityTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].OpacityTextureEnabled) { + ubo.setTexture("opacitySampler", this._opacityTexture); + } + if (reflectionTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].ReflectionTextureEnabled) { + if (defines.LODBASEDMICROSFURACE) { + ubo.setTexture("reflectionSampler", reflectionTexture); + } + else { + ubo.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture); + ubo.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture); + ubo.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture); + } + if (defines.USEIRRADIANCEMAP) { + ubo.setTexture("irradianceSampler", reflectionTexture.irradianceTexture); + } + } + if (defines.ENVIRONMENTBRDF) { + ubo.setTexture("environmentBrdfSampler", this._environmentBRDFTexture); + } + if (this._emissiveTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].EmissiveTextureEnabled) { + ubo.setTexture("emissiveSampler", this._emissiveTexture); + } + if (this._lightmapTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].LightmapTextureEnabled) { + ubo.setTexture("lightmapSampler", this._lightmapTexture); + } + if (_materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].SpecularTextureEnabled) { + if (this._metallicTexture) { + ubo.setTexture("reflectivitySampler", this._metallicTexture); + } + else if (this._reflectivityTexture) { + ubo.setTexture("reflectivitySampler", this._reflectivityTexture); + } + if (this._microSurfaceTexture) { + ubo.setTexture("microSurfaceSampler", this._microSurfaceTexture); + } + } + if (this._bumpTexture && engine.getCaps().standardDerivatives && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].BumpTextureEnabled && !this._disableBumpMap) { + ubo.setTexture("bumpSampler", this._bumpTexture); + } + } + this.subSurface.bindForSubMesh(ubo, scene, engine, this.isFrozen, defines.LODBASEDMICROSFURACE); + this.clearCoat.bindForSubMesh(ubo, scene, engine, this._disableBumpMap, this.isFrozen, this._invertNormalMapX, this._invertNormalMapY); + this.anisotropy.bindForSubMesh(ubo, scene, this.isFrozen); + this.sheen.bindForSubMesh(ubo, scene, this.isFrozen); + // Clip plane + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].BindClipPlane(this._activeEffect, scene); + // Colors + scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor); + var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition); + var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null)); + effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1); + effect.setColor3("vAmbientColor", this._globalAmbientColor); + effect.setFloat2("vDebugMode", this.debugLimit, this.debugFactor); + } + if (mustRebind || !this.isFrozen) { + // Lights + if (scene.lightsEnabled && !this._disableLighting) { + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD); + } + // View + if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== _scene__WEBPACK_IMPORTED_MODULE_5__["Scene"].FOGMODE_NONE || reflectionTexture) { + this.bindView(effect); + } + // Fog + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].BindFogParameters(scene, mesh, this._activeEffect, true); + // Morph targets + if (defines.NUM_MORPH_INFLUENCERS) { + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].BindMorphTargetParameters(mesh, this._activeEffect); + } + // image processing + this._imageProcessingConfiguration.bind(this._activeEffect); + // Log. depth + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].BindLogDepth(defines, this._activeEffect, scene); + } + ubo.update(); + this._afterBind(mesh, this._activeEffect); + }; + /** + * Returns the animatable textures. + * @returns - Array of animatable textures. + */ + PBRBaseMaterial.prototype.getAnimatables = function () { + var results = []; + if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) { + results.push(this._albedoTexture); + } + if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) { + results.push(this._ambientTexture); + } + if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) { + results.push(this._opacityTexture); + } + if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) { + results.push(this._reflectionTexture); + } + if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) { + results.push(this._emissiveTexture); + } + if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) { + results.push(this._metallicTexture); + } + else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) { + results.push(this._reflectivityTexture); + } + if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) { + results.push(this._bumpTexture); + } + if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) { + results.push(this._lightmapTexture); + } + this.subSurface.getAnimatables(results); + this.clearCoat.getAnimatables(results); + this.sheen.getAnimatables(results); + this.anisotropy.getAnimatables(results); + return results; + }; + /** + * Returns the texture used for reflections. + * @returns - Reflection texture if present. Otherwise, returns the environment texture. + */ + PBRBaseMaterial.prototype._getReflectionTexture = function () { + if (this._reflectionTexture) { + return this._reflectionTexture; + } + return this.getScene().environmentTexture; + }; + /** + * Returns an array of the actively used textures. + * @returns - Array of BaseTextures + */ + PBRBaseMaterial.prototype.getActiveTextures = function () { + var activeTextures = _super.prototype.getActiveTextures.call(this); + if (this._albedoTexture) { + activeTextures.push(this._albedoTexture); + } + if (this._ambientTexture) { + activeTextures.push(this._ambientTexture); + } + if (this._opacityTexture) { + activeTextures.push(this._opacityTexture); + } + if (this._reflectionTexture) { + activeTextures.push(this._reflectionTexture); + } + if (this._emissiveTexture) { + activeTextures.push(this._emissiveTexture); + } + if (this._reflectivityTexture) { + activeTextures.push(this._reflectivityTexture); + } + if (this._metallicTexture) { + activeTextures.push(this._metallicTexture); + } + if (this._microSurfaceTexture) { + activeTextures.push(this._microSurfaceTexture); + } + if (this._bumpTexture) { + activeTextures.push(this._bumpTexture); + } + if (this._lightmapTexture) { + activeTextures.push(this._lightmapTexture); + } + this.subSurface.getActiveTextures(activeTextures); + this.clearCoat.getActiveTextures(activeTextures); + this.sheen.getActiveTextures(activeTextures); + this.anisotropy.getActiveTextures(activeTextures); + return activeTextures; + }; + /** + * Checks to see if a texture is used in the material. + * @param texture - Base texture to use. + * @returns - Boolean specifying if a texture is used in the material. + */ + PBRBaseMaterial.prototype.hasTexture = function (texture) { + if (_super.prototype.hasTexture.call(this, texture)) { + return true; + } + if (this._albedoTexture === texture) { + return true; + } + if (this._ambientTexture === texture) { + return true; + } + if (this._opacityTexture === texture) { + return true; + } + if (this._reflectionTexture === texture) { + return true; + } + if (this._reflectivityTexture === texture) { + return true; + } + if (this._metallicTexture === texture) { + return true; + } + if (this._microSurfaceTexture === texture) { + return true; + } + if (this._bumpTexture === texture) { + return true; + } + if (this._lightmapTexture === texture) { + return true; + } + return this.subSurface.hasTexture(texture) || + this.clearCoat.hasTexture(texture) || + this.sheen.hasTexture(texture) || + this.anisotropy.hasTexture(texture); + }; + /** + * Disposes the resources of the material. + * @param forceDisposeEffect - Forces the disposal of effects. + * @param forceDisposeTextures - Forces the disposal of all textures. + */ + PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) { + if (forceDisposeTextures) { + if (this._albedoTexture) { + this._albedoTexture.dispose(); + } + if (this._ambientTexture) { + this._ambientTexture.dispose(); + } + if (this._opacityTexture) { + this._opacityTexture.dispose(); + } + if (this._reflectionTexture) { + this._reflectionTexture.dispose(); + } + if (this._environmentBRDFTexture && this.getScene().environmentBRDFTexture !== this._environmentBRDFTexture) { + this._environmentBRDFTexture.dispose(); + } + if (this._emissiveTexture) { + this._emissiveTexture.dispose(); + } + if (this._metallicTexture) { + this._metallicTexture.dispose(); + } + if (this._reflectivityTexture) { + this._reflectivityTexture.dispose(); + } + if (this._bumpTexture) { + this._bumpTexture.dispose(); + } + if (this._lightmapTexture) { + this._lightmapTexture.dispose(); + } + } + this.subSurface.dispose(forceDisposeTextures); + this.clearCoat.dispose(forceDisposeTextures); + this.sheen.dispose(forceDisposeTextures); + this.anisotropy.dispose(forceDisposeTextures); + this._renderTargets.dispose(); + if (this._imageProcessingConfiguration && this._imageProcessingObserver) { + this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver); + } + _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures); + }; + /** + * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use. + */ + PBRBaseMaterial.PBRMATERIAL_OPAQUE = 0; + /** + * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value. + */ + PBRBaseMaterial.PBRMATERIAL_ALPHATEST = 1; + /** + * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer. + */ + PBRBaseMaterial.PBRMATERIAL_ALPHABLEND = 2; + /** + * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer. + * They are also discarded below the alpha cutoff threshold to improve performances. + */ + PBRBaseMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3; + /** + * Defines the default value of how much AO map is occluding the analytical lights + * (point spot...). + */ + PBRBaseMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 0; + /** + * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law. + */ + PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0; + /** + * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document + * to enhance interoperability with other engines. + */ + PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1; + /** + * PBRMaterialLightFalloff Standard: light is falling off like in the standard material + * to enhance interoperability with other materials. + */ + PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2; + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsImageProcessingConfiguration"])() + ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsMiscDirty") + ], PBRBaseMaterial.prototype, "debugMode", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], PBRBaseMaterial.prototype, "transparencyMode", null); + return PBRBaseMaterial; +}(_Materials_pushMaterial__WEBPACK_IMPORTED_MODULE_16__["PushMaterial"])); + + + +/***/ }), + +/***/ "./Materials/PBR/pbrBaseSimpleMaterial.ts": +/*!************************************************!*\ + !*** ./Materials/PBR/pbrBaseSimpleMaterial.ts ***! + \************************************************/ +/*! exports provided: PBRBaseSimpleMaterial */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PBRBaseSimpleMaterial", function() { return PBRBaseSimpleMaterial; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./pbrBaseMaterial */ "./Materials/PBR/pbrBaseMaterial.ts"); + + + + +/** + * The Physically based simple base material of BJS. + * + * This enables better naming and convention enforcements on top of the pbrMaterial. + * It is used as the base class for both the specGloss and metalRough conventions. + */ +var PBRBaseSimpleMaterial = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PBRBaseSimpleMaterial, _super); + /** + * Instantiates a new PBRMaterial instance. + * + * @param name The material name + * @param scene The scene the material will be use in. + */ + function PBRBaseSimpleMaterial(name, scene) { + var _this = _super.call(this, name, scene) || this; + /** + * Number of Simultaneous lights allowed on the material. + */ + _this.maxSimultaneousLights = 4; + /** + * If sets to true, disables all the lights affecting the material. + */ + _this.disableLighting = false; + /** + * If sets to true, x component of normal map value will invert (x = 1.0 - x). + */ + _this.invertNormalMapX = false; + /** + * If sets to true, y component of normal map value will invert (y = 1.0 - y). + */ + _this.invertNormalMapY = false; + /** + * Emissivie color used to self-illuminate the model. + */ + _this.emissiveColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color3"](0, 0, 0); + /** + * Occlusion Channel Strenght. + */ + _this.occlusionStrength = 1.0; + /** + * If true, the light map contains occlusion information instead of lighting info. + */ + _this.useLightmapAsShadowmap = false; + _this._useAlphaFromAlbedoTexture = true; + _this._useAmbientInGrayScale = true; + return _this; + } + Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", { + /** + * Gets the current double sided mode. + */ + get: function () { + return this._twoSidedLighting; + }, + /** + * If sets to true and backfaceCulling is false, normals will be flipped on the backside. + */ + set: function (value) { + if (this._twoSidedLighting === value) { + return; + } + this._twoSidedLighting = value; + this.backFaceCulling = !value; + this._markAllSubMeshesAsTexturesDirty(); + }, + enumerable: true, + configurable: true + }); + PBRBaseSimpleMaterial.prototype.getClassName = function () { + return "PBRBaseSimpleMaterial"; + }; + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsLightsDirty") + ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsLightsDirty") + ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture") + ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty", "_bumpTexture") + ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])("emissive"), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength") + ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty", "_ambientTexture") + ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff") + ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], PBRBaseSimpleMaterial.prototype, "doubleSided", null); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty", null) + ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0); + return PBRBaseSimpleMaterial; +}(_pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_3__["PBRBaseMaterial"])); + + + +/***/ }), + +/***/ "./Materials/PBR/pbrClearCoatConfiguration.ts": +/*!****************************************************!*\ + !*** ./Materials/PBR/pbrClearCoatConfiguration.ts ***! + \****************************************************/ +/*! exports provided: PBRClearCoatConfiguration */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PBRClearCoatConfiguration", function() { return PBRClearCoatConfiguration; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _materialFlags__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../materialFlags */ "./Materials/materialFlags.ts"); +/* harmony import */ var _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Materials/materialHelper */ "./Materials/materialHelper.ts"); + + + + + +/** + * Define the code related to the clear coat parameters of the pbr material. + */ +var PBRClearCoatConfiguration = /** @class */ (function () { + /** + * Instantiate a new istance of clear coat configuration. + * @param markAllSubMeshesAsTexturesDirty Callback to flag the material to dirty + */ + function PBRClearCoatConfiguration(markAllSubMeshesAsTexturesDirty) { + this._isEnabled = false; + /** + * Defines if the clear coat is enabled in the material. + */ + this.isEnabled = false; + /** + * Defines the clear coat layer strength (between 0 and 1) it defaults to 1. + */ + this.intensity = 1; + /** + * Defines the clear coat layer roughness. + */ + this.roughness = 0; + this._indiceOfRefraction = PBRClearCoatConfiguration._DefaultIndiceOfRefraction; + /** + * Defines the indice of refraction of the clear coat. + * This defaults to 1.5 corresponding to a 0.04 f0 or a 4% reflectance at normal incidence + * The default fits with a polyurethane material. + * Changing the default value is more performance intensive. + */ + this.indiceOfRefraction = PBRClearCoatConfiguration._DefaultIndiceOfRefraction; + this._texture = null; + /** + * Stores the clear coat values in a texture. + */ + this.texture = null; + this._bumpTexture = null; + /** + * Define the clear coat specific bump texture. + */ + this.bumpTexture = null; + this._isTintEnabled = false; + /** + * Defines if the clear coat tint is enabled in the material. + */ + this.isTintEnabled = false; + /** + * Defines the clear coat tint of the material. + * This is only use if tint is enabled + */ + this.tintColor = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color3"].White(); + /** + * Defines the distance at which the tint color should be found in the + * clear coat media. + * This is only use if tint is enabled + */ + this.tintColorAtDistance = 1; + /** + * Defines the clear coat layer thickness. + * This is only use if tint is enabled + */ + this.tintThickness = 1; + this._tintTexture = null; + /** + * Stores the clear tint values in a texture. + * rgb is tint + * a is a thickness factor + */ + this.tintTexture = null; + this._internalMarkAllSubMeshesAsTexturesDirty = markAllSubMeshesAsTexturesDirty; + } + /** @hidden */ + PBRClearCoatConfiguration.prototype._markAllSubMeshesAsTexturesDirty = function () { + this._internalMarkAllSubMeshesAsTexturesDirty(); + }; + /** + * Gets wehter the submesh is ready to be used or not. + * @param defines the list of "defines" to update. + * @param scene defines the scene the material belongs to. + * @param engine defines the engine the material belongs to. + * @param disableBumpMap defines wether the material disables bump or not. + * @returns - boolean indicating that the submesh is ready or not. + */ + PBRClearCoatConfiguration.prototype.isReadyForSubMesh = function (defines, scene, engine, disableBumpMap) { + if (defines._areTexturesDirty) { + if (scene.texturesEnabled) { + if (this._texture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].ClearCoatTextureEnabled) { + if (!this._texture.isReadyOrNotBlocking()) { + return false; + } + } + if (engine.getCaps().standardDerivatives && this._bumpTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].ClearCoatBumpTextureEnabled && !disableBumpMap) { + // Bump texture cannot be not blocking. + if (!this._bumpTexture.isReady()) { + return false; + } + } + if (this._isTintEnabled && this._tintTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].ClearCoatTintTextureEnabled) { + if (!this._tintTexture.isReadyOrNotBlocking()) { + return false; + } + } + } + } + return true; + }; + /** + * Checks to see if a texture is used in the material. + * @param defines the list of "defines" to update. + * @param scene defines the scene to the material belongs to. + */ + PBRClearCoatConfiguration.prototype.prepareDefines = function (defines, scene) { + if (this._isEnabled) { + defines.CLEARCOAT = true; + if (defines._areTexturesDirty) { + if (scene.texturesEnabled) { + if (this._texture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].ClearCoatTextureEnabled) { + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_4__["MaterialHelper"].PrepareDefinesForMergedUV(this._texture, defines, "CLEARCOAT_TEXTURE"); + } + else { + defines.CLEARCOAT_TEXTURE = false; + } + if (this._bumpTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].ClearCoatBumpTextureEnabled) { + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_4__["MaterialHelper"].PrepareDefinesForMergedUV(this._bumpTexture, defines, "CLEARCOAT_BUMP"); + } + else { + defines.CLEARCOAT_BUMP = false; + } + defines.CLEARCOAT_DEFAULTIOR = this._indiceOfRefraction === PBRClearCoatConfiguration._DefaultIndiceOfRefraction; + if (this._isTintEnabled) { + defines.CLEARCOAT_TINT = true; + if (this._tintTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].ClearCoatTintTextureEnabled) { + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_4__["MaterialHelper"].PrepareDefinesForMergedUV(this._tintTexture, defines, "CLEARCOAT_TINT_TEXTURE"); + } + else { + defines.CLEARCOAT_TINT_TEXTURE = false; + } + } + else { + defines.CLEARCOAT_TINT = false; + defines.CLEARCOAT_TINT_TEXTURE = false; + } + } + } + } + else { + defines.CLEARCOAT = false; + defines.CLEARCOAT_TEXTURE = false; + defines.CLEARCOAT_BUMP = false; + defines.CLEARCOAT_TINT = false; + defines.CLEARCOAT_TINT_TEXTURE = false; + } + }; + /** + * Binds the material data. + * @param uniformBuffer defines the Uniform buffer to fill in. + * @param scene defines the scene the material belongs to. + * @param engine defines the engine the material belongs to. + * @param disableBumpMap defines wether the material disables bump or not. + * @param isFrozen defines wether the material is frozen or not. + * @param invertNormalMapX If sets to true, x component of normal map value will be inverted (x = 1.0 - x). + * @param invertNormalMapY If sets to true, y component of normal map value will be inverted (y = 1.0 - y). + */ + PBRClearCoatConfiguration.prototype.bindForSubMesh = function (uniformBuffer, scene, engine, disableBumpMap, isFrozen, invertNormalMapX, invertNormalMapY) { + if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) { + if (this._texture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].ClearCoatTextureEnabled) { + uniformBuffer.updateFloat2("vClearCoatInfos", this._texture.coordinatesIndex, this._texture.level); + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_4__["MaterialHelper"].BindTextureMatrix(this._texture, uniformBuffer, "clearCoat"); + } + if (this._bumpTexture && engine.getCaps().standardDerivatives && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].ClearCoatTextureEnabled && !disableBumpMap) { + uniformBuffer.updateFloat2("vClearCoatBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level); + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_4__["MaterialHelper"].BindTextureMatrix(this._bumpTexture, uniformBuffer, "clearCoatBump"); + if (scene._mirroredCameraPosition) { + uniformBuffer.updateFloat2("vClearCoatTangentSpaceParams", invertNormalMapX ? 1.0 : -1.0, invertNormalMapY ? 1.0 : -1.0); + } + else { + uniformBuffer.updateFloat2("vClearCoatTangentSpaceParams", invertNormalMapX ? -1.0 : 1.0, invertNormalMapY ? -1.0 : 1.0); + } + } + if (this._tintTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].ClearCoatTintTextureEnabled) { + uniformBuffer.updateFloat2("vClearCoatTintInfos", this._tintTexture.coordinatesIndex, this._tintTexture.level); + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_4__["MaterialHelper"].BindTextureMatrix(this._tintTexture, uniformBuffer, "clearCoatTint"); + } + // Clear Coat General params + uniformBuffer.updateFloat2("vClearCoatParams", this.intensity, this.roughness); + // Clear Coat Refraction params + var a = 1 - this._indiceOfRefraction; + var b = 1 + this._indiceOfRefraction; + var f0 = Math.pow((-a / b), 2); // Schlicks approx: (ior1 - ior2) / (ior1 + ior2) where ior2 for air is close to vacuum = 1. + var eta = 1 / this._indiceOfRefraction; + uniformBuffer.updateFloat4("vClearCoatRefractionParams", f0, eta, a, b); + if (this._isTintEnabled) { + uniformBuffer.updateFloat4("vClearCoatTintParams", this.tintColor.r, this.tintColor.g, this.tintColor.b, Math.max(0.00001, this.tintThickness)); + uniformBuffer.updateFloat("clearCoatColorAtDistance", Math.max(0.00001, this.tintColorAtDistance)); + } + } + // Textures + if (scene.texturesEnabled) { + if (this._texture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].ClearCoatTextureEnabled) { + uniformBuffer.setTexture("clearCoatSampler", this._texture); + } + if (this._bumpTexture && engine.getCaps().standardDerivatives && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].ClearCoatBumpTextureEnabled && !disableBumpMap) { + uniformBuffer.setTexture("clearCoatBumpSampler", this._bumpTexture); + } + if (this._isTintEnabled && this._tintTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].ClearCoatTintTextureEnabled) { + uniformBuffer.setTexture("clearCoatTintSampler", this._tintTexture); + } + } + }; + /** + * Checks to see if a texture is used in the material. + * @param texture - Base texture to use. + * @returns - Boolean specifying if a texture is used in the material. + */ + PBRClearCoatConfiguration.prototype.hasTexture = function (texture) { + if (this._texture === texture) { + return true; + } + if (this._bumpTexture === texture) { + return true; + } + if (this._tintTexture === texture) { + return true; + } + return false; + }; + /** + * Returns an array of the actively used textures. + * @param activeTextures Array of BaseTextures + */ + PBRClearCoatConfiguration.prototype.getActiveTextures = function (activeTextures) { + if (this._texture) { + activeTextures.push(this._texture); + } + if (this._bumpTexture) { + activeTextures.push(this._bumpTexture); + } + if (this._tintTexture) { + activeTextures.push(this._tintTexture); + } + }; + /** + * Returns the animatable textures. + * @param animatables Array of animatable textures. + */ + PBRClearCoatConfiguration.prototype.getAnimatables = function (animatables) { + if (this._texture && this._texture.animations && this._texture.animations.length > 0) { + animatables.push(this._texture); + } + if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) { + animatables.push(this._bumpTexture); + } + if (this._tintTexture && this._tintTexture.animations && this._tintTexture.animations.length > 0) { + animatables.push(this._tintTexture); + } + }; + /** + * Disposes the resources of the material. + * @param forceDisposeTextures - Forces the disposal of all textures. + */ + PBRClearCoatConfiguration.prototype.dispose = function (forceDisposeTextures) { + if (forceDisposeTextures) { + if (this._texture) { + this._texture.dispose(); + } + if (this._bumpTexture) { + this._bumpTexture.dispose(); + } + if (this._tintTexture) { + this._tintTexture.dispose(); + } + } + }; + /** + * Get the current class name of the texture useful for serialization or dynamic coding. + * @returns "PBRClearCoatConfiguration" + */ + PBRClearCoatConfiguration.prototype.getClassName = function () { + return "PBRClearCoatConfiguration"; + }; + /** + * Add fallbacks to the effect fallbacks list. + * @param defines defines the Base texture to use. + * @param fallbacks defines the current fallback list. + * @param currentRank defines the current fallback rank. + * @returns the new fallback rank. + */ + PBRClearCoatConfiguration.AddFallbacks = function (defines, fallbacks, currentRank) { + if (defines.CLEARCOAT_BUMP) { + fallbacks.addFallback(currentRank++, "CLEARCOAT_BUMP"); + } + if (defines.CLEARCOAT_TINT) { + fallbacks.addFallback(currentRank++, "CLEARCOAT_TINT"); + } + if (defines.CLEARCOAT) { + fallbacks.addFallback(currentRank++, "CLEARCOAT"); + } + return currentRank; + }; + /** + * Add the required uniforms to the current list. + * @param uniforms defines the current uniform list. + */ + PBRClearCoatConfiguration.AddUniforms = function (uniforms) { + uniforms.push("vClearCoatTangentSpaceParams", "vClearCoatParams", "vClearCoatRefractionParams", "vClearCoatTintParams", "clearCoatColorAtDistance", "clearCoatMatrix", "clearCoatBumpMatrix", "clearCoatTintMatrix", "vClearCoatInfos", "vClearCoatBumpInfos", "vClearCoatTintInfos"); + }; + /** + * Add the required samplers to the current list. + * @param samplers defines the current sampler list. + */ + PBRClearCoatConfiguration.AddSamplers = function (samplers) { + samplers.push("clearCoatSampler", "clearCoatBumpSampler", "clearCoatTintSampler"); + }; + /** + * Add the required uniforms to the current buffer. + * @param uniformBuffer defines the current uniform buffer. + */ + PBRClearCoatConfiguration.PrepareUniformBuffer = function (uniformBuffer) { + uniformBuffer.addUniform("vClearCoatParams", 2); + uniformBuffer.addUniform("vClearCoatRefractionParams", 4); + uniformBuffer.addUniform("vClearCoatInfos", 2); + uniformBuffer.addUniform("clearCoatMatrix", 16); + uniformBuffer.addUniform("vClearCoatBumpInfos", 2); + uniformBuffer.addUniform("vClearCoatTangentSpaceParams", 2); + uniformBuffer.addUniform("clearCoatBumpMatrix", 16); + uniformBuffer.addUniform("vClearCoatTintParams", 4); + uniformBuffer.addUniform("clearCoatColorAtDistance", 1); + uniformBuffer.addUniform("vClearCoatTintInfos", 2); + uniformBuffer.addUniform("clearCoatTintMatrix", 16); + }; + /** + * Makes a duplicate of the current configuration into another one. + * @param clearCoatConfiguration define the config where to copy the info + */ + PBRClearCoatConfiguration.prototype.copyTo = function (clearCoatConfiguration) { + _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Clone(function () { return clearCoatConfiguration; }, this); + }; + /** + * Serializes this clear coat configuration. + * @returns - An object with the serialized config. + */ + PBRClearCoatConfiguration.prototype.serialize = function () { + return _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(this); + }; + /** + * Parses a Clear Coat Configuration from a serialized object. + * @param source - Serialized object. + */ + PBRClearCoatConfiguration.prototype.parse = function (source) { + var _this = this; + _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(function () { return _this; }, source, null); + }; + /** + * This defaults to 1.5 corresponding to a 0.04 f0 or a 4% reflectance at normal incidence + * The default fits with a polyurethane material. + */ + PBRClearCoatConfiguration._DefaultIndiceOfRefraction = 1.5; + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], PBRClearCoatConfiguration.prototype, "_isEnabled", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRClearCoatConfiguration.prototype, "isEnabled", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], PBRClearCoatConfiguration.prototype, "intensity", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], PBRClearCoatConfiguration.prototype, "roughness", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], PBRClearCoatConfiguration.prototype, "_indiceOfRefraction", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRClearCoatConfiguration.prototype, "indiceOfRefraction", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])() + ], PBRClearCoatConfiguration.prototype, "_texture", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRClearCoatConfiguration.prototype, "texture", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])() + ], PBRClearCoatConfiguration.prototype, "_bumpTexture", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRClearCoatConfiguration.prototype, "bumpTexture", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], PBRClearCoatConfiguration.prototype, "_isTintEnabled", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRClearCoatConfiguration.prototype, "isTintEnabled", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])() + ], PBRClearCoatConfiguration.prototype, "tintColor", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], PBRClearCoatConfiguration.prototype, "tintColorAtDistance", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], PBRClearCoatConfiguration.prototype, "tintThickness", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])() + ], PBRClearCoatConfiguration.prototype, "_tintTexture", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRClearCoatConfiguration.prototype, "tintTexture", void 0); + return PBRClearCoatConfiguration; +}()); + + + +/***/ }), + +/***/ "./Materials/PBR/pbrMaterial.ts": +/*!**************************************!*\ + !*** ./Materials/PBR/pbrMaterial.ts ***! + \**************************************/ +/*! exports provided: PBRMaterial */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PBRMaterial", function() { return PBRMaterial; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _Misc_brdfTextureTools__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/brdfTextureTools */ "./Misc/brdfTextureTools.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./pbrBaseMaterial */ "./Materials/PBR/pbrBaseMaterial.ts"); +/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Misc/typeStore */ "./Misc/typeStore.ts"); + + + + + + +/** + * The Physically based material of BJS. + * + * This offers the main features of a standard PBR material. + * For more information, please refer to the documentation : + * https://doc.babylonjs.com/how_to/physically_based_rendering + */ +var PBRMaterial = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PBRMaterial, _super); + /** + * Instantiates a new PBRMaterial instance. + * + * @param name The material name + * @param scene The scene the material will be use in. + */ + function PBRMaterial(name, scene) { + var _this = _super.call(this, name, scene) || this; + /** + * Intensity of the direct lights e.g. the four lights available in your scene. + * This impacts both the direct diffuse and specular highlights. + */ + _this.directIntensity = 1.0; + /** + * Intensity of the emissive part of the material. + * This helps controlling the emissive effect without modifying the emissive color. + */ + _this.emissiveIntensity = 1.0; + /** + * Intensity of the environment e.g. how much the environment will light the object + * either through harmonics for rough material or through the refelction for shiny ones. + */ + _this.environmentIntensity = 1.0; + /** + * This is a special control allowing the reduction of the specular highlights coming from the + * four lights of the scene. Those highlights may not be needed in full environment lighting. + */ + _this.specularIntensity = 1.0; + /** + * Debug Control allowing disabling the bump map on this material. + */ + _this.disableBumpMap = false; + /** + * AKA Occlusion Texture Intensity in other nomenclature. + */ + _this.ambientTextureStrength = 1.0; + /** + * Defines how much the AO map is occluding the analytical lights (point spot...). + * 1 means it completely occludes it + * 0 mean it has no impact + */ + _this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS; + /** + * The color of a material in ambient lighting. + */ + _this.ambientColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Color3"](0, 0, 0); + /** + * AKA Diffuse Color in other nomenclature. + */ + _this.albedoColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Color3"](1, 1, 1); + /** + * AKA Specular Color in other nomenclature. + */ + _this.reflectivityColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Color3"](1, 1, 1); + /** + * The color reflected from the material. + */ + _this.reflectionColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Color3"](1.0, 1.0, 1.0); + /** + * The color emitted from the material. + */ + _this.emissiveColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Color3"](0, 0, 0); + /** + * AKA Glossiness in other nomenclature. + */ + _this.microSurface = 1.0; + /** + * If true, the light map contains occlusion information instead of lighting info. + */ + _this.useLightmapAsShadowmap = false; + /** + * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending. + */ + _this.useAlphaFromAlbedoTexture = false; + /** + * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations. + */ + _this.forceAlphaTest = false; + /** + * Defines the alpha limits in alpha test mode. + */ + _this.alphaCutOff = 0.4; + /** + * Specifies that the material will keep the specular highlights over a transparent surface (only the most limunous ones). + * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind. + */ + _this.useSpecularOverAlpha = true; + /** + * Specifies if the reflectivity texture contains the glossiness information in its alpha channel. + */ + _this.useMicroSurfaceFromReflectivityMapAlpha = false; + /** + * Specifies if the metallic texture contains the roughness information in its alpha channel. + */ + _this.useRoughnessFromMetallicTextureAlpha = true; + /** + * Specifies if the metallic texture contains the roughness information in its green channel. + */ + _this.useRoughnessFromMetallicTextureGreen = false; + /** + * Specifies if the metallic texture contains the metallness information in its blue channel. + */ + _this.useMetallnessFromMetallicTextureBlue = false; + /** + * Specifies if the metallic texture contains the ambient occlusion information in its red channel. + */ + _this.useAmbientOcclusionFromMetallicTextureRed = false; + /** + * Specifies if the ambient texture contains the ambient occlusion information in its red channel only. + */ + _this.useAmbientInGrayScale = false; + /** + * In case the reflectivity map does not contain the microsurface information in its alpha channel, + * The material will try to infer what glossiness each pixel should be. + */ + _this.useAutoMicroSurfaceFromReflectivityMap = false; + /** + * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones). + * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind. + */ + _this.useRadianceOverAlpha = true; + /** + * Allows using an object space normal map (instead of tangent space). + */ + _this.useObjectSpaceNormalMap = false; + /** + * Allows using the bump map in parallax mode. + */ + _this.useParallax = false; + /** + * Allows using the bump map in parallax occlusion mode. + */ + _this.useParallaxOcclusion = false; + /** + * Controls the scale bias of the parallax mode. + */ + _this.parallaxScaleBias = 0.05; + /** + * If sets to true, disables all the lights affecting the material. + */ + _this.disableLighting = false; + /** + * Force the shader to compute irradiance in the fragment shader in order to take bump in account. + */ + _this.forceIrradianceInFragment = false; + /** + * Number of Simultaneous lights allowed on the material. + */ + _this.maxSimultaneousLights = 4; + /** + * If sets to true, x component of normal map value will invert (x = 1.0 - x). + */ + _this.invertNormalMapX = false; + /** + * If sets to true, y component of normal map value will invert (y = 1.0 - y). + */ + _this.invertNormalMapY = false; + /** + * If sets to true and backfaceCulling is false, normals will be flipped on the backside. + */ + _this.twoSidedLighting = false; + /** + * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested. + * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel) + */ + _this.useAlphaFresnel = false; + /** + * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested. + * And/Or occlude the blended part. (alpha stays linear to compute the fresnel) + */ + _this.useLinearAlphaFresnel = false; + /** + * Let user defines the brdf lookup texture used for IBL. + * A default 8bit version is embedded but you could point at : + * * Default texture: https://assets.babylonjs.com/environments/correlatedMSBRDF.png + * * Default 16bit pixel depth texture: https://assets.babylonjs.com/environments/correlatedMSBRDF.dds + * * LEGACY Default None correlated https://assets.babylonjs.com/environments/uncorrelatedBRDF.png + * * LEGACY Default None correlated 16bit pixel depth https://assets.babylonjs.com/environments/uncorrelatedBRDF.dds + */ + _this.environmentBRDFTexture = null; + /** + * Force normal to face away from face. + */ + _this.forceNormalForward = false; + /** + * Enables specular anti aliasing in the PBR shader. + * It will both interacts on the Geometry for analytical and IBL lighting. + * It also prefilter the roughness map based on the bump values. + */ + _this.enableSpecularAntiAliasing = false; + /** + * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal + * makes the reflect vector face the model (under horizon). + */ + _this.useHorizonOcclusion = true; + /** + * This parameters will enable/disable radiance occlusion by preventing the radiance to lit + * too much the area relying on ambient texture to define their ambient occlusion. + */ + _this.useRadianceOcclusion = true; + /** + * If set to true, no lighting calculations will be applied. + */ + _this.unlit = false; + _this._environmentBRDFTexture = _Misc_brdfTextureTools__WEBPACK_IMPORTED_MODULE_2__["BRDFTextureTools"].GetEnvironmentBRDFTexture(scene); + return _this; + } + Object.defineProperty(PBRMaterial.prototype, "refractionTexture", { + /** + * Stores the refracted light information in a texture. + */ + get: function () { + return this.subSurface.refractionTexture; + }, + set: function (value) { + this.subSurface.refractionTexture = value; + if (value) { + this.subSurface.isRefractionEnabled = true; + } + else if (!this.subSurface.linkRefractionWithTransparency) { + this.subSurface.isRefractionEnabled = false; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(PBRMaterial.prototype, "indexOfRefraction", { + /** + * source material index of refraction (IOR)' / 'destination material IOR. + */ + get: function () { + return 1 / this.subSurface.indexOfRefraction; + }, + set: function (value) { + this.subSurface.indexOfRefraction = 1 / value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(PBRMaterial.prototype, "invertRefractionY", { + /** + * Controls if refraction needs to be inverted on Y. This could be useful for procedural texture. + */ + get: function () { + return this.subSurface.invertRefractionY; + }, + set: function (value) { + this.subSurface.invertRefractionY = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(PBRMaterial.prototype, "linkRefractionWithTransparency", { + /** + * This parameters will make the material used its opacity to control how much it is refracting aginst not. + * Materials half opaque for instance using refraction could benefit from this control. + */ + get: function () { + return this.subSurface.linkRefractionWithTransparency; + }, + set: function (value) { + this.subSurface.linkRefractionWithTransparency = value; + if (value) { + this.subSurface.isRefractionEnabled = true; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", { + /** + * BJS is using an harcoded light falloff based on a manually sets up range. + * In PBR, one way to represents the fallof is to use the inverse squared root algorythm. + * This parameter can help you switch back to the BJS mode in order to create scenes using both materials. + */ + get: function () { + return this._lightFalloff === _pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_4__["PBRBaseMaterial"].LIGHTFALLOFF_PHYSICAL; + }, + /** + * BJS is using an harcoded light falloff based on a manually sets up range. + * In PBR, one way to represents the fallof is to use the inverse squared root algorythm. + * This parameter can help you switch back to the BJS mode in order to create scenes using both materials. + */ + set: function (value) { + if (value !== this.usePhysicalLightFalloff) { + // Ensure the effect will be rebuilt. + this._markAllSubMeshesAsTexturesDirty(); + if (value) { + this._lightFalloff = _pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_4__["PBRBaseMaterial"].LIGHTFALLOFF_PHYSICAL; + } + else { + this._lightFalloff = _pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_4__["PBRBaseMaterial"].LIGHTFALLOFF_STANDARD; + } + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", { + /** + * In order to support the falloff compatibility with gltf, a special mode has been added + * to reproduce the gltf light falloff. + */ + get: function () { + return this._lightFalloff === _pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_4__["PBRBaseMaterial"].LIGHTFALLOFF_GLTF; + }, + /** + * In order to support the falloff compatibility with gltf, a special mode has been added + * to reproduce the gltf light falloff. + */ + set: function (value) { + if (value !== this.useGLTFLightFalloff) { + // Ensure the effect will be rebuilt. + this._markAllSubMeshesAsTexturesDirty(); + if (value) { + this._lightFalloff = _pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_4__["PBRBaseMaterial"].LIGHTFALLOFF_GLTF; + } + else { + this._lightFalloff = _pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_4__["PBRBaseMaterial"].LIGHTFALLOFF_STANDARD; + } + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", { + /** + * Gets the image processing configuration used either in this material. + */ + get: function () { + return this._imageProcessingConfiguration; + }, + /** + * Sets the Default image processing configuration used either in the this material. + * + * If sets to null, the scene one is in use. + */ + set: function (value) { + this._attachImageProcessingConfiguration(value); + // Ensure the effect will be rebuilt. + this._markAllSubMeshesAsTexturesDirty(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", { + /** + * Gets wether the color curves effect is enabled. + */ + get: function () { + return this.imageProcessingConfiguration.colorCurvesEnabled; + }, + /** + * Sets wether the color curves effect is enabled. + */ + set: function (value) { + this.imageProcessingConfiguration.colorCurvesEnabled = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", { + /** + * Gets wether the color grading effect is enabled. + */ + get: function () { + return this.imageProcessingConfiguration.colorGradingEnabled; + }, + /** + * Gets wether the color grading effect is enabled. + */ + set: function (value) { + this.imageProcessingConfiguration.colorGradingEnabled = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", { + /** + * Gets wether tonemapping is enabled or not. + */ + get: function () { + return this._imageProcessingConfiguration.toneMappingEnabled; + }, + /** + * Sets wether tonemapping is enabled or not + */ + set: function (value) { + this._imageProcessingConfiguration.toneMappingEnabled = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(PBRMaterial.prototype, "cameraExposure", { + /** + * The camera exposure used on this material. + * This property is here and not in the camera to allow controlling exposure without full screen post process. + * This corresponds to a photographic exposure. + */ + get: function () { + return this._imageProcessingConfiguration.exposure; + }, + /** + * The camera exposure used on this material. + * This property is here and not in the camera to allow controlling exposure without full screen post process. + * This corresponds to a photographic exposure. + */ + set: function (value) { + this._imageProcessingConfiguration.exposure = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(PBRMaterial.prototype, "cameraContrast", { + /** + * Gets The camera contrast used on this material. + */ + get: function () { + return this._imageProcessingConfiguration.contrast; + }, + /** + * Sets The camera contrast used on this material. + */ + set: function (value) { + this._imageProcessingConfiguration.contrast = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", { + /** + * Gets the Color Grading 2D Lookup Texture. + */ + get: function () { + return this._imageProcessingConfiguration.colorGradingTexture; + }, + /** + * Sets the Color Grading 2D Lookup Texture. + */ + set: function (value) { + this._imageProcessingConfiguration.colorGradingTexture = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", { + /** + * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT). + * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects. + * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image; + * corresponding to low luminance, medium luminance, and high luminance areas respectively. + */ + get: function () { + return this._imageProcessingConfiguration.colorCurves; + }, + /** + * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT). + * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects. + * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image; + * corresponding to low luminance, medium luminance, and high luminance areas respectively. + */ + set: function (value) { + this._imageProcessingConfiguration.colorCurves = value; + }, + enumerable: true, + configurable: true + }); + /** + * Returns the name of this material class. + */ + PBRMaterial.prototype.getClassName = function () { + return "PBRMaterial"; + }; + /** + * Makes a duplicate of the current material. + * @param name - name to use for the new material. + */ + PBRMaterial.prototype.clone = function (name) { + var _this = this; + var clone = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this); + clone.id = name; + clone.name = name; + this.clearCoat.copyTo(clone.clearCoat); + this.anisotropy.copyTo(clone.anisotropy); + this.brdf.copyTo(clone.brdf); + this.sheen.copyTo(clone.sheen); + return clone; + }; + /** + * Serializes this PBR Material. + * @returns - An object with the serialized material. + */ + PBRMaterial.prototype.serialize = function () { + var serializationObject = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(this); + serializationObject.customType = "BABYLON.PBRMaterial"; + serializationObject.clearCoat = this.clearCoat.serialize(); + serializationObject.anisotropy = this.anisotropy.serialize(); + serializationObject.brdf = this.brdf.serialize(); + serializationObject.sheen = this.sheen.serialize(); + serializationObject.subSurface = this.subSurface.serialize(); + return serializationObject; + }; + // Statics + /** + * Parses a PBR Material from a serialized object. + * @param source - Serialized object. + * @param scene - BJS scene instance. + * @param rootUrl - url for the scene object + * @returns - PBRMaterial + */ + PBRMaterial.Parse = function (source, scene, rootUrl) { + var material = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl); + if (source.clearCoat) { + material.clearCoat.parse(source.clearCoat); + } + if (source.anisotropy) { + material.anisotropy.parse(source.anisotropy); + } + if (source.brdf) { + material.brdf.parse(source.brdf); + } + if (source.sheen) { + material.sheen.parse(source.sheen); + } + if (source.subSurface) { + material.subSurface.parse(source.subSurface); + } + return material; + }; + /** + * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use. + */ + PBRMaterial.PBRMATERIAL_OPAQUE = _pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_4__["PBRBaseMaterial"].PBRMATERIAL_OPAQUE; + /** + * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value. + */ + PBRMaterial.PBRMATERIAL_ALPHATEST = _pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_4__["PBRBaseMaterial"].PBRMATERIAL_ALPHATEST; + /** + * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer. + */ + PBRMaterial.PBRMATERIAL_ALPHABLEND = _pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_4__["PBRBaseMaterial"].PBRMATERIAL_ALPHABLEND; + /** + * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer. + * They are also discarded below the alpha cutoff threshold to improve performances. + */ + PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = _pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_4__["PBRBaseMaterial"].PBRMATERIAL_ALPHATESTANDBLEND; + /** + * Defines the default value of how much AO map is occluding the analytical lights + * (point spot...). + */ + PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = _pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_4__["PBRBaseMaterial"].DEFAULT_AO_ON_ANALYTICAL_LIGHTS; + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMaterial.prototype, "directIntensity", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMaterial.prototype, "emissiveIntensity", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMaterial.prototype, "environmentIntensity", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMaterial.prototype, "specularIntensity", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMaterial.prototype, "disableBumpMap", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMaterial.prototype, "albedoTexture", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMaterial.prototype, "ambientTexture", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMaterial.prototype, "ambientTextureStrength", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesAndMiscDirty") + ], PBRMaterial.prototype, "opacityTexture", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMaterial.prototype, "reflectionTexture", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMaterial.prototype, "emissiveTexture", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMaterial.prototype, "reflectivityTexture", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMaterial.prototype, "metallicTexture", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMaterial.prototype, "metallic", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMaterial.prototype, "roughness", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMaterial.prototype, "microSurfaceTexture", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMaterial.prototype, "bumpTexture", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty", null) + ], PBRMaterial.prototype, "lightmapTexture", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])("ambient"), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMaterial.prototype, "ambientColor", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])("albedo"), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMaterial.prototype, "albedoColor", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])("reflectivity"), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMaterial.prototype, "reflectivityColor", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])("reflection"), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMaterial.prototype, "reflectionColor", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])("emissive"), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMaterial.prototype, "emissiveColor", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMaterial.prototype, "microSurface", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesAndMiscDirty") + ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesAndMiscDirty") + ], PBRMaterial.prototype, "forceAlphaTest", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesAndMiscDirty") + ], PBRMaterial.prototype, "alphaCutOff", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], PBRMaterial.prototype, "usePhysicalLightFalloff", null); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], PBRMaterial.prototype, "useGLTFLightFalloff", null); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMaterial.prototype, "useParallax", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMaterial.prototype, "useParallaxOcclusion", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMaterial.prototype, "parallaxScaleBias", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsLightsDirty") + ], PBRMaterial.prototype, "disableLighting", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsLightsDirty") + ], PBRMaterial.prototype, "maxSimultaneousLights", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMaterial.prototype, "invertNormalMapX", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMaterial.prototype, "invertNormalMapY", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMaterial.prototype, "twoSidedLighting", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMaterial.prototype, "useAlphaFresnel", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMaterial.prototype, "environmentBRDFTexture", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMaterial.prototype, "forceNormalForward", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMaterial.prototype, "useHorizonOcclusion", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMaterial.prototype, "useRadianceOcclusion", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsMiscDirty") + ], PBRMaterial.prototype, "unlit", void 0); + return PBRMaterial; +}(_pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_4__["PBRBaseMaterial"])); + +_Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__["_TypeStore"].RegisteredTypes["BABYLON.PBRMaterial"] = PBRMaterial; + + +/***/ }), + +/***/ "./Materials/PBR/pbrMetallicRoughnessMaterial.ts": +/*!*******************************************************!*\ + !*** ./Materials/PBR/pbrMetallicRoughnessMaterial.ts ***! + \*******************************************************/ +/*! exports provided: PBRMetallicRoughnessMaterial */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PBRMetallicRoughnessMaterial", function() { return PBRMetallicRoughnessMaterial; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _pbrBaseSimpleMaterial__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./pbrBaseSimpleMaterial */ "./Materials/PBR/pbrBaseSimpleMaterial.ts"); +/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Misc/typeStore */ "./Misc/typeStore.ts"); + + + + +/** + * The PBR material of BJS following the metal roughness convention. + * + * This fits to the PBR convention in the GLTF definition: + * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0 + */ +var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PBRMetallicRoughnessMaterial, _super); + /** + * Instantiates a new PBRMetalRoughnessMaterial instance. + * + * @param name The material name + * @param scene The scene the material will be use in. + */ + function PBRMetallicRoughnessMaterial(name, scene) { + var _this = _super.call(this, name, scene) || this; + _this._useRoughnessFromMetallicTextureAlpha = false; + _this._useRoughnessFromMetallicTextureGreen = true; + _this._useMetallnessFromMetallicTextureBlue = true; + _this.metallic = 1.0; + _this.roughness = 1.0; + return _this; + } + /** + * Return the currrent class name of the material. + */ + PBRMetallicRoughnessMaterial.prototype.getClassName = function () { + return "PBRMetallicRoughnessMaterial"; + }; + /** + * Makes a duplicate of the current material. + * @param name - name to use for the new material. + */ + PBRMetallicRoughnessMaterial.prototype.clone = function (name) { + var _this = this; + var clone = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this); + clone.id = name; + clone.name = name; + this.clearCoat.copyTo(clone.clearCoat); + this.anisotropy.copyTo(clone.anisotropy); + this.brdf.copyTo(clone.brdf); + this.sheen.copyTo(clone.sheen); + return clone; + }; + /** + * Serialize the material to a parsable JSON object. + */ + PBRMetallicRoughnessMaterial.prototype.serialize = function () { + var serializationObject = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(this); + serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial"; + serializationObject.clearCoat = this.clearCoat.serialize(); + serializationObject.anisotropy = this.anisotropy.serialize(); + serializationObject.brdf = this.brdf.serialize(); + serializationObject.sheen = this.sheen.serialize(); + serializationObject.subSurface = this.subSurface.serialize(); + return serializationObject; + }; + /** + * Parses a JSON object correponding to the serialize function. + */ + PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) { + var material = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl); + if (source.clearCoat) { + material.clearCoat.parse(source.clearCoat); + } + if (source.anisotropy) { + material.anisotropy.parse(source.anisotropy); + } + if (source.brdf) { + material.brdf.parse(source.brdf); + } + if (source.sheen) { + material.sheen.parse(source.sheen); + } + if (source.subSurface) { + material.subSurface.parse(source.subSurface); + } + return material; + }; + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty", "_albedoColor") + ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty", "_albedoTexture") + ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty", "_metallicTexture") + ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0); + return PBRMetallicRoughnessMaterial; +}(_pbrBaseSimpleMaterial__WEBPACK_IMPORTED_MODULE_2__["PBRBaseSimpleMaterial"])); + +_Misc_typeStore__WEBPACK_IMPORTED_MODULE_3__["_TypeStore"].RegisteredTypes["BABYLON.PBRMetallicRoughnessMaterial"] = PBRMetallicRoughnessMaterial; + + +/***/ }), + +/***/ "./Materials/PBR/pbrSheenConfiguration.ts": +/*!************************************************!*\ + !*** ./Materials/PBR/pbrSheenConfiguration.ts ***! + \************************************************/ +/*! exports provided: PBRSheenConfiguration */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PBRSheenConfiguration", function() { return PBRSheenConfiguration; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Materials_materialFlags__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Materials/materialFlags */ "./Materials/materialFlags.ts"); +/* harmony import */ var _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Materials/materialHelper */ "./Materials/materialHelper.ts"); + + + + + +/** + * Define the code related to the Sheen parameters of the pbr material. + */ +var PBRSheenConfiguration = /** @class */ (function () { + /** + * Instantiate a new istance of clear coat configuration. + * @param markAllSubMeshesAsTexturesDirty Callback to flag the material to dirty + */ + function PBRSheenConfiguration(markAllSubMeshesAsTexturesDirty) { + this._isEnabled = false; + /** + * Defines if the material uses sheen. + */ + this.isEnabled = false; + this._linkSheenWithAlbedo = false; + /** + * Defines if the sheen is linked to the sheen color. + */ + this.linkSheenWithAlbedo = false; + /** + * Defines the sheen intensity. + */ + this.intensity = 1; + /** + * Defines the sheen color. + */ + this.color = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color3"].White(); + this._texture = null; + /** + * Stores the sheen tint values in a texture. + * rgb is tint + * a is a intensity + */ + this.texture = null; + this._internalMarkAllSubMeshesAsTexturesDirty = markAllSubMeshesAsTexturesDirty; + } + /** @hidden */ + PBRSheenConfiguration.prototype._markAllSubMeshesAsTexturesDirty = function () { + this._internalMarkAllSubMeshesAsTexturesDirty(); + }; + /** + * Specifies that the submesh is ready to be used. + * @param defines the list of "defines" to update. + * @param scene defines the scene the material belongs to. + * @returns - boolean indicating that the submesh is ready or not. + */ + PBRSheenConfiguration.prototype.isReadyForSubMesh = function (defines, scene) { + if (defines._areTexturesDirty) { + if (scene.texturesEnabled) { + if (this._texture && _Materials_materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].SheenTextureEnabled) { + if (!this._texture.isReadyOrNotBlocking()) { + return false; + } + } + } + } + return true; + }; + /** + * Checks to see if a texture is used in the material. + * @param defines the list of "defines" to update. + * @param scene defines the scene the material belongs to. + */ + PBRSheenConfiguration.prototype.prepareDefines = function (defines, scene) { + if (this._isEnabled) { + defines.SHEEN = this._isEnabled; + defines.SHEEN_LINKWITHALBEDO = this._linkSheenWithAlbedo; + if (defines._areTexturesDirty) { + if (scene.texturesEnabled) { + if (this._texture && _Materials_materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].SheenTextureEnabled) { + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_4__["MaterialHelper"].PrepareDefinesForMergedUV(this._texture, defines, "SHEEN_TEXTURE"); + } + else { + defines.SHEEN_TEXTURE = false; + } + } + } + } + else { + defines.SHEEN = false; + defines.SHEEN_TEXTURE = false; + defines.SHEEN_LINKWITHALBEDO = false; + } + }; + /** + * Binds the material data. + * @param uniformBuffer defines the Uniform buffer to fill in. + * @param scene defines the scene the material belongs to. + * @param isFrozen defines wether the material is frozen or not. + */ + PBRSheenConfiguration.prototype.bindForSubMesh = function (uniformBuffer, scene, isFrozen) { + if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) { + if (this._texture && _Materials_materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].SheenTextureEnabled) { + uniformBuffer.updateFloat2("vSheenInfos", this._texture.coordinatesIndex, this._texture.level); + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_4__["MaterialHelper"].BindTextureMatrix(this._texture, uniformBuffer, "sheen"); + } + // Sheen + uniformBuffer.updateFloat4("vSheenColor", this.color.r, this.color.g, this.color.b, this.intensity); + } + // Textures + if (scene.texturesEnabled) { + if (this._texture && _Materials_materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].SheenTextureEnabled) { + uniformBuffer.setTexture("sheenSampler", this._texture); + } + } + }; + /** + * Checks to see if a texture is used in the material. + * @param texture - Base texture to use. + * @returns - Boolean specifying if a texture is used in the material. + */ + PBRSheenConfiguration.prototype.hasTexture = function (texture) { + if (this._texture === texture) { + return true; + } + return false; + }; + /** + * Returns an array of the actively used textures. + * @param activeTextures Array of BaseTextures + */ + PBRSheenConfiguration.prototype.getActiveTextures = function (activeTextures) { + if (this._texture) { + activeTextures.push(this._texture); + } + }; + /** + * Returns the animatable textures. + * @param animatables Array of animatable textures. + */ + PBRSheenConfiguration.prototype.getAnimatables = function (animatables) { + if (this._texture && this._texture.animations && this._texture.animations.length > 0) { + animatables.push(this._texture); + } + }; + /** + * Disposes the resources of the material. + * @param forceDisposeTextures - Forces the disposal of all textures. + */ + PBRSheenConfiguration.prototype.dispose = function (forceDisposeTextures) { + if (forceDisposeTextures) { + if (this._texture) { + this._texture.dispose(); + } + } + }; + /** + * Get the current class name of the texture useful for serialization or dynamic coding. + * @returns "PBRSheenConfiguration" + */ + PBRSheenConfiguration.prototype.getClassName = function () { + return "PBRSheenConfiguration"; + }; + /** + * Add fallbacks to the effect fallbacks list. + * @param defines defines the Base texture to use. + * @param fallbacks defines the current fallback list. + * @param currentRank defines the current fallback rank. + * @returns the new fallback rank. + */ + PBRSheenConfiguration.AddFallbacks = function (defines, fallbacks, currentRank) { + if (defines.SHEEN) { + fallbacks.addFallback(currentRank++, "SHEEN"); + } + return currentRank; + }; + /** + * Add the required uniforms to the current list. + * @param uniforms defines the current uniform list. + */ + PBRSheenConfiguration.AddUniforms = function (uniforms) { + uniforms.push("vSheenColor", "vSheenInfos", "sheenMatrix"); + }; + /** + * Add the required uniforms to the current buffer. + * @param uniformBuffer defines the current uniform buffer. + */ + PBRSheenConfiguration.PrepareUniformBuffer = function (uniformBuffer) { + uniformBuffer.addUniform("vSheenColor", 4); + uniformBuffer.addUniform("vSheenInfos", 2); + uniformBuffer.addUniform("sheenMatrix", 16); + }; + /** + * Add the required samplers to the current list. + * @param samplers defines the current sampler list. + */ + PBRSheenConfiguration.AddSamplers = function (samplers) { + samplers.push("sheenSampler"); + }; + /** + * Makes a duplicate of the current configuration into another one. + * @param sheenConfiguration define the config where to copy the info + */ + PBRSheenConfiguration.prototype.copyTo = function (sheenConfiguration) { + _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Clone(function () { return sheenConfiguration; }, this); + }; + /** + * Serializes this BRDF configuration. + * @returns - An object with the serialized config. + */ + PBRSheenConfiguration.prototype.serialize = function () { + return _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(this); + }; + /** + * Parses a Sheen Configuration from a serialized object. + * @param source - Serialized object. + */ + PBRSheenConfiguration.prototype.parse = function (source) { + var _this = this; + _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(function () { return _this; }, source, null); + }; + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], PBRSheenConfiguration.prototype, "_isEnabled", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRSheenConfiguration.prototype, "isEnabled", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], PBRSheenConfiguration.prototype, "_linkSheenWithAlbedo", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRSheenConfiguration.prototype, "linkSheenWithAlbedo", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], PBRSheenConfiguration.prototype, "intensity", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])() + ], PBRSheenConfiguration.prototype, "color", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])() + ], PBRSheenConfiguration.prototype, "_texture", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRSheenConfiguration.prototype, "texture", void 0); + return PBRSheenConfiguration; +}()); + + + +/***/ }), + +/***/ "./Materials/PBR/pbrSpecularGlossinessMaterial.ts": +/*!********************************************************!*\ + !*** ./Materials/PBR/pbrSpecularGlossinessMaterial.ts ***! + \********************************************************/ +/*! exports provided: PBRSpecularGlossinessMaterial */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PBRSpecularGlossinessMaterial", function() { return PBRSpecularGlossinessMaterial; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _pbrBaseSimpleMaterial__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./pbrBaseSimpleMaterial */ "./Materials/PBR/pbrBaseSimpleMaterial.ts"); +/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Misc/typeStore */ "./Misc/typeStore.ts"); + + + + +/** + * The PBR material of BJS following the specular glossiness convention. + * + * This fits to the PBR convention in the GLTF definition: + * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness + */ +var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PBRSpecularGlossinessMaterial, _super); + /** + * Instantiates a new PBRSpecularGlossinessMaterial instance. + * + * @param name The material name + * @param scene The scene the material will be use in. + */ + function PBRSpecularGlossinessMaterial(name, scene) { + var _this = _super.call(this, name, scene) || this; + _this._useMicroSurfaceFromReflectivityMapAlpha = true; + return _this; + } + /** + * Return the currrent class name of the material. + */ + PBRSpecularGlossinessMaterial.prototype.getClassName = function () { + return "PBRSpecularGlossinessMaterial"; + }; + /** + * Makes a duplicate of the current material. + * @param name - name to use for the new material. + */ + PBRSpecularGlossinessMaterial.prototype.clone = function (name) { + var _this = this; + var clone = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this); + clone.id = name; + clone.name = name; + this.clearCoat.copyTo(clone.clearCoat); + this.anisotropy.copyTo(clone.anisotropy); + this.brdf.copyTo(clone.brdf); + this.sheen.copyTo(clone.sheen); + return clone; + }; + /** + * Serialize the material to a parsable JSON object. + */ + PBRSpecularGlossinessMaterial.prototype.serialize = function () { + var serializationObject = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(this); + serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial"; + serializationObject.clearCoat = this.clearCoat.serialize(); + serializationObject.anisotropy = this.anisotropy.serialize(); + serializationObject.brdf = this.brdf.serialize(); + serializationObject.sheen = this.sheen.serialize(); + serializationObject.subSurface = this.subSurface.serialize(); + return serializationObject; + }; + /** + * Parses a JSON object correponding to the serialize function. + */ + PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) { + var material = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl); + if (source.clearCoat) { + material.clearCoat.parse(source.clearCoat); + } + if (source.anisotropy) { + material.anisotropy.parse(source.anisotropy); + } + if (source.brdf) { + material.brdf.parse(source.brdf); + } + if (source.sheen) { + material.sheen.parse(source.sheen); + } + if (source.subSurface) { + material.subSurface.parse(source.subSurface); + } + return material; + }; + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])("diffuse"), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty", "_albedoColor") + ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty", "_albedoTexture") + ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])("specular"), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor") + ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty", "_microSurface") + ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture") + ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0); + return PBRSpecularGlossinessMaterial; +}(_pbrBaseSimpleMaterial__WEBPACK_IMPORTED_MODULE_2__["PBRBaseSimpleMaterial"])); + +_Misc_typeStore__WEBPACK_IMPORTED_MODULE_3__["_TypeStore"].RegisteredTypes["BABYLON.PBRSpecularGlossinessMaterial"] = PBRSpecularGlossinessMaterial; + + +/***/ }), + +/***/ "./Materials/PBR/pbrSubSurfaceConfiguration.ts": +/*!*****************************************************!*\ + !*** ./Materials/PBR/pbrSubSurfaceConfiguration.ts ***! + \*****************************************************/ +/*! exports provided: PBRSubSurfaceConfiguration */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PBRSubSurfaceConfiguration", function() { return PBRSubSurfaceConfiguration; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _materialFlags__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../materialFlags */ "./Materials/materialFlags.ts"); +/* harmony import */ var _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Materials/materialHelper */ "./Materials/materialHelper.ts"); + + + + + +/** + * Define the code related to the sub surface parameters of the pbr material. + */ +var PBRSubSurfaceConfiguration = /** @class */ (function () { + /** + * Instantiate a new istance of sub surface configuration. + * @param markAllSubMeshesAsTexturesDirty Callback to flag the material to dirty + */ + function PBRSubSurfaceConfiguration(markAllSubMeshesAsTexturesDirty) { + this._isRefractionEnabled = false; + /** + * Defines if the refraction is enabled in the material. + */ + this.isRefractionEnabled = false; + this._isTranslucencyEnabled = false; + /** + * Defines if the translucency is enabled in the material. + */ + this.isTranslucencyEnabled = false; + this._isScatteringEnabled = false; + // /** + // * Defines if the sub surface scattering is enabled in the material. + // */ + // @expandToProperty("_markAllSubMeshesAsTexturesDirty") + // public isScatteringEnabled = false; + /** + * Defines the refraction intensity of the material. + * The refraction when enabled replaces the Diffuse part of the material. + * The intensity helps transitionning between diffuse and refraction. + */ + this.refractionIntensity = 1; + /** + * Defines the translucency intensity of the material. + * When translucency has been enabled, this defines how much of the "translucency" + * is addded to the diffuse part of the material. + */ + this.translucencyIntensity = 1; + /** + * Defines the scattering intensity of the material. + * When scattering has been enabled, this defines how much of the "scattered light" + * is addded to the diffuse part of the material. + */ + this.scatteringIntensity = 1; + this._thicknessTexture = null; + /** + * Stores the average thickness of a mesh in a texture (The texture is holding the values linearly). + * The red channel of the texture should contain the thickness remapped between 0 and 1. + * 0 would mean minimumThickness + * 1 would mean maximumThickness + * The other channels might be use as a mask to vary the different effects intensity. + */ + this.thicknessTexture = null; + this._refractionTexture = null; + /** + * Defines the texture to use for refraction. + */ + this.refractionTexture = null; + this._indexOfRefraction = 1; + /** + * Defines the indice of refraction used in the material. + * https://en.wikipedia.org/wiki/List_of_refractive_indices + */ + this.indexOfRefraction = 1; + this._invertRefractionY = false; + /** + * Controls if refraction needs to be inverted on Y. This could be useful for procedural texture. + */ + this.invertRefractionY = false; + this._linkRefractionWithTransparency = false; + /** + * This parameters will make the material used its opacity to control how much it is refracting aginst not. + * Materials half opaque for instance using refraction could benefit from this control. + */ + this.linkRefractionWithTransparency = false; + /** + * Defines the minimum thickness stored in the thickness map. + * If no thickness map is defined, this value will be used to simulate thickness. + */ + this.minimumThickness = 0; + /** + * Defines the maximum thickness stored in the thickness map. + */ + this.maximumThickness = 1; + /** + * Defines the volume tint of the material. + * This is used for both translucency and scattering. + */ + this.tintColor = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color3"].White(); + /** + * Defines the distance at which the tint color should be found in the media. + * This is used for refraction only. + */ + this.tintColorAtDistance = 1; + /** + * Defines how far each channel transmit through the media. + * It is defined as a color to simplify it selection. + */ + this.diffusionDistance = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color3"].White(); + this._useMaskFromThicknessTexture = false; + /** + * Stores the intensity of the different subsurface effects in the thickness texture. + * * the green channel is the translucency intensity. + * * the blue channel is the scattering intensity. + * * the alpha channel is the refraction intensity. + */ + this.useMaskFromThicknessTexture = false; + this._internalMarkAllSubMeshesAsTexturesDirty = markAllSubMeshesAsTexturesDirty; + } + /** @hidden */ + PBRSubSurfaceConfiguration.prototype._markAllSubMeshesAsTexturesDirty = function () { + this._internalMarkAllSubMeshesAsTexturesDirty(); + }; + /** + * Gets wehter the submesh is ready to be used or not. + * @param defines the list of "defines" to update. + * @param scene defines the scene the material belongs to. + * @returns - boolean indicating that the submesh is ready or not. + */ + PBRSubSurfaceConfiguration.prototype.isReadyForSubMesh = function (defines, scene) { + if (defines._areTexturesDirty) { + if (scene.texturesEnabled) { + if (this._thicknessTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].ThicknessTextureEnabled) { + if (!this._thicknessTexture.isReadyOrNotBlocking()) { + return false; + } + } + var refractionTexture = this._getRefractionTexture(scene); + if (refractionTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].RefractionTextureEnabled) { + if (!refractionTexture.isReadyOrNotBlocking()) { + return false; + } + } + } + } + return true; + }; + /** + * Checks to see if a texture is used in the material. + * @param defines the list of "defines" to update. + * @param scene defines the scene to the material belongs to. + */ + PBRSubSurfaceConfiguration.prototype.prepareDefines = function (defines, scene) { + if (defines._areTexturesDirty) { + defines.SUBSURFACE = false; + defines.SS_TRANSLUCENCY = this._isTranslucencyEnabled; + defines.SS_SCATERRING = this._isScatteringEnabled; + defines.SS_THICKNESSANDMASK_TEXTURE = false; + defines.SS_MASK_FROM_THICKNESS_TEXTURE = false; + defines.SS_REFRACTION = false; + defines.SS_REFRACTIONMAP_3D = false; + defines.SS_GAMMAREFRACTION = false; + defines.SS_RGBDREFRACTION = false; + defines.SS_LINEARSPECULARREFRACTION = false; + defines.SS_REFRACTIONMAP_OPPOSITEZ = false; + defines.SS_LODINREFRACTIONALPHA = false; + defines.SS_LINKREFRACTIONTOTRANSPARENCY = false; + if (this._isRefractionEnabled || this._isTranslucencyEnabled || this._isScatteringEnabled) { + defines.SUBSURFACE = true; + if (defines._areTexturesDirty) { + if (scene.texturesEnabled) { + if (this._thicknessTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].ThicknessTextureEnabled) { + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_4__["MaterialHelper"].PrepareDefinesForMergedUV(this._thicknessTexture, defines, "SS_THICKNESSANDMASK_TEXTURE"); + } + } + } + defines.SS_MASK_FROM_THICKNESS_TEXTURE = this._useMaskFromThicknessTexture; + } + if (this._isRefractionEnabled) { + if (scene.texturesEnabled) { + var refractionTexture = this._getRefractionTexture(scene); + if (refractionTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].RefractionTextureEnabled) { + defines.SS_REFRACTION = true; + defines.SS_REFRACTIONMAP_3D = refractionTexture.isCube; + defines.SS_GAMMAREFRACTION = refractionTexture.gammaSpace; + defines.SS_RGBDREFRACTION = refractionTexture.isRGBD; + defines.SS_LINEARSPECULARREFRACTION = refractionTexture.linearSpecularLOD; + defines.SS_REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ; + defines.SS_LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha; + defines.SS_LINKREFRACTIONTOTRANSPARENCY = this._linkRefractionWithTransparency; + } + } + } + } + }; + /** + * Binds the material data. + * @param uniformBuffer defines the Uniform buffer to fill in. + * @param scene defines the scene the material belongs to. + * @param engine defines the engine the material belongs to. + * @param isFrozen defines wether the material is frozen or not. + * @param lodBasedMicrosurface defines wether the material relies on lod based microsurface or not. + */ + PBRSubSurfaceConfiguration.prototype.bindForSubMesh = function (uniformBuffer, scene, engine, isFrozen, lodBasedMicrosurface) { + var refractionTexture = this._getRefractionTexture(scene); + if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) { + if (this._thicknessTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].ThicknessTextureEnabled) { + uniformBuffer.updateFloat2("vThicknessInfos", this._thicknessTexture.coordinatesIndex, this._thicknessTexture.level); + _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_4__["MaterialHelper"].BindTextureMatrix(this._thicknessTexture, uniformBuffer, "thickness"); + } + uniformBuffer.updateFloat2("vThicknessParam", this.minimumThickness, this.maximumThickness - this.minimumThickness); + if (refractionTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].RefractionTextureEnabled) { + uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix()); + var depth = 1.0; + if (!refractionTexture.isCube) { + if (refractionTexture.depth) { + depth = refractionTexture.depth; + } + } + uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, 1 / this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1); + uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset); + } + uniformBuffer.updateColor3("vDiffusionDistance", this.diffusionDistance); + uniformBuffer.updateFloat4("vTintColor", this.tintColor.r, this.tintColor.g, this.tintColor.b, this.tintColorAtDistance); + uniformBuffer.updateFloat3("vSubSurfaceIntensity", this.refractionIntensity, this.translucencyIntensity, this.scatteringIntensity); + } + // Textures + if (scene.texturesEnabled) { + if (this._thicknessTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].ThicknessTextureEnabled) { + uniformBuffer.setTexture("thicknessSampler", this._thicknessTexture); + } + if (refractionTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].RefractionTextureEnabled) { + if (lodBasedMicrosurface) { + uniformBuffer.setTexture("refractionSampler", refractionTexture); + } + else { + uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture); + uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture); + uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture); + } + } + } + }; + /** + * Unbinds the material from the mesh. + * @param activeEffect defines the effect that should be unbound from. + * @returns true if unbound, otherwise false + */ + PBRSubSurfaceConfiguration.prototype.unbind = function (activeEffect) { + if (this._refractionTexture && this._refractionTexture.isRenderTarget) { + activeEffect.setTexture("refractionSampler", null); + return true; + } + return false; + }; + /** + * Returns the texture used for refraction or null if none is used. + * @param scene defines the scene the material belongs to. + * @returns - Refraction texture if present. If no refraction texture and refraction + * is linked with transparency, returns environment texture. Otherwise, returns null. + */ + PBRSubSurfaceConfiguration.prototype._getRefractionTexture = function (scene) { + if (this._refractionTexture) { + return this._refractionTexture; + } + if (this._isRefractionEnabled) { + return scene.environmentTexture; + } + return null; + }; + Object.defineProperty(PBRSubSurfaceConfiguration.prototype, "disableAlphaBlending", { + /** + * Returns true if alpha blending should be disabled. + */ + get: function () { + return this.isRefractionEnabled && this._linkRefractionWithTransparency; + }, + enumerable: true, + configurable: true + }); + /** + * Fills the list of render target textures. + * @param renderTargets the list of render targets to update + */ + PBRSubSurfaceConfiguration.prototype.fillRenderTargetTextures = function (renderTargets) { + if (_materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) { + renderTargets.push(this._refractionTexture); + } + }; + /** + * Checks to see if a texture is used in the material. + * @param texture - Base texture to use. + * @returns - Boolean specifying if a texture is used in the material. + */ + PBRSubSurfaceConfiguration.prototype.hasTexture = function (texture) { + if (this._thicknessTexture === texture) { + return true; + } + if (this._refractionTexture === texture) { + return true; + } + return false; + }; + /** + * Gets a boolean indicating that current material needs to register RTT + * @returns true if this uses a render target otherwise false. + */ + PBRSubSurfaceConfiguration.prototype.hasRenderTargetTextures = function () { + if (_materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) { + return true; + } + return false; + }; + /** + * Returns an array of the actively used textures. + * @param activeTextures Array of BaseTextures + */ + PBRSubSurfaceConfiguration.prototype.getActiveTextures = function (activeTextures) { + if (this._thicknessTexture) { + activeTextures.push(this._thicknessTexture); + } + if (this._refractionTexture) { + activeTextures.push(this._refractionTexture); + } + }; + /** + * Returns the animatable textures. + * @param animatables Array of animatable textures. + */ + PBRSubSurfaceConfiguration.prototype.getAnimatables = function (animatables) { + if (this._thicknessTexture && this._thicknessTexture.animations && this._thicknessTexture.animations.length > 0) { + animatables.push(this._thicknessTexture); + } + if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) { + animatables.push(this._refractionTexture); + } + }; + /** + * Disposes the resources of the material. + * @param forceDisposeTextures - Forces the disposal of all textures. + */ + PBRSubSurfaceConfiguration.prototype.dispose = function (forceDisposeTextures) { + if (forceDisposeTextures) { + if (this._thicknessTexture) { + this._thicknessTexture.dispose(); + } + if (this._refractionTexture) { + this._refractionTexture.dispose(); + } + } + }; + /** + * Get the current class name of the texture useful for serialization or dynamic coding. + * @returns "PBRSubSurfaceConfiguration" + */ + PBRSubSurfaceConfiguration.prototype.getClassName = function () { + return "PBRSubSurfaceConfiguration"; + }; + /** + * Add fallbacks to the effect fallbacks list. + * @param defines defines the Base texture to use. + * @param fallbacks defines the current fallback list. + * @param currentRank defines the current fallback rank. + * @returns the new fallback rank. + */ + PBRSubSurfaceConfiguration.AddFallbacks = function (defines, fallbacks, currentRank) { + if (defines.SS_SCATERRING) { + fallbacks.addFallback(currentRank++, "SS_SCATERRING"); + } + if (defines.SS_TRANSLUCENCY) { + fallbacks.addFallback(currentRank++, "SS_TRANSLUCENCY"); + } + return currentRank; + }; + /** + * Add the required uniforms to the current list. + * @param uniforms defines the current uniform list. + */ + PBRSubSurfaceConfiguration.AddUniforms = function (uniforms) { + uniforms.push("vDiffusionDistance", "vTintColor", "vSubSurfaceIntensity", "vRefractionMicrosurfaceInfos", "vRefractionInfos", "vThicknessInfos", "vThicknessParam", "refractionMatrix", "thicknessMatrix"); + }; + /** + * Add the required samplers to the current list. + * @param samplers defines the current sampler list. + */ + PBRSubSurfaceConfiguration.AddSamplers = function (samplers) { + samplers.push("thicknessSampler", "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh"); + }; + /** + * Add the required uniforms to the current buffer. + * @param uniformBuffer defines the current uniform buffer. + */ + PBRSubSurfaceConfiguration.PrepareUniformBuffer = function (uniformBuffer) { + uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3); + uniformBuffer.addUniform("vRefractionInfos", 4); + uniformBuffer.addUniform("refractionMatrix", 16); + uniformBuffer.addUniform("vThicknessInfos", 2); + uniformBuffer.addUniform("thicknessMatrix", 16); + uniformBuffer.addUniform("vThicknessParam", 2); + uniformBuffer.addUniform("vDiffusionDistance", 3); + uniformBuffer.addUniform("vTintColor", 4); + uniformBuffer.addUniform("vSubSurfaceIntensity", 3); + }; + /** + * Makes a duplicate of the current configuration into another one. + * @param configuration define the config where to copy the info + */ + PBRSubSurfaceConfiguration.prototype.copyTo = function (configuration) { + _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Clone(function () { return configuration; }, this); + }; + /** + * Serializes this Sub Surface configuration. + * @returns - An object with the serialized config. + */ + PBRSubSurfaceConfiguration.prototype.serialize = function () { + return _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(this); + }; + /** + * Parses a Sub Surface Configuration from a serialized object. + * @param source - Serialized object. + */ + PBRSubSurfaceConfiguration.prototype.parse = function (source) { + var _this = this; + _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(function () { return _this; }, source, null); + }; + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], PBRSubSurfaceConfiguration.prototype, "_isRefractionEnabled", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRSubSurfaceConfiguration.prototype, "isRefractionEnabled", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], PBRSubSurfaceConfiguration.prototype, "_isTranslucencyEnabled", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRSubSurfaceConfiguration.prototype, "isTranslucencyEnabled", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], PBRSubSurfaceConfiguration.prototype, "_isScatteringEnabled", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], PBRSubSurfaceConfiguration.prototype, "refractionIntensity", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], PBRSubSurfaceConfiguration.prototype, "translucencyIntensity", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], PBRSubSurfaceConfiguration.prototype, "scatteringIntensity", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])() + ], PBRSubSurfaceConfiguration.prototype, "_thicknessTexture", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRSubSurfaceConfiguration.prototype, "thicknessTexture", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRSubSurfaceConfiguration.prototype, "refractionTexture", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRSubSurfaceConfiguration.prototype, "indexOfRefraction", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRSubSurfaceConfiguration.prototype, "invertRefractionY", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRSubSurfaceConfiguration.prototype, "linkRefractionWithTransparency", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], PBRSubSurfaceConfiguration.prototype, "minimumThickness", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], PBRSubSurfaceConfiguration.prototype, "maximumThickness", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])() + ], PBRSubSurfaceConfiguration.prototype, "tintColor", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], PBRSubSurfaceConfiguration.prototype, "tintColorAtDistance", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])() + ], PBRSubSurfaceConfiguration.prototype, "diffusionDistance", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], PBRSubSurfaceConfiguration.prototype, "_useMaskFromThicknessTexture", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") + ], PBRSubSurfaceConfiguration.prototype, "useMaskFromThicknessTexture", void 0); + return PBRSubSurfaceConfiguration; +}()); + + + +/***/ }), + +/***/ "./Materials/Textures/Loaders/ddsTextureLoader.ts": +/*!********************************************************!*\ + !*** ./Materials/Textures/Loaders/ddsTextureLoader.ts ***! + \********************************************************/ +/*! exports provided: _DDSTextureLoader */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_DDSTextureLoader", function() { return _DDSTextureLoader; }); +/* harmony import */ var _Maths_sphericalPolynomial__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../../Maths/sphericalPolynomial */ "./Maths/sphericalPolynomial.ts"); +/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../../Engines/engine */ "./Engines/engine.ts"); +/* harmony import */ var _Misc_dds__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../../Misc/dds */ "./Misc/dds.ts"); + + + +/** + * Implementation of the DDS Texture Loader. + * @hidden + */ +var _DDSTextureLoader = /** @class */ (function () { + function _DDSTextureLoader() { + /** + * Defines wether the loader supports cascade loading the different faces. + */ + this.supportCascades = true; + } + /** + * This returns if the loader support the current file information. + * @param extension defines the file extension of the file being loaded + * @param textureFormatInUse defines the current compressed format in use iun the engine + * @param fallback defines the fallback internal texture if any + * @param isBase64 defines whether the texture is encoded as a base64 + * @param isBuffer defines whether the texture data are stored as a buffer + * @returns true if the loader can load the specified file + */ + _DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) { + return extension.indexOf(".dds") === 0; + }; + /** + * Transform the url before loading if required. + * @param rootUrl the url of the texture + * @param textureFormatInUse defines the current compressed format in use iun the engine + * @returns the transformed texture + */ + _DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) { + return rootUrl; + }; + /** + * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work + * @param rootUrl the url of the texture + * @param textureFormatInUse defines the current compressed format in use iun the engine + * @returns the fallback texture + */ + _DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) { + return null; + }; + /** + * Uploads the cube texture data to the WebGl Texture. It has alreday been bound. + * @param data contains the texture data + * @param texture defines the BabylonJS internal texture + * @param createPolynomials will be true if polynomials have been requested + * @param onLoad defines the callback to trigger once the texture is ready + * @param onError defines the callback to trigger in case of error + */ + _DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) { + var engine = texture.getEngine(); + var info; + var loadMipmap = false; + if (Array.isArray(imgs)) { + for (var index = 0; index < imgs.length; index++) { + var data_1 = imgs[index]; + info = _Misc_dds__WEBPACK_IMPORTED_MODULE_2__["DDSTools"].GetDDSInfo(data_1); + texture.width = info.width; + texture.height = info.height; + loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps; + engine._unpackFlipY(info.isCompressed); + _Misc_dds__WEBPACK_IMPORTED_MODULE_2__["DDSTools"].UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index); + if (!info.isFourCC && info.mipmapCount === 1) { + engine.generateMipMapsForCubemap(texture); + } + } + } + else { + var data = imgs; + info = _Misc_dds__WEBPACK_IMPORTED_MODULE_2__["DDSTools"].GetDDSInfo(data); + texture.width = info.width; + texture.height = info.height; + if (createPolynomials) { + info.sphericalPolynomial = new _Maths_sphericalPolynomial__WEBPACK_IMPORTED_MODULE_0__["SphericalPolynomial"](); + } + loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps; + engine._unpackFlipY(info.isCompressed); + _Misc_dds__WEBPACK_IMPORTED_MODULE_2__["DDSTools"].UploadDDSLevels(engine, texture, data, info, loadMipmap, 6); + if (!info.isFourCC && info.mipmapCount === 1) { + engine.generateMipMapsForCubemap(texture); + } + } + engine._setCubeMapTextureParams(loadMipmap); + texture.isReady = true; + if (onLoad) { + onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture }); + } + }; + /** + * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback. + * @param data contains the texture data + * @param texture defines the BabylonJS internal texture + * @param callback defines the method to call once ready to upload + */ + _DDSTextureLoader.prototype.loadData = function (data, texture, callback) { + var info = _Misc_dds__WEBPACK_IMPORTED_MODULE_2__["DDSTools"].GetDDSInfo(data); + var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1); + callback(info.width, info.height, loadMipmap, info.isFourCC, function () { + _Misc_dds__WEBPACK_IMPORTED_MODULE_2__["DDSTools"].UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1); + }); + }; + return _DDSTextureLoader; +}()); + +// Register the loader. +_Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"]._TextureLoaders.push(new _DDSTextureLoader()); + + +/***/ }), + +/***/ "./Materials/Textures/Loaders/envTextureLoader.ts": +/*!********************************************************!*\ + !*** ./Materials/Textures/Loaders/envTextureLoader.ts ***! + \********************************************************/ +/*! exports provided: _ENVTextureLoader */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_ENVTextureLoader", function() { return _ENVTextureLoader; }); +/* harmony import */ var _Misc_environmentTextureTools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../../Misc/environmentTextureTools */ "./Misc/environmentTextureTools.ts"); +/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../../Engines/engine */ "./Engines/engine.ts"); + + +/** + * Implementation of the ENV Texture Loader. + * @hidden + */ +var _ENVTextureLoader = /** @class */ (function () { + function _ENVTextureLoader() { + /** + * Defines wether the loader supports cascade loading the different faces. + */ + this.supportCascades = false; + } + /** + * This returns if the loader support the current file information. + * @param extension defines the file extension of the file being loaded + * @param textureFormatInUse defines the current compressed format in use iun the engine + * @param fallback defines the fallback internal texture if any + * @param isBase64 defines whether the texture is encoded as a base64 + * @param isBuffer defines whether the texture data are stored as a buffer + * @returns true if the loader can load the specified file + */ + _ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) { + return extension.indexOf(".env") === 0; + }; + /** + * Transform the url before loading if required. + * @param rootUrl the url of the texture + * @param textureFormatInUse defines the current compressed format in use iun the engine + * @returns the transformed texture + */ + _ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) { + return rootUrl; + }; + /** + * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work + * @param rootUrl the url of the texture + * @param textureFormatInUse defines the current compressed format in use iun the engine + * @returns the fallback texture + */ + _ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) { + return null; + }; + /** + * Uploads the cube texture data to the WebGl Texture. It has alreday been bound. + * @param data contains the texture data + * @param texture defines the BabylonJS internal texture + * @param createPolynomials will be true if polynomials have been requested + * @param onLoad defines the callback to trigger once the texture is ready + * @param onError defines the callback to trigger in case of error + */ + _ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) { + if (Array.isArray(data)) { + return; + } + data = data; + var info = _Misc_environmentTextureTools__WEBPACK_IMPORTED_MODULE_0__["EnvironmentTextureTools"].GetEnvInfo(data); + if (info) { + texture.width = info.width; + texture.height = info.width; + _Misc_environmentTextureTools__WEBPACK_IMPORTED_MODULE_0__["EnvironmentTextureTools"].UploadEnvSpherical(texture, info); + _Misc_environmentTextureTools__WEBPACK_IMPORTED_MODULE_0__["EnvironmentTextureTools"].UploadEnvLevelsAsync(texture, data, info).then(function () { + texture.isReady = true; + if (onLoad) { + onLoad(); + } + }); + } + else if (onError) { + onError("Can not parse the environment file", null); + } + }; + /** + * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback. + * @param data contains the texture data + * @param texture defines the BabylonJS internal texture + * @param callback defines the method to call once ready to upload + */ + _ENVTextureLoader.prototype.loadData = function (data, texture, callback) { + throw ".env not supported in 2d."; + }; + return _ENVTextureLoader; +}()); + +// Register the loader. +_Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"]._TextureLoaders.push(new _ENVTextureLoader()); + + +/***/ }), + +/***/ "./Materials/Textures/Loaders/index.ts": +/*!*********************************************!*\ + !*** ./Materials/Textures/Loaders/index.ts ***! + \*********************************************/ +/*! exports provided: _DDSTextureLoader, _ENVTextureLoader, _KTXTextureLoader, _TGATextureLoader */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _ddsTextureLoader__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ddsTextureLoader */ "./Materials/Textures/Loaders/ddsTextureLoader.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_DDSTextureLoader", function() { return _ddsTextureLoader__WEBPACK_IMPORTED_MODULE_0__["_DDSTextureLoader"]; }); + +/* harmony import */ var _envTextureLoader__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./envTextureLoader */ "./Materials/Textures/Loaders/envTextureLoader.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_ENVTextureLoader", function() { return _envTextureLoader__WEBPACK_IMPORTED_MODULE_1__["_ENVTextureLoader"]; }); + +/* harmony import */ var _ktxTextureLoader__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./ktxTextureLoader */ "./Materials/Textures/Loaders/ktxTextureLoader.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_KTXTextureLoader", function() { return _ktxTextureLoader__WEBPACK_IMPORTED_MODULE_2__["_KTXTextureLoader"]; }); + +/* harmony import */ var _tgaTextureLoader__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./tgaTextureLoader */ "./Materials/Textures/Loaders/tgaTextureLoader.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_TGATextureLoader", function() { return _tgaTextureLoader__WEBPACK_IMPORTED_MODULE_3__["_TGATextureLoader"]; }); + + + + + + + +/***/ }), + +/***/ "./Materials/Textures/Loaders/ktxTextureLoader.ts": +/*!********************************************************!*\ + !*** ./Materials/Textures/Loaders/ktxTextureLoader.ts ***! + \********************************************************/ +/*! exports provided: _KTXTextureLoader */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_KTXTextureLoader", function() { return _KTXTextureLoader; }); +/* harmony import */ var _Misc_khronosTextureContainer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../../Misc/khronosTextureContainer */ "./Misc/khronosTextureContainer.ts"); +/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../../Engines/engine */ "./Engines/engine.ts"); + + +/** + * Implementation of the KTX Texture Loader. + * @hidden + */ +var _KTXTextureLoader = /** @class */ (function () { + function _KTXTextureLoader() { + /** + * Defines wether the loader supports cascade loading the different faces. + */ + this.supportCascades = false; + } + /** + * This returns if the loader support the current file information. + * @param extension defines the file extension of the file being loaded + * @param textureFormatInUse defines the current compressed format in use iun the engine + * @param fallback defines the fallback internal texture if any + * @param isBase64 defines whether the texture is encoded as a base64 + * @param isBuffer defines whether the texture data are stored as a buffer + * @returns true if the loader can load the specified file + */ + _KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) { + if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) { + return true; + } + return false; + }; + /** + * Transform the url before loading if required. + * @param rootUrl the url of the texture + * @param textureFormatInUse defines the current compressed format in use iun the engine + * @returns the transformed texture + */ + _KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) { + var lastDot = rootUrl.lastIndexOf('.'); + if (lastDot != -1 && rootUrl.substring(lastDot + 1) == "ktx") { + // Already transformed + return rootUrl; + } + return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse; + }; + /** + * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work + * @param rootUrl the url of the texture + * @param textureFormatInUse defines the current compressed format in use iun the engine + * @returns the fallback texture + */ + _KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) { + // remove the format appended to the rootUrl in the original createCubeTexture call. + var exp = new RegExp("" + textureFormatInUse + "$"); + return rootUrl.replace(exp, ""); + }; + /** + * Uploads the cube texture data to the WebGl Texture. It has alreday been bound. + * @param data contains the texture data + * @param texture defines the BabylonJS internal texture + * @param createPolynomials will be true if polynomials have been requested + * @param onLoad defines the callback to trigger once the texture is ready + * @param onError defines the callback to trigger in case of error + */ + _KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) { + if (Array.isArray(data)) { + return; + } + // Need to invert vScale as invertY via UNPACK_FLIP_Y_WEBGL is not supported by compressed texture + texture._invertVScale = !texture.invertY; + var engine = texture.getEngine(); + var ktx = new _Misc_khronosTextureContainer__WEBPACK_IMPORTED_MODULE_0__["KhronosTextureContainer"](data, 6); + var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps; + engine._unpackFlipY(true); + ktx.uploadLevels(texture, texture.generateMipMaps); + texture.width = ktx.pixelWidth; + texture.height = ktx.pixelHeight; + engine._setCubeMapTextureParams(loadMipmap); + texture.isReady = true; + }; + /** + * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback. + * @param data contains the texture data + * @param texture defines the BabylonJS internal texture + * @param callback defines the method to call once ready to upload + */ + _KTXTextureLoader.prototype.loadData = function (data, texture, callback) { + // Need to invert vScale as invertY via UNPACK_FLIP_Y_WEBGL is not supported by compressed texture + texture._invertVScale = !texture.invertY; + var ktx = new _Misc_khronosTextureContainer__WEBPACK_IMPORTED_MODULE_0__["KhronosTextureContainer"](data, 1); + callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () { + ktx.uploadLevels(texture, texture.generateMipMaps); + }, ktx.isInvalid); + }; + return _KTXTextureLoader; +}()); + +// Register the loader. +_Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"]._TextureLoaders.unshift(new _KTXTextureLoader()); + + +/***/ }), + +/***/ "./Materials/Textures/Loaders/tgaTextureLoader.ts": +/*!********************************************************!*\ + !*** ./Materials/Textures/Loaders/tgaTextureLoader.ts ***! + \********************************************************/ +/*! exports provided: _TGATextureLoader */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_TGATextureLoader", function() { return _TGATextureLoader; }); +/* harmony import */ var _Misc_tga__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../../Misc/tga */ "./Misc/tga.ts"); +/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../../Engines/engine */ "./Engines/engine.ts"); + + +/** + * Implementation of the TGA Texture Loader. + * @hidden + */ +var _TGATextureLoader = /** @class */ (function () { + function _TGATextureLoader() { + /** + * Defines wether the loader supports cascade loading the different faces. + */ + this.supportCascades = false; + } + /** + * This returns if the loader support the current file information. + * @param extension defines the file extension of the file being loaded + * @param textureFormatInUse defines the current compressed format in use iun the engine + * @param fallback defines the fallback internal texture if any + * @param isBase64 defines whether the texture is encoded as a base64 + * @param isBuffer defines whether the texture data are stored as a buffer + * @returns true if the loader can load the specified file + */ + _TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) { + return extension.indexOf(".tga") === 0; + }; + /** + * Transform the url before loading if required. + * @param rootUrl the url of the texture + * @param textureFormatInUse defines the current compressed format in use iun the engine + * @returns the transformed texture + */ + _TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) { + return rootUrl; + }; + /** + * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work + * @param rootUrl the url of the texture + * @param textureFormatInUse defines the current compressed format in use iun the engine + * @returns the fallback texture + */ + _TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) { + return null; + }; + /** + * Uploads the cube texture data to the WebGl Texture. It has alreday been bound. + * @param data contains the texture data + * @param texture defines the BabylonJS internal texture + * @param createPolynomials will be true if polynomials have been requested + * @param onLoad defines the callback to trigger once the texture is ready + * @param onError defines the callback to trigger in case of error + */ + _TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) { + throw ".env not supported in Cube."; + }; + /** + * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback. + * @param data contains the texture data + * @param texture defines the BabylonJS internal texture + * @param callback defines the method to call once ready to upload + */ + _TGATextureLoader.prototype.loadData = function (data, texture, callback) { + var uintData = new Uint8Array(data); + var header = _Misc_tga__WEBPACK_IMPORTED_MODULE_0__["TGATools"].GetTGAHeader(uintData); + callback(header.width, header.height, texture.generateMipMaps, false, function () { + _Misc_tga__WEBPACK_IMPORTED_MODULE_0__["TGATools"].UploadContent(texture, uintData); + }); + }; + return _TGATextureLoader; +}()); + +// Register the loader. +_Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"]._TextureLoaders.push(new _TGATextureLoader()); + + +/***/ }), + +/***/ "./Materials/Textures/MultiviewRenderTarget.ts": +/*!*****************************************************!*\ + !*** ./Materials/Textures/MultiviewRenderTarget.ts ***! + \*****************************************************/ +/*! exports provided: MultiviewRenderTarget */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MultiviewRenderTarget", function() { return MultiviewRenderTarget; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Textures/renderTargetTexture */ "./Materials/Textures/renderTargetTexture.ts"); +/* harmony import */ var _Textures_internalTexture__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Textures/internalTexture */ "./Materials/Textures/internalTexture.ts"); + + + +/** + * Renders to multiple views with a single draw call + * @see https://www.khronos.org/registry/webgl/extensions/WEBGL_multiview/ + */ +var MultiviewRenderTarget = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](MultiviewRenderTarget, _super); + /** + * Creates a multiview render target + * @param scene scene used with the render target + * @param size the size of the render target (used for each view) + */ + function MultiviewRenderTarget(scene, size) { + if (size === void 0) { size = 512; } + var _this = _super.call(this, "multiview rtt", size, scene, false, true, _Textures_internalTexture__WEBPACK_IMPORTED_MODULE_2__["InternalTexture"].DATASOURCE_UNKNOWN, false, undefined, false, false, true, undefined, true) || this; + var internalTexture = scene.getEngine().createMultiviewRenderTargetTexture(_this.getRenderWidth(), _this.getRenderHeight()); + internalTexture.isMultiview = true; + _this._texture = internalTexture; + return _this; + } + /** + * @hidden + * @param faceIndex the face index, if its a cube texture + */ + MultiviewRenderTarget.prototype._bindFrameBuffer = function (faceIndex) { + if (faceIndex === void 0) { faceIndex = 0; } + if (!this._texture) { + return; + } + this.getScene().getEngine().bindMultiviewFramebuffer(this._texture); + }; + /** + * Gets the number of views the corresponding to the texture (eg. a MultiviewRenderTarget will have > 1) + * @returns the view count + */ + MultiviewRenderTarget.prototype.getViewCount = function () { + return 2; + }; + return MultiviewRenderTarget; +}(_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_1__["RenderTargetTexture"])); + + + +/***/ }), + +/***/ "./Materials/Textures/Procedurals/customProceduralTexture.ts": +/*!*******************************************************************!*\ + !*** ./Materials/Textures/Procedurals/customProceduralTexture.ts ***! + \*******************************************************************/ +/*! exports provided: CustomProceduralTexture */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CustomProceduralTexture", function() { return CustomProceduralTexture; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../../Misc/logger */ "./Misc/logger.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../../Materials/Textures/texture */ "./Materials/Textures/texture.ts"); +/* harmony import */ var _proceduralTexture__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./proceduralTexture */ "./Materials/Textures/Procedurals/proceduralTexture.ts"); +/* harmony import */ var _Misc_webRequest__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../../Misc/webRequest */ "./Misc/webRequest.ts"); + + + + + + +/** + * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images. + * Custom Procedural textures are the easiest way to create your own procedural in your application. + * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures#creating-custom-procedural-textures + */ +var CustomProceduralTexture = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](CustomProceduralTexture, _super); + /** + * Instantiates a new Custom Procedural Texture. + * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images. + * Custom Procedural textures are the easiest way to create your own procedural in your application. + * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures#creating-custom-procedural-textures + * @param name Define the name of the texture + * @param texturePath Define the folder path containing all the cutom texture related files (config, shaders...) + * @param size Define the size of the texture to create + * @param scene Define the scene the texture belongs to + * @param fallbackTexture Define a fallback texture in case there were issues to create the custom texture + * @param generateMipMaps Define if the texture should creates mip maps or not + */ + function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) { + var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this; + _this._animate = true; + _this._time = 0; + _this._texturePath = texturePath; + //Try to load json + _this._loadJson(texturePath); + _this.refreshRate = 1; + return _this; + } + CustomProceduralTexture.prototype._loadJson = function (jsonUrl) { + var _this = this; + var noConfigFile = function () { + _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element"); + try { + _this.setFragment(_this._texturePath); + } + catch (ex) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Error("No json or ShaderStore or DOM element found for CustomProceduralTexture"); + } + }; + var configFileUrl = jsonUrl + "/config.json"; + var xhr = new _Misc_webRequest__WEBPACK_IMPORTED_MODULE_5__["WebRequest"](); + xhr.open("GET", configFileUrl); + xhr.addEventListener("load", function () { + if (xhr.status === 200 || (xhr.responseText && xhr.responseText.length > 0)) { + try { + _this._config = JSON.parse(xhr.response); + _this.updateShaderUniforms(); + _this.updateTextures(); + _this.setFragment(_this._texturePath + "/custom"); + _this._animate = _this._config.animate; + _this.refreshRate = _this._config.refreshrate; + } + catch (ex) { + noConfigFile(); + } + } + else { + noConfigFile(); + } + }, false); + xhr.addEventListener("error", function () { + noConfigFile(); + }, false); + try { + xhr.send(); + } + catch (ex) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Error("CustomProceduralTexture: Error on XHR send request."); + } + }; + /** + * Is the texture ready to be used ? (rendered at least once) + * @returns true if ready, otherwise, false. + */ + CustomProceduralTexture.prototype.isReady = function () { + if (!_super.prototype.isReady.call(this)) { + return false; + } + for (var name in this._textures) { + var texture = this._textures[name]; + if (!texture.isReady()) { + return false; + } + } + return true; + }; + /** + * Render the texture to its associated render target. + * @param useCameraPostProcess Define if camera post process should be applied to the texture + */ + CustomProceduralTexture.prototype.render = function (useCameraPostProcess) { + var scene = this.getScene(); + if (this._animate && scene) { + this._time += scene.getAnimationRatio() * 0.03; + this.updateShaderUniforms(); + } + _super.prototype.render.call(this, useCameraPostProcess); + }; + /** + * Update the list of dependant textures samplers in the shader. + */ + CustomProceduralTexture.prototype.updateTextures = function () { + for (var i = 0; i < this._config.sampler2Ds.length; i++) { + this.setTexture(this._config.sampler2Ds[i].sample2Dname, new _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_3__["Texture"](this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene())); + } + }; + /** + * Update the uniform values of the procedural texture in the shader. + */ + CustomProceduralTexture.prototype.updateShaderUniforms = function () { + if (this._config) { + for (var j = 0; j < this._config.uniforms.length; j++) { + var uniform = this._config.uniforms[j]; + switch (uniform.type) { + case "float": + this.setFloat(uniform.name, uniform.value); + break; + case "color3": + this.setColor3(uniform.name, new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color3"](uniform.r, uniform.g, uniform.b)); + break; + case "color4": + this.setColor4(uniform.name, new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color4"](uniform.r, uniform.g, uniform.b, uniform.a)); + break; + case "vector2": + this.setVector2(uniform.name, new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector2"](uniform.x, uniform.y)); + break; + case "vector3": + this.setVector3(uniform.name, new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](uniform.x, uniform.y, uniform.z)); + break; + } + } + } + this.setFloat("time", this._time); + }; + Object.defineProperty(CustomProceduralTexture.prototype, "animate", { + /** + * Define if the texture animates or not. + */ + get: function () { + return this._animate; + }, + set: function (value) { + this._animate = value; + }, + enumerable: true, + configurable: true + }); + return CustomProceduralTexture; +}(_proceduralTexture__WEBPACK_IMPORTED_MODULE_4__["ProceduralTexture"])); + + + +/***/ }), + +/***/ "./Materials/Textures/Procedurals/index.ts": +/*!*************************************************!*\ + !*** ./Materials/Textures/Procedurals/index.ts ***! + \*************************************************/ +/*! exports provided: CustomProceduralTexture, NoiseProceduralTexture, ProceduralTexture, ProceduralTextureSceneComponent */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _customProceduralTexture__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./customProceduralTexture */ "./Materials/Textures/Procedurals/customProceduralTexture.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CustomProceduralTexture", function() { return _customProceduralTexture__WEBPACK_IMPORTED_MODULE_0__["CustomProceduralTexture"]; }); + +/* harmony import */ var _noiseProceduralTexture__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./noiseProceduralTexture */ "./Materials/Textures/Procedurals/noiseProceduralTexture.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NoiseProceduralTexture", function() { return _noiseProceduralTexture__WEBPACK_IMPORTED_MODULE_1__["NoiseProceduralTexture"]; }); + +/* harmony import */ var _proceduralTexture__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./proceduralTexture */ "./Materials/Textures/Procedurals/proceduralTexture.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ProceduralTexture", function() { return _proceduralTexture__WEBPACK_IMPORTED_MODULE_2__["ProceduralTexture"]; }); + +/* harmony import */ var _proceduralTextureSceneComponent__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./proceduralTextureSceneComponent */ "./Materials/Textures/Procedurals/proceduralTextureSceneComponent.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ProceduralTextureSceneComponent", function() { return _proceduralTextureSceneComponent__WEBPACK_IMPORTED_MODULE_3__["ProceduralTextureSceneComponent"]; }); + + + + + + + +/***/ }), + +/***/ "./Materials/Textures/Procedurals/noiseProceduralTexture.ts": +/*!******************************************************************!*\ + !*** ./Materials/Textures/Procedurals/noiseProceduralTexture.ts ***! + \******************************************************************/ +/*! exports provided: NoiseProceduralTexture */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NoiseProceduralTexture", function() { return NoiseProceduralTexture; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Engines_engineStore__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../../Engines/engineStore */ "./Engines/engineStore.ts"); +/* harmony import */ var _proceduralTexture__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./proceduralTexture */ "./Materials/Textures/Procedurals/proceduralTexture.ts"); +/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../../Misc/typeStore */ "./Misc/typeStore.ts"); +/* harmony import */ var _Shaders_noise_fragment__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Shaders/noise.fragment */ "./Shaders/noise.fragment.ts"); + + + + + +/** + * Class used to generate noise procedural textures + */ +var NoiseProceduralTexture = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](NoiseProceduralTexture, _super); + /** + * Creates a new NoiseProceduralTexture + * @param name defines the name fo the texture + * @param size defines the size of the texture (default is 256) + * @param scene defines the hosting scene + * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created + * @param generateMipMaps defines if mipmaps must be generated (true by default) + */ + function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) { + if (size === void 0) { size = 256; } + if (scene === void 0) { scene = _Engines_engineStore__WEBPACK_IMPORTED_MODULE_1__["EngineStore"].LastCreatedScene; } + var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this; + _this._time = 0; + /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */ + _this.brightness = 0.2; + /** Defines the number of octaves to process */ + _this.octaves = 3; + /** Defines the level of persistence (0.8 by default) */ + _this.persistence = 0.8; + /** Gets or sets animation speed factor (default is 1) */ + _this.animationSpeedFactor = 1; + _this.autoClear = false; + _this._updateShaderUniforms(); + return _this; + } + NoiseProceduralTexture.prototype._updateShaderUniforms = function () { + var scene = this.getScene(); + if (!scene) { + return; + } + this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01; + this.setFloat("brightness", this.brightness); + this.setFloat("persistence", this.persistence); + this.setFloat("timeScale", this._time); + }; + NoiseProceduralTexture.prototype._getDefines = function () { + return "#define OCTAVES " + (this.octaves | 0); + }; + /** Generate the current state of the procedural texture */ + NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) { + this._updateShaderUniforms(); + _super.prototype.render.call(this, useCameraPostProcess); + }; + /** + * Serializes this noise procedural texture + * @returns a serialized noise procedural texture object + */ + NoiseProceduralTexture.prototype.serialize = function () { + var serializationObject = {}; + serializationObject.customType = "BABYLON.NoiseProceduralTexture"; + serializationObject.brightness = this.brightness; + serializationObject.octaves = this.octaves; + serializationObject.persistence = this.persistence; + serializationObject.animationSpeedFactor = this.animationSpeedFactor; + serializationObject.size = this.getSize().width; + serializationObject.generateMipMaps = this._generateMipMaps; + return serializationObject; + }; + /** + * Creates a NoiseProceduralTexture from parsed noise procedural texture data + * @param parsedTexture defines parsed texture data + * @param scene defines the current scene + * @param rootUrl defines the root URL containing noise procedural texture information + * @returns a parsed NoiseProceduralTexture + */ + NoiseProceduralTexture.Parse = function (parsedTexture, scene) { + var texture = new NoiseProceduralTexture(parsedTexture.name, parsedTexture.size, scene, undefined, parsedTexture.generateMipMaps); + texture.brightness = parsedTexture.brightness; + texture.octaves = parsedTexture.octaves; + texture.persistence = parsedTexture.persistence; + texture.animationSpeedFactor = parsedTexture.animationSpeedFactor; + return texture; + }; + return NoiseProceduralTexture; +}(_proceduralTexture__WEBPACK_IMPORTED_MODULE_2__["ProceduralTexture"])); + +_Misc_typeStore__WEBPACK_IMPORTED_MODULE_3__["_TypeStore"].RegisteredTypes["BABYLON.NoiseProceduralTexture"] = NoiseProceduralTexture; + + +/***/ }), + +/***/ "./Materials/Textures/Procedurals/proceduralTexture.ts": +/*!*************************************************************!*\ + !*** ./Materials/Textures/Procedurals/proceduralTexture.ts ***! + \*************************************************************/ +/*! exports provided: ProceduralTexture */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ProceduralTexture", function() { return ProceduralTexture; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../../Meshes/buffer */ "./Meshes/buffer.ts"); +/* harmony import */ var _sceneComponent__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../sceneComponent */ "./sceneComponent.ts"); +/* harmony import */ var _Materials_material__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../../Materials/material */ "./Materials/material.ts"); +/* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../../Materials/Textures/texture */ "./Materials/Textures/texture.ts"); +/* harmony import */ var _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../../Materials/Textures/renderTargetTexture */ "./Materials/Textures/renderTargetTexture.ts"); +/* harmony import */ var _proceduralTextureSceneComponent__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./proceduralTextureSceneComponent */ "./Materials/Textures/Procedurals/proceduralTextureSceneComponent.ts"); +/* harmony import */ var _Engines_Extensions_engine_renderTarget__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../../../Engines/Extensions/engine.renderTarget */ "./Engines/Extensions/engine.renderTarget.ts"); +/* harmony import */ var _Shaders_procedural_vertex__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../../../Shaders/procedural.vertex */ "./Shaders/procedural.vertex.ts"); + + + + + + + + + + + +/** + * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes calmpler' images. + * This is the base class of any Procedural texture and contains most of the shareable code. + * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures + */ +var ProceduralTexture = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ProceduralTexture, _super); + /** + * Instantiates a new procedural texture. + * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images. + * This is the base class of any Procedural texture and contains most of the shareable code. + * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures + * @param name Define the name of the texture + * @param size Define the size of the texture to create + * @param fragment Define the fragment shader to use to generate the texture or null if it is defined later + * @param scene Define the scene the texture belongs to + * @param fallbackTexture Define a fallback texture in case there were issues to create the custom texture + * @param generateMipMaps Define if the texture should creates mip maps or not + * @param isCube Define if the texture is a cube texture or not (this will render each faces of the cube) + */ + function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) { + if (fallbackTexture === void 0) { fallbackTexture = null; } + if (generateMipMaps === void 0) { generateMipMaps = true; } + if (isCube === void 0) { isCube = false; } + var _this = _super.call(this, null, scene, !generateMipMaps) || this; + _this.isCube = isCube; + /** + * Define if the texture is enabled or not (disabled texture will not render) + */ + _this.isEnabled = true; + /** + * Define if the texture must be cleared before rendering (default is true) + */ + _this.autoClear = true; + /** + * Event raised when the texture is generated + */ + _this.onGeneratedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); + /** @hidden */ + _this._textures = {}; + _this._currentRefreshId = -1; + _this._refreshRate = 1; + _this._vertexBuffers = {}; + _this._uniforms = new Array(); + _this._samplers = new Array(); + _this._floats = {}; + _this._ints = {}; + _this._floatsArrays = {}; + _this._colors3 = {}; + _this._colors4 = {}; + _this._vectors2 = {}; + _this._vectors3 = {}; + _this._matrices = {}; + _this._fallbackTextureUsed = false; + _this._cachedDefines = ""; + _this._contentUpdateId = -1; + scene = _this.getScene(); + var component = scene._getComponent(_sceneComponent__WEBPACK_IMPORTED_MODULE_4__["SceneComponentConstants"].NAME_PROCEDURALTEXTURE); + if (!component) { + component = new _proceduralTextureSceneComponent__WEBPACK_IMPORTED_MODULE_8__["ProceduralTextureSceneComponent"](scene); + scene._addComponent(component); + } + scene.proceduralTextures.push(_this); + _this._engine = scene.getEngine(); + _this.name = name; + _this.isRenderTarget = true; + _this._size = size; + _this._generateMipMaps = generateMipMaps; + _this.setFragment(fragment); + _this._fallbackTexture = fallbackTexture; + if (isCube) { + _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps, generateDepthBuffer: false, generateStencilBuffer: false }); + _this.setFloat("face", 0); + } + else { + _this._texture = _this._engine.createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, generateDepthBuffer: false, generateStencilBuffer: false }); + } + // VBO + var vertices = []; + vertices.push(1, 1); + vertices.push(-1, 1); + vertices.push(-1, -1); + vertices.push(1, -1); + _this._vertexBuffers[_Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__["VertexBuffer"].PositionKind] = new _Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__["VertexBuffer"](_this._engine, vertices, _Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__["VertexBuffer"].PositionKind, false, false, 2); + _this._createIndexBuffer(); + return _this; + } + /** + * The effect that is created when initializing the post process. + * @returns The created effect corrisponding the the postprocess. + */ + ProceduralTexture.prototype.getEffect = function () { + return this._effect; + }; + /** + * Gets texture content (Use this function wisely as reading from a texture can be slow) + * @returns an ArrayBufferView (Uint8Array or Float32Array) + */ + ProceduralTexture.prototype.getContent = function () { + if (this._contentData && this._currentRefreshId == this._contentUpdateId) { + return this._contentData; + } + this._contentData = this.readPixels(0, 0, this._contentData); + this._contentUpdateId = this._currentRefreshId; + return this._contentData; + }; + ProceduralTexture.prototype._createIndexBuffer = function () { + var engine = this._engine; + // Indices + var indices = []; + indices.push(0); + indices.push(1); + indices.push(2); + indices.push(0); + indices.push(2); + indices.push(3); + this._indexBuffer = engine.createIndexBuffer(indices); + }; + /** @hidden */ + ProceduralTexture.prototype._rebuild = function () { + var vb = this._vertexBuffers[_Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__["VertexBuffer"].PositionKind]; + if (vb) { + vb._rebuild(); + } + this._createIndexBuffer(); + if (this.refreshRate === _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_7__["RenderTargetTexture"].REFRESHRATE_RENDER_ONCE) { + this.refreshRate = _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_7__["RenderTargetTexture"].REFRESHRATE_RENDER_ONCE; + } + }; + /** + * Resets the texture in order to recreate its associated resources. + * This can be called in case of context loss + */ + ProceduralTexture.prototype.reset = function () { + if (this._effect === undefined) { + return; + } + this._effect.dispose(); + }; + ProceduralTexture.prototype._getDefines = function () { + return ""; + }; + /** + * Is the texture ready to be used ? (rendered at least once) + * @returns true if ready, otherwise, false. + */ + ProceduralTexture.prototype.isReady = function () { + var _this = this; + var engine = this._engine; + var shaders; + if (!this._fragment) { + return false; + } + if (this._fallbackTextureUsed) { + return true; + } + var defines = this._getDefines(); + if (this._effect && defines === this._cachedDefines && this._effect.isReady()) { + return true; + } + if (this._fragment.fragmentElement !== undefined) { + shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement }; + } + else { + shaders = { vertex: "procedural", fragment: this._fragment }; + } + this._cachedDefines = defines; + this._effect = engine.createEffect(shaders, [_Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__["VertexBuffer"].PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, function () { + _this.releaseInternalTexture(); + if (_this._fallbackTexture) { + _this._texture = _this._fallbackTexture._texture; + if (_this._texture) { + _this._texture.incrementReferences(); + } + } + _this._fallbackTextureUsed = true; + }); + return this._effect.isReady(); + }; + /** + * Resets the refresh counter of the texture and start bak from scratch. + * Could be useful to regenerate the texture if it is setup to render only once. + */ + ProceduralTexture.prototype.resetRefreshCounter = function () { + this._currentRefreshId = -1; + }; + /** + * Set the fragment shader to use in order to render the texture. + * @param fragment This can be set to a path (into the shader store) or to a json object containing a fragmentElement property. + */ + ProceduralTexture.prototype.setFragment = function (fragment) { + this._fragment = fragment; + }; + Object.defineProperty(ProceduralTexture.prototype, "refreshRate", { + /** + * Define the refresh rate of the texture or the rendering frequency. + * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on... + */ + get: function () { + return this._refreshRate; + }, + set: function (value) { + this._refreshRate = value; + this.resetRefreshCounter(); + }, + enumerable: true, + configurable: true + }); + /** @hidden */ + ProceduralTexture.prototype._shouldRender = function () { + if (!this.isEnabled || !this.isReady() || !this._texture) { + if (this._texture) { + this._texture.isReady = false; + } + return false; + } + if (this._fallbackTextureUsed) { + return false; + } + if (this._currentRefreshId === -1) { // At least render once + this._currentRefreshId = 1; + return true; + } + if (this.refreshRate === this._currentRefreshId) { + this._currentRefreshId = 1; + return true; + } + this._currentRefreshId++; + return false; + }; + /** + * Get the size the texture is rendering at. + * @returns the size (texture is always squared) + */ + ProceduralTexture.prototype.getRenderSize = function () { + return this._size; + }; + /** + * Resize the texture to new value. + * @param size Define the new size the texture should have + * @param generateMipMaps Define whether the new texture should create mip maps + */ + ProceduralTexture.prototype.resize = function (size, generateMipMaps) { + if (this._fallbackTextureUsed) { + return; + } + this.releaseInternalTexture(); + this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps); + // Update properties + this._size = size; + this._generateMipMaps = generateMipMaps; + }; + ProceduralTexture.prototype._checkUniform = function (uniformName) { + if (this._uniforms.indexOf(uniformName) === -1) { + this._uniforms.push(uniformName); + } + }; + /** + * Set a texture in the shader program used to render. + * @param name Define the name of the uniform samplers as defined in the shader + * @param texture Define the texture to bind to this sampler + * @return the texture itself allowing "fluent" like uniform updates + */ + ProceduralTexture.prototype.setTexture = function (name, texture) { + if (this._samplers.indexOf(name) === -1) { + this._samplers.push(name); + } + this._textures[name] = texture; + return this; + }; + /** + * Set a float in the shader. + * @param name Define the name of the uniform as defined in the shader + * @param value Define the value to give to the uniform + * @return the texture itself allowing "fluent" like uniform updates + */ + ProceduralTexture.prototype.setFloat = function (name, value) { + this._checkUniform(name); + this._floats[name] = value; + return this; + }; + /** + * Set a int in the shader. + * @param name Define the name of the uniform as defined in the shader + * @param value Define the value to give to the uniform + * @return the texture itself allowing "fluent" like uniform updates + */ + ProceduralTexture.prototype.setInt = function (name, value) { + this._checkUniform(name); + this._ints[name] = value; + return this; + }; + /** + * Set an array of floats in the shader. + * @param name Define the name of the uniform as defined in the shader + * @param value Define the value to give to the uniform + * @return the texture itself allowing "fluent" like uniform updates + */ + ProceduralTexture.prototype.setFloats = function (name, value) { + this._checkUniform(name); + this._floatsArrays[name] = value; + return this; + }; + /** + * Set a vec3 in the shader from a Color3. + * @param name Define the name of the uniform as defined in the shader + * @param value Define the value to give to the uniform + * @return the texture itself allowing "fluent" like uniform updates + */ + ProceduralTexture.prototype.setColor3 = function (name, value) { + this._checkUniform(name); + this._colors3[name] = value; + return this; + }; + /** + * Set a vec4 in the shader from a Color4. + * @param name Define the name of the uniform as defined in the shader + * @param value Define the value to give to the uniform + * @return the texture itself allowing "fluent" like uniform updates + */ + ProceduralTexture.prototype.setColor4 = function (name, value) { + this._checkUniform(name); + this._colors4[name] = value; + return this; + }; + /** + * Set a vec2 in the shader from a Vector2. + * @param name Define the name of the uniform as defined in the shader + * @param value Define the value to give to the uniform + * @return the texture itself allowing "fluent" like uniform updates + */ + ProceduralTexture.prototype.setVector2 = function (name, value) { + this._checkUniform(name); + this._vectors2[name] = value; + return this; + }; + /** + * Set a vec3 in the shader from a Vector3. + * @param name Define the name of the uniform as defined in the shader + * @param value Define the value to give to the uniform + * @return the texture itself allowing "fluent" like uniform updates + */ + ProceduralTexture.prototype.setVector3 = function (name, value) { + this._checkUniform(name); + this._vectors3[name] = value; + return this; + }; + /** + * Set a mat4 in the shader from a MAtrix. + * @param name Define the name of the uniform as defined in the shader + * @param value Define the value to give to the uniform + * @return the texture itself allowing "fluent" like uniform updates + */ + ProceduralTexture.prototype.setMatrix = function (name, value) { + this._checkUniform(name); + this._matrices[name] = value; + return this; + }; + /** + * Render the texture to its associated render target. + * @param useCameraPostProcess Define if camera post process should be applied to the texture + */ + ProceduralTexture.prototype.render = function (useCameraPostProcess) { + var scene = this.getScene(); + if (!scene) { + return; + } + var engine = this._engine; + // Render + engine.enableEffect(this._effect); + engine.setState(false); + // Texture + for (var name in this._textures) { + this._effect.setTexture(name, this._textures[name]); + } + // Float + for (name in this._ints) { + this._effect.setInt(name, this._ints[name]); + } + // Float + for (name in this._floats) { + this._effect.setFloat(name, this._floats[name]); + } + // Floats + for (name in this._floatsArrays) { + this._effect.setArray(name, this._floatsArrays[name]); + } + // Color3 + for (name in this._colors3) { + this._effect.setColor3(name, this._colors3[name]); + } + // Color4 + for (name in this._colors4) { + var color = this._colors4[name]; + this._effect.setFloat4(name, color.r, color.g, color.b, color.a); + } + // Vector2 + for (name in this._vectors2) { + this._effect.setVector2(name, this._vectors2[name]); + } + // Vector3 + for (name in this._vectors3) { + this._effect.setVector3(name, this._vectors3[name]); + } + // Matrix + for (name in this._matrices) { + this._effect.setMatrix(name, this._matrices[name]); + } + if (!this._texture) { + return; + } + if (this.isCube) { + for (var face = 0; face < 6; face++) { + engine.bindFramebuffer(this._texture, face, undefined, undefined, true); + // VBOs + engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect); + this._effect.setFloat("face", face); + // Clear + if (this.autoClear) { + engine.clear(scene.clearColor, true, false, false); + } + // Draw order + engine.drawElementsType(_Materials_material__WEBPACK_IMPORTED_MODULE_5__["Material"].TriangleFillMode, 0, 6); + // Mipmaps + if (face === 5) { + engine.generateMipMapsForCubemap(this._texture); + } + } + } + else { + engine.bindFramebuffer(this._texture, 0, undefined, undefined, true); + // VBOs + engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect); + // Clear + if (this.autoClear) { + engine.clear(scene.clearColor, true, false, false); + } + // Draw order + engine.drawElementsType(_Materials_material__WEBPACK_IMPORTED_MODULE_5__["Material"].TriangleFillMode, 0, 6); + } + // Unbind + engine.unBindFramebuffer(this._texture, this.isCube); + if (this.onGenerated) { + this.onGenerated(); + } + this.onGeneratedObservable.notifyObservers(this); + }; + /** + * Clone the texture. + * @returns the cloned texture + */ + ProceduralTexture.prototype.clone = function () { + var textureSize = this.getSize(); + var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps); + // Base texture + newTexture.hasAlpha = this.hasAlpha; + newTexture.level = this.level; + // RenderTarget Texture + newTexture.coordinatesMode = this.coordinatesMode; + return newTexture; + }; + /** + * Dispose the texture and release its asoociated resources. + */ + ProceduralTexture.prototype.dispose = function () { + var scene = this.getScene(); + if (!scene) { + return; + } + var index = scene.proceduralTextures.indexOf(this); + if (index >= 0) { + scene.proceduralTextures.splice(index, 1); + } + var vertexBuffer = this._vertexBuffers[_Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__["VertexBuffer"].PositionKind]; + if (vertexBuffer) { + vertexBuffer.dispose(); + this._vertexBuffers[_Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__["VertexBuffer"].PositionKind] = null; + } + if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) { + this._indexBuffer = null; + } + _super.prototype.dispose.call(this); + }; + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ProceduralTexture.prototype, "isEnabled", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ProceduralTexture.prototype, "autoClear", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ProceduralTexture.prototype, "_generateMipMaps", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ProceduralTexture.prototype, "_size", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ProceduralTexture.prototype, "refreshRate", null); + return ProceduralTexture; +}(_Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__["Texture"])); + + + +/***/ }), + +/***/ "./Materials/Textures/Procedurals/proceduralTextureSceneComponent.ts": +/*!***************************************************************************!*\ + !*** ./Materials/Textures/Procedurals/proceduralTextureSceneComponent.ts ***! + \***************************************************************************/ +/*! exports provided: ProceduralTextureSceneComponent */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ProceduralTextureSceneComponent", function() { return ProceduralTextureSceneComponent; }); +/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../../Misc/tools */ "./Misc/tools.ts"); +/* harmony import */ var _sceneComponent__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../../sceneComponent */ "./sceneComponent.ts"); + + +/** + * Defines the Procedural Texture scene component responsible to manage any Procedural Texture + * in a given scene. + */ +var ProceduralTextureSceneComponent = /** @class */ (function () { + /** + * Creates a new instance of the component for the given scene + * @param scene Defines the scene to register the component in + */ + function ProceduralTextureSceneComponent(scene) { + /** + * The component name helpfull to identify the component in the list of scene components. + */ + this.name = _sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].NAME_PROCEDURALTEXTURE; + this.scene = scene; + this.scene.proceduralTextures = new Array(); + } + /** + * Registers the component in a given scene + */ + ProceduralTextureSceneComponent.prototype.register = function () { + this.scene._beforeClearStage.registerStep(_sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear); + }; + /** + * Rebuilds the elements related to this component in case of + * context lost for instance. + */ + ProceduralTextureSceneComponent.prototype.rebuild = function () { + // Nothing to do here. + }; + /** + * Disposes the component and the associated ressources. + */ + ProceduralTextureSceneComponent.prototype.dispose = function () { + // Nothing to do here. + }; + ProceduralTextureSceneComponent.prototype._beforeClear = function () { + if (this.scene.proceduralTexturesEnabled) { + _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].StartPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0); + for (var proceduralIndex = 0; proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) { + var proceduralTexture = this.scene.proceduralTextures[proceduralIndex]; + if (proceduralTexture._shouldRender()) { + proceduralTexture.render(); + } + } + _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0); + } + }; + return ProceduralTextureSceneComponent; +}()); + + + +/***/ }), + +/***/ "./Materials/Textures/baseTexture.ts": +/*!*******************************************!*\ + !*** ./Materials/Textures/baseTexture.ts ***! + \*******************************************/ +/*! exports provided: BaseTexture */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BaseTexture", function() { return BaseTexture; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Misc/tools */ "./Misc/tools.ts"); +/* harmony import */ var _Misc_HighDynamicRange_cubemapToSphericalPolynomial__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Misc/HighDynamicRange/cubemapToSphericalPolynomial */ "./Misc/HighDynamicRange/cubemapToSphericalPolynomial.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Engines_engineStore__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../Engines/engineStore */ "./Engines/engineStore.ts"); +/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../Engines/constants */ "./Engines/constants.ts"); + + + + + + + + +/** + * Base class of all the textures in babylon. + * It groups all the common properties the materials, post process, lights... might need + * in order to make a correct use of the texture. + */ +var BaseTexture = /** @class */ (function () { + /** + * Instantiates a new BaseTexture. + * Base class of all the textures in babylon. + * It groups all the common properties the materials, post process, lights... might need + * in order to make a correct use of the texture. + * @param scene Define the scene the texture blongs to + */ + function BaseTexture(scene) { + /** + * Gets or sets an object used to store user defined information. + */ + this.metadata = null; + /** + * For internal use only. Please do not use. + */ + this.reservedDataStore = null; + this._hasAlpha = false; + /** + * Defines if the alpha value should be determined via the rgb values. + * If true the luminance of the pixel might be used to find the corresponding alpha value. + */ + this.getAlphaFromRGB = false; + /** + * Intensity or strength of the texture. + * It is commonly used by materials to fine tune the intensity of the texture + */ + this.level = 1; + /** + * Define the UV chanel to use starting from 0 and defaulting to 0. + * This is part of the texture as textures usually maps to one uv set. + */ + this.coordinatesIndex = 0; + this._coordinatesMode = _Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURE_EXPLICIT_MODE; + /** + * | Value | Type | Description | + * | ----- | ------------------ | ----------- | + * | 0 | CLAMP_ADDRESSMODE | | + * | 1 | WRAP_ADDRESSMODE | | + * | 2 | MIRROR_ADDRESSMODE | | + */ + this.wrapU = _Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURE_WRAP_ADDRESSMODE; + /** + * | Value | Type | Description | + * | ----- | ------------------ | ----------- | + * | 0 | CLAMP_ADDRESSMODE | | + * | 1 | WRAP_ADDRESSMODE | | + * | 2 | MIRROR_ADDRESSMODE | | + */ + this.wrapV = _Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURE_WRAP_ADDRESSMODE; + /** + * | Value | Type | Description | + * | ----- | ------------------ | ----------- | + * | 0 | CLAMP_ADDRESSMODE | | + * | 1 | WRAP_ADDRESSMODE | | + * | 2 | MIRROR_ADDRESSMODE | | + */ + this.wrapR = _Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURE_WRAP_ADDRESSMODE; + /** + * With compliant hardware and browser (supporting anisotropic filtering) + * this defines the level of anisotropic filtering in the texture. + * The higher the better but the slower. This defaults to 4 as it seems to be the best tradeoff. + */ + this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL; + /** + * Define if the texture contains data in gamma space (most of the png/jpg aside bump). + * HDR texture are usually stored in linear space. + * This only impacts the PBR and Background materials + */ + this.gammaSpace = true; + /** + * Is Z inverted in the texture (useful in a cube texture). + */ + this.invertZ = false; + /** + * @hidden + */ + this.lodLevelInAlpha = false; + /** + * Define if the texture is a render target. + */ + this.isRenderTarget = false; + /** + * Define the list of animation attached to the texture. + */ + this.animations = new Array(); + /** + * An event triggered when the texture is disposed. + */ + this.onDisposeObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); + this._onDisposeObserver = null; + /** + * Define the current state of the loading sequence when in delayed load mode. + */ + this.delayLoadState = _Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].DELAYLOADSTATE_NONE; + this._scene = null; + /** @hidden */ + this._texture = null; + this._uid = null; + this._cachedSize = _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Size"].Zero(); + this._scene = scene || _Engines_engineStore__WEBPACK_IMPORTED_MODULE_6__["EngineStore"].LastCreatedScene; + if (this._scene) { + this.uniqueId = this._scene.getUniqueId(); + this._scene.addTexture(this); + } + this._uid = null; + } + Object.defineProperty(BaseTexture.prototype, "hasAlpha", { + get: function () { + return this._hasAlpha; + }, + /** + * Define if the texture is having a usable alpha value (can be use for transparency or glossiness for instance). + */ + set: function (value) { + if (this._hasAlpha === value) { + return; + } + this._hasAlpha = value; + if (this._scene) { + this._scene.markAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].MATERIAL_TextureDirtyFlag | _Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].MATERIAL_MiscDirtyFlag); + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(BaseTexture.prototype, "coordinatesMode", { + get: function () { + return this._coordinatesMode; + }, + /** + * How a texture is mapped. + * + * | Value | Type | Description | + * | ----- | ----------------------------------- | ----------- | + * | 0 | EXPLICIT_MODE | | + * | 1 | SPHERICAL_MODE | | + * | 2 | PLANAR_MODE | | + * | 3 | CUBIC_MODE | | + * | 4 | PROJECTION_MODE | | + * | 5 | SKYBOX_MODE | | + * | 6 | INVCUBIC_MODE | | + * | 7 | EQUIRECTANGULAR_MODE | | + * | 8 | FIXED_EQUIRECTANGULAR_MODE | | + * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | | + */ + set: function (value) { + if (this._coordinatesMode === value) { + return; + } + this._coordinatesMode = value; + if (this._scene) { + this._scene.markAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].MATERIAL_TextureDirtyFlag); + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(BaseTexture.prototype, "isCube", { + /** + * Define if the texture is a cube texture or if false a 2d texture. + */ + get: function () { + if (!this._texture) { + return false; + } + return this._texture.isCube; + }, + set: function (value) { + if (!this._texture) { + return; + } + this._texture.isCube = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(BaseTexture.prototype, "is3D", { + /** + * Define if the texture is a 3d texture (webgl 2) or if false a 2d texture. + */ + get: function () { + if (!this._texture) { + return false; + } + return this._texture.is3D; + }, + set: function (value) { + if (!this._texture) { + return; + } + this._texture.is3D = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(BaseTexture.prototype, "isRGBD", { + /** + * Gets whether or not the texture contains RGBD data. + */ + get: function () { + return this._texture != null && this._texture._isRGBD; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(BaseTexture.prototype, "noMipmap", { + /** + * Are mip maps generated for this texture or not. + */ + get: function () { + return false; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", { + /** + * With prefiltered texture, defined the offset used during the prefiltering steps. + */ + get: function () { + if (this._texture) { + return this._texture._lodGenerationOffset; + } + return 0.0; + }, + set: function (value) { + if (this._texture) { + this._texture._lodGenerationOffset = value; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", { + /** + * With prefiltered texture, defined the scale used during the prefiltering steps. + */ + get: function () { + if (this._texture) { + return this._texture._lodGenerationScale; + } + return 0.0; + }, + set: function (value) { + if (this._texture) { + this._texture._lodGenerationScale = value; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(BaseTexture.prototype, "linearSpecularLOD", { + /** + * With prefiltered texture, defined if the specular generation is based on a linear ramp. + * By default we are using a log2 of the linear roughness helping to keep a better resolution for + * average roughness values. + */ + get: function () { + if (this._texture) { + return this._texture._linearSpecularLOD; + } + return false; + }, + set: function (value) { + if (this._texture) { + this._texture._linearSpecularLOD = value; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(BaseTexture.prototype, "irradianceTexture", { + /** + * In case a better definition than spherical harmonics is required for the diffuse part of the environment. + * You can set the irradiance texture to rely on a texture instead of the spherical approach. + * This texture need to have the same characteristics than its parent (Cube vs 2d, coordinates mode, Gamma/Linear, RGBD). + */ + get: function () { + if (this._texture) { + return this._texture._irradianceTexture; + } + return null; + }, + set: function (value) { + if (this._texture) { + this._texture._irradianceTexture = value; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(BaseTexture.prototype, "uid", { + /** + * Define the unique id of the texture in the scene. + */ + get: function () { + if (!this._uid) { + this._uid = _Misc_tools__WEBPACK_IMPORTED_MODULE_3__["Tools"].RandomId(); + } + return this._uid; + }, + enumerable: true, + configurable: true + }); + /** + * Return a string representation of the texture. + * @returns the texture as a string + */ + BaseTexture.prototype.toString = function () { + return this.name; + }; + /** + * Get the class name of the texture. + * @returns "BaseTexture" + */ + BaseTexture.prototype.getClassName = function () { + return "BaseTexture"; + }; + Object.defineProperty(BaseTexture.prototype, "onDispose", { + /** + * Callback triggered when the texture has been disposed. + * Kept for back compatibility, you can use the onDisposeObservable instead. + */ + set: function (callback) { + if (this._onDisposeObserver) { + this.onDisposeObservable.remove(this._onDisposeObserver); + } + this._onDisposeObserver = this.onDisposeObservable.add(callback); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(BaseTexture.prototype, "isBlocking", { + /** + * Define if the texture is preventinga material to render or not. + * If not and the texture is not ready, the engine will use a default black texture instead. + */ + get: function () { + return true; + }, + enumerable: true, + configurable: true + }); + /** + * Get the scene the texture belongs to. + * @returns the scene or null if undefined + */ + BaseTexture.prototype.getScene = function () { + return this._scene; + }; + /** + * Get the texture transform matrix used to offset tile the texture for istance. + * @returns the transformation matrix + */ + BaseTexture.prototype.getTextureMatrix = function () { + return _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Matrix"].IdentityReadOnly; + }; + /** + * Get the texture reflection matrix used to rotate/transform the reflection. + * @returns the reflection matrix + */ + BaseTexture.prototype.getReflectionTextureMatrix = function () { + return _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Matrix"].IdentityReadOnly; + }; + /** + * Get the underlying lower level texture from Babylon. + * @returns the insternal texture + */ + BaseTexture.prototype.getInternalTexture = function () { + return this._texture; + }; + /** + * Get if the texture is ready to be consumed (either it is ready or it is not blocking) + * @returns true if ready or not blocking + */ + BaseTexture.prototype.isReadyOrNotBlocking = function () { + return !this.isBlocking || this.isReady(); + }; + /** + * Get if the texture is ready to be used (downloaded, converted, mip mapped...). + * @returns true if fully ready + */ + BaseTexture.prototype.isReady = function () { + if (this.delayLoadState === _Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].DELAYLOADSTATE_NOTLOADED) { + this.delayLoad(); + return false; + } + if (this._texture) { + return this._texture.isReady; + } + return false; + }; + /** + * Get the size of the texture. + * @returns the texture size. + */ + BaseTexture.prototype.getSize = function () { + if (this._texture) { + if (this._texture.width) { + this._cachedSize.width = this._texture.width; + this._cachedSize.height = this._texture.height; + return this._cachedSize; + } + if (this._texture._size) { + this._cachedSize.width = this._texture._size; + this._cachedSize.height = this._texture._size; + return this._cachedSize; + } + } + return this._cachedSize; + }; + /** + * Get the base size of the texture. + * It can be different from the size if the texture has been resized for POT for instance + * @returns the base size + */ + BaseTexture.prototype.getBaseSize = function () { + if (!this.isReady() || !this._texture) { + return _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Size"].Zero(); + } + if (this._texture._size) { + return new _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Size"](this._texture._size, this._texture._size); + } + return new _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Size"](this._texture.baseWidth, this._texture.baseHeight); + }; + /** + * Update the sampling mode of the texture. + * Default is Trilinear mode. + * + * | Value | Type | Description | + * | ----- | ------------------ | ----------- | + * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear | + * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest | + * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear | + * | 4 | NEAREST_NEAREST_MIPNEAREST | | + * | 5 | NEAREST_LINEAR_MIPNEAREST | | + * | 6 | NEAREST_LINEAR_MIPLINEAR | | + * | 7 | NEAREST_LINEAR | | + * | 8 | NEAREST_NEAREST | | + * | 9 | LINEAR_NEAREST_MIPNEAREST | | + * | 10 | LINEAR_NEAREST_MIPLINEAR | | + * | 11 | LINEAR_LINEAR | | + * | 12 | LINEAR_NEAREST | | + * + * > _mag_: magnification filter (close to the viewer) + * > _min_: minification filter (far from the viewer) + * > _mip_: filter used between mip map levels + *@param samplingMode Define the new sampling mode of the texture + */ + BaseTexture.prototype.updateSamplingMode = function (samplingMode) { + if (!this._texture) { + return; + } + var scene = this.getScene(); + if (!scene) { + return; + } + scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture); + }; + /** + * Scales the texture if is `canRescale()` + * @param ratio the resize factor we want to use to rescale + */ + BaseTexture.prototype.scale = function (ratio) { + }; + Object.defineProperty(BaseTexture.prototype, "canRescale", { + /** + * Get if the texture can rescale. + */ + get: function () { + return false; + }, + enumerable: true, + configurable: true + }); + /** @hidden */ + BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling, invertY) { + if (!this._scene) { + return null; + } + var texturesCache = this._scene.getEngine().getLoadedTexturesCache(); + for (var index = 0; index < texturesCache.length; index++) { + var texturesCacheEntry = texturesCache[index]; + if (invertY === undefined || invertY === texturesCacheEntry.invertY) { + if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) { + if (!sampling || sampling === texturesCacheEntry.samplingMode) { + texturesCacheEntry.incrementReferences(); + return texturesCacheEntry; + } + } + } + } + return null; + }; + /** @hidden */ + BaseTexture.prototype._rebuild = function () { + }; + /** + * Triggers the load sequence in delayed load mode. + */ + BaseTexture.prototype.delayLoad = function () { + }; + /** + * Clones the texture. + * @returns the cloned texture + */ + BaseTexture.prototype.clone = function () { + return null; + }; + Object.defineProperty(BaseTexture.prototype, "textureType", { + /** + * Get the texture underlying type (INT, FLOAT...) + */ + get: function () { + if (!this._texture) { + return _Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_UNSIGNED_INT; + } + return (this._texture.type !== undefined) ? this._texture.type : _Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_UNSIGNED_INT; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(BaseTexture.prototype, "textureFormat", { + /** + * Get the texture underlying format (RGB, RGBA...) + */ + get: function () { + if (!this._texture) { + return _Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RGBA; + } + return (this._texture.format !== undefined) ? this._texture.format : _Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RGBA; + }, + enumerable: true, + configurable: true + }); + /** + * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer. + * This will returns an RGBA array buffer containing either in values (0-255) or + * float values (0-1) depending of the underlying buffer type. + * @param faceIndex defines the face of the texture to read (in case of cube texture) + * @param level defines the LOD level of the texture to read (in case of Mip Maps) + * @param buffer defines a user defined buffer to fill with data (can be null) + * @returns The Array buffer containing the pixels data. + */ + BaseTexture.prototype.readPixels = function (faceIndex, level, buffer) { + if (faceIndex === void 0) { faceIndex = 0; } + if (level === void 0) { level = 0; } + if (buffer === void 0) { buffer = null; } + if (!this._texture) { + return null; + } + var size = this.getSize(); + var width = size.width; + var height = size.height; + var scene = this.getScene(); + if (!scene) { + return null; + } + var engine = scene.getEngine(); + if (level != 0) { + width = width / Math.pow(2, level); + height = height / Math.pow(2, level); + width = Math.round(width); + height = Math.round(height); + } + if (this._texture.isCube) { + return engine._readTexturePixels(this._texture, width, height, faceIndex, level, buffer); + } + return engine._readTexturePixels(this._texture, width, height, -1, level, buffer); + }; + /** + * Release and destroy the underlying lower level texture aka internalTexture. + */ + BaseTexture.prototype.releaseInternalTexture = function () { + if (this._texture) { + this._texture.dispose(); + this._texture = null; + } + }; + Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", { + /** + * Get the polynomial representation of the texture data. + * This is mainly use as a fast way to recover IBL Diffuse irradiance data. + * @see https://learnopengl.com/PBR/IBL/Diffuse-irradiance + */ + get: function () { + if (!this._texture || !_Misc_HighDynamicRange_cubemapToSphericalPolynomial__WEBPACK_IMPORTED_MODULE_4__["CubeMapToSphericalPolynomialTools"] || !this.isReady()) { + return null; + } + if (!this._texture._sphericalPolynomial) { + this._texture._sphericalPolynomial = + _Misc_HighDynamicRange_cubemapToSphericalPolynomial__WEBPACK_IMPORTED_MODULE_4__["CubeMapToSphericalPolynomialTools"].ConvertCubeMapTextureToSphericalPolynomial(this); + } + return this._texture._sphericalPolynomial; + }, + set: function (value) { + if (this._texture) { + this._texture._sphericalPolynomial = value; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", { + /** @hidden */ + get: function () { + if (this._texture) { + return this._texture._lodTextureHigh; + } + return null; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", { + /** @hidden */ + get: function () { + if (this._texture) { + return this._texture._lodTextureMid; + } + return null; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", { + /** @hidden */ + get: function () { + if (this._texture) { + return this._texture._lodTextureLow; + } + return null; + }, + enumerable: true, + configurable: true + }); + /** + * Dispose the texture and release its associated resources. + */ + BaseTexture.prototype.dispose = function () { + if (!this._scene) { + return; + } + // Animations + if (this._scene.stopAnimation) { + this._scene.stopAnimation(this); + } + // Remove from scene + this._scene._removePendingData(this); + var index = this._scene.textures.indexOf(this); + if (index >= 0) { + this._scene.textures.splice(index, 1); + } + this._scene.onTextureRemovedObservable.notifyObservers(this); + if (this._texture === undefined) { + return; + } + // Release + this.releaseInternalTexture(); + // Callback + this.onDisposeObservable.notifyObservers(this); + this.onDisposeObservable.clear(); + }; + /** + * Serialize the texture into a JSON representation that can be parsed later on. + * @returns the JSON representation of the texture + */ + BaseTexture.prototype.serialize = function () { + if (!this.name) { + return null; + } + var serializationObject = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(this); + // Animations + _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].AppendSerializedAnimations(this, serializationObject); + return serializationObject; + }; + /** + * Helper function to be called back once a list of texture contains only ready textures. + * @param textures Define the list of textures to wait for + * @param callback Define the callback triggered once the entire list will be ready + */ + BaseTexture.WhenAllReady = function (textures, callback) { + var numRemaining = textures.length; + if (numRemaining === 0) { + callback(); + return; + } + var _loop_1 = function () { + texture = textures[i]; + if (texture.isReady()) { + if (--numRemaining === 0) { + callback(); + } + } + else { + onLoadObservable = texture.onLoadObservable; + var onLoadCallback_1 = function () { + onLoadObservable.removeCallback(onLoadCallback_1); + if (--numRemaining === 0) { + callback(); + } + }; + onLoadObservable.add(onLoadCallback_1); + } + }; + var texture, onLoadObservable; + for (var i = 0; i < textures.length; i++) { + _loop_1(); + } + }; + /** + * Default anisotropic filtering level for the application. + * It is set to 4 as a good tradeoff between perf and quality. + */ + BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4; + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], BaseTexture.prototype, "uniqueId", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], BaseTexture.prototype, "name", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], BaseTexture.prototype, "metadata", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])("hasAlpha") + ], BaseTexture.prototype, "_hasAlpha", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], BaseTexture.prototype, "getAlphaFromRGB", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], BaseTexture.prototype, "level", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], BaseTexture.prototype, "coordinatesIndex", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])("coordinatesMode") + ], BaseTexture.prototype, "_coordinatesMode", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], BaseTexture.prototype, "wrapU", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], BaseTexture.prototype, "wrapV", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], BaseTexture.prototype, "wrapR", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], BaseTexture.prototype, "isCube", null); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], BaseTexture.prototype, "is3D", null); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], BaseTexture.prototype, "gammaSpace", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], BaseTexture.prototype, "invertZ", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], BaseTexture.prototype, "lodLevelInAlpha", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], BaseTexture.prototype, "lodGenerationOffset", null); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], BaseTexture.prototype, "lodGenerationScale", null); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], BaseTexture.prototype, "linearSpecularLOD", null); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])() + ], BaseTexture.prototype, "irradianceTexture", null); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], BaseTexture.prototype, "isRenderTarget", void 0); + return BaseTexture; +}()); + + + +/***/ }), + +/***/ "./Materials/Textures/colorGradingTexture.ts": +/*!***************************************************!*\ + !*** ./Materials/Textures/colorGradingTexture.ts ***! + \***************************************************/ +/*! exports provided: ColorGradingTexture */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorGradingTexture", function() { return ColorGradingTexture; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Materials_Textures_baseTexture__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Materials/Textures/baseTexture */ "./Materials/Textures/baseTexture.ts"); +/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Engines/constants */ "./Engines/constants.ts"); +/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Misc/typeStore */ "./Misc/typeStore.ts"); + + + + + +/** + * This represents a color grading texture. This acts as a lookup table LUT, useful during post process + * It can help converting any input color in a desired output one. This can then be used to create effects + * from sepia, black and white to sixties or futuristic rendering... + * + * The only supported format is currently 3dl. + * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table + */ +var ColorGradingTexture = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ColorGradingTexture, _super); + /** + * Instantiates a ColorGradingTexture from the following parameters. + * + * @param url The location of the color gradind data (currently only supporting 3dl) + * @param scene The scene the texture will be used in + */ + function ColorGradingTexture(url, scene) { + var _this = _super.call(this, scene) || this; + if (!url) { + return _this; + } + _this._engine = scene.getEngine(); + _this._textureMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Identity(); + _this.name = url; + _this.url = url; + _this.hasAlpha = false; + _this.isCube = false; + _this.is3D = _this._engine.webGLVersion > 1; + _this.wrapU = _Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].TEXTURE_CLAMP_ADDRESSMODE; + _this.wrapV = _Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].TEXTURE_CLAMP_ADDRESSMODE; + _this.wrapR = _Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].TEXTURE_CLAMP_ADDRESSMODE; + _this.anisotropicFilteringLevel = 1; + _this._texture = _this._getFromCache(url, true); + if (!_this._texture) { + if (!scene.useDelayedTextureLoading) { + _this.loadTexture(); + } + else { + _this.delayLoadState = _Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].DELAYLOADSTATE_NOTLOADED; + } + } + return _this; + } + /** + * Returns the texture matrix used in most of the material. + * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in). + */ + ColorGradingTexture.prototype.getTextureMatrix = function () { + return this._textureMatrix; + }; + /** + * Occurs when the file being loaded is a .3dl LUT file. + */ + ColorGradingTexture.prototype.load3dlTexture = function () { + var engine = this._engine; + var texture; + if (engine.webGLVersion === 1) { + texture = engine.createRawTexture(null, 1, 1, _Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].TEXTUREFORMAT_RGBA, false, false, _Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].TEXTURE_BILINEAR_SAMPLINGMODE); + } + else { + texture = engine.createRawTexture3D(null, 1, 1, 1, _Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].TEXTUREFORMAT_RGBA, false, false, _Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].TEXTURE_BILINEAR_SAMPLINGMODE); + } + this._texture = texture; + var callback = function (text) { + if (typeof text !== "string") { + return; + } + var data = null; + var tempData = null; + var line; + var lines = text.split('\n'); + var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0; + var maxColor = 0; + for (var i = 0; i < lines.length; i++) { + line = lines[i]; + if (!ColorGradingTexture._noneEmptyLineRegex.test(line)) { + continue; + } + if (line.indexOf('#') === 0) { + continue; + } + var words = line.split(" "); + if (size === 0) { + // Number of space + one + size = words.length; + data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8 + tempData = new Float32Array(size * size * size * 4); + continue; + } + if (size != 0) { + var r = Math.max(parseInt(words[0]), 0); + var g = Math.max(parseInt(words[1]), 0); + var b = Math.max(parseInt(words[2]), 0); + maxColor = Math.max(r, maxColor); + maxColor = Math.max(g, maxColor); + maxColor = Math.max(b, maxColor); + var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4; + if (tempData) { + tempData[pixelStorageIndex + 0] = r; + tempData[pixelStorageIndex + 1] = g; + tempData[pixelStorageIndex + 2] = b; + } + // Keep for reference in case of back compat problems. + // pixelIndexSlice++; + // if (pixelIndexSlice % size == 0) { + // pixelIndexH++; + // pixelIndexSlice = 0; + // if (pixelIndexH % size == 0) { + // pixelIndexW++; + // pixelIndexH = 0; + // } + // } + pixelIndexH++; + if (pixelIndexH % size == 0) { + pixelIndexSlice++; + pixelIndexH = 0; + if (pixelIndexSlice % size == 0) { + pixelIndexW++; + pixelIndexSlice = 0; + } + } + } + } + if (tempData && data) { + for (var i = 0; i < tempData.length; i++) { + if (i > 0 && (i + 1) % 4 === 0) { + data[i] = 255; + } + else { + var value = tempData[i]; + data[i] = (value / maxColor * 255); + } + } + } + if (texture.is3D) { + texture.updateSize(size, size, size); + engine.updateRawTexture3D(texture, data, _Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].TEXTUREFORMAT_RGBA, false); + } + else { + texture.updateSize(size * size, size); + engine.updateRawTexture(texture, data, _Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].TEXTUREFORMAT_RGBA, false); + } + }; + var scene = this.getScene(); + if (scene) { + scene._loadFile(this.url, callback); + } + else { + this._engine._loadFile(this.url, callback); + } + return this._texture; + }; + /** + * Starts the loading process of the texture. + */ + ColorGradingTexture.prototype.loadTexture = function () { + if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) { + this.load3dlTexture(); + } + }; + /** + * Clones the color gradind texture. + */ + ColorGradingTexture.prototype.clone = function () { + var newTexture = new ColorGradingTexture(this.url, this.getScene()); + // Base texture + newTexture.level = this.level; + return newTexture; + }; + /** + * Called during delayed load for textures. + */ + ColorGradingTexture.prototype.delayLoad = function () { + if (this.delayLoadState !== _Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].DELAYLOADSTATE_NOTLOADED) { + return; + } + this.delayLoadState = _Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].DELAYLOADSTATE_LOADED; + this._texture = this._getFromCache(this.url, true); + if (!this._texture) { + this.loadTexture(); + } + }; + /** + * Parses a color grading texture serialized by Babylon. + * @param parsedTexture The texture information being parsedTexture + * @param scene The scene to load the texture in + * @param rootUrl The root url of the data assets to load + * @return A color gradind texture + */ + ColorGradingTexture.Parse = function (parsedTexture, scene) { + var texture = null; + if (parsedTexture.name && !parsedTexture.isRenderTarget) { + texture = new ColorGradingTexture(parsedTexture.name, scene); + texture.name = parsedTexture.name; + texture.level = parsedTexture.level; + } + return texture; + }; + /** + * Serializes the LUT texture to json format. + */ + ColorGradingTexture.prototype.serialize = function () { + if (!this.name) { + return null; + } + var serializationObject = {}; + serializationObject.name = this.name; + serializationObject.level = this.level; + serializationObject.customType = "BABYLON.ColorGradingTexture"; + return serializationObject; + }; + /** + * Empty line regex stored for GC. + */ + ColorGradingTexture._noneEmptyLineRegex = /\S+/; + return ColorGradingTexture; +}(_Materials_Textures_baseTexture__WEBPACK_IMPORTED_MODULE_2__["BaseTexture"])); + +_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.ColorGradingTexture"] = ColorGradingTexture; + + +/***/ }), + +/***/ "./Materials/Textures/cubeTexture.ts": +/*!*******************************************!*\ + !*** ./Materials/Textures/cubeTexture.ts ***! + \*******************************************/ +/*! exports provided: CubeTexture */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CubeTexture", function() { return CubeTexture; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/tools */ "./Misc/tools.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Materials_Textures_baseTexture__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Materials/Textures/baseTexture */ "./Materials/Textures/baseTexture.ts"); +/* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Materials/Textures/texture */ "./Materials/Textures/texture.ts"); +/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../Engines/constants */ "./Engines/constants.ts"); +/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../Misc/typeStore */ "./Misc/typeStore.ts"); +/* harmony import */ var _Engines_Extensions_engine_cubeTexture__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../Engines/Extensions/engine.cubeTexture */ "./Engines/Extensions/engine.cubeTexture.ts"); + + + + + + + + + +/** + * Class for creating a cube texture + */ +var CubeTexture = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](CubeTexture, _super); + /** + * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well + * as prefiltered data. + * @param rootUrl defines the url of the texture or the root name of the six images + * @param scene defines the scene the texture is attached to + * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg... + * @param noMipmap defines if mipmaps should be created or not + * @param files defines the six files to load for the different faces in that order: px, py, pz, nx, ny, nz + * @param onLoad defines a callback triggered at the end of the file load if no errors occured + * @param onError defines a callback triggered in case of error during load + * @param format defines the internal format to use for the texture once loaded + * @param prefiltered defines whether or not the texture is created from prefiltered data + * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name + * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary + * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness + * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness + * @return the cube texture + */ + function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) { + if (extensions === void 0) { extensions = null; } + if (noMipmap === void 0) { noMipmap = false; } + if (files === void 0) { files = null; } + if (onLoad === void 0) { onLoad = null; } + if (onError === void 0) { onError = null; } + if (format === void 0) { format = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTUREFORMAT_RGBA; } + if (prefiltered === void 0) { prefiltered = false; } + if (forcedExtension === void 0) { forcedExtension = null; } + if (createPolynomials === void 0) { createPolynomials = false; } + if (lodScale === void 0) { lodScale = 0.8; } + if (lodOffset === void 0) { lodOffset = 0; } + var _this = _super.call(this, scene) || this; + /** + * Gets or sets the center of the bounding box associated with the cube texture. + * It must define where the camera used to render the texture was set + * @see http://doc.babylonjs.com/how_to/reflect#using-local-cubemap-mode + */ + _this.boundingBoxPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(); + _this._rotationY = 0; + /** @hidden */ + _this._prefiltered = false; + _this.name = rootUrl; + _this.url = rootUrl; + _this._noMipmap = noMipmap; + _this.hasAlpha = false; + _this._format = format; + _this.isCube = true; + _this._textureMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"].Identity(); + _this._createPolynomials = createPolynomials; + _this.coordinatesMode = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_5__["Texture"].CUBIC_MODE; + if (!rootUrl && !files) { + return _this; + } + var lastDot = rootUrl.lastIndexOf("."); + var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : ""); + var isDDS = (extension === ".dds"); + var isEnv = (extension === ".env"); + if (isEnv) { + _this.gammaSpace = false; + _this._prefiltered = false; + } + else { + _this._prefiltered = prefiltered; + if (prefiltered) { + _this.gammaSpace = false; + } + } + _this._texture = _this._getFromCache(rootUrl, noMipmap); + if (!files) { + if (!isEnv && !isDDS && !extensions) { + extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"]; + } + files = []; + if (extensions) { + for (var index = 0; index < extensions.length; index++) { + files.push(rootUrl + extensions[index]); + } + } + } + _this._files = files; + if (!_this._texture) { + if (!scene.useDelayedTextureLoading) { + if (prefiltered) { + _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials); + } + else { + _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset); + } + } + else { + _this.delayLoadState = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].DELAYLOADSTATE_NOTLOADED; + } + } + else if (onLoad) { + if (_this._texture.isReady) { + _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].SetImmediate(function () { return onLoad(); }); + } + else { + _this._texture.onLoadedObservable.add(onLoad); + } + } + return _this; + } + Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", { + /** + * Returns the bounding box size + * @see http://doc.babylonjs.com/how_to/reflect#using-local-cubemap-mode + */ + get: function () { + return this._boundingBoxSize; + }, + /** + * Gets or sets the size of the bounding box associated with the cube texture + * When defined, the cubemap will switch to local mode + * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity + * @example https://www.babylonjs-playground.com/#RNASML + */ + set: function (value) { + if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) { + return; + } + this._boundingBoxSize = value; + var scene = this.getScene(); + if (scene) { + scene.markAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].MATERIAL_TextureDirtyFlag); + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(CubeTexture.prototype, "rotationY", { + /** + * Gets texture matrix rotation angle around Y axis radians. + */ + get: function () { + return this._rotationY; + }, + /** + * Sets texture matrix rotation angle around Y axis in radians. + */ + set: function (value) { + this._rotationY = value; + this.setReflectionTextureMatrix(_Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"].RotationY(this._rotationY)); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(CubeTexture.prototype, "noMipmap", { + /** + * Are mip maps generated for this texture or not. + */ + get: function () { + return this._noMipmap; + }, + enumerable: true, + configurable: true + }); + /** + * Creates a cube texture from an array of image urls + * @param files defines an array of image urls + * @param scene defines the hosting scene + * @param noMipmap specifies if mip maps are not used + * @returns a cube texture + */ + CubeTexture.CreateFromImages = function (files, scene, noMipmap) { + var rootUrlKey = ""; + files.forEach(function (url) { return rootUrlKey += url; }); + return new CubeTexture(rootUrlKey, scene, null, noMipmap, files); + }; + /** + * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys. + * @param url defines the url of the prefiltered texture + * @param scene defines the scene the texture is attached to + * @param forcedExtension defines the extension of the file if different from the url + * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary + * @return the prefiltered texture + */ + CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) { + if (forcedExtension === void 0) { forcedExtension = null; } + if (createPolynomials === void 0) { createPolynomials = true; } + return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials); + }; + Object.defineProperty(CubeTexture.prototype, "isPrefiltered", { + /** + * Gets a boolean indicating if the cube texture contains prefiltered mips (used to simulate roughness with PBR) + */ + get: function () { + return this._prefiltered; + }, + enumerable: true, + configurable: true + }); + /** + * Get the current class name of the texture useful for serialization or dynamic coding. + * @returns "CubeTexture" + */ + CubeTexture.prototype.getClassName = function () { + return "CubeTexture"; + }; + /** + * Update the url (and optional buffer) of this texture if url was null during construction. + * @param url the url of the texture + * @param forcedExtension defines the extension to use + * @param onLoad callback called when the texture is loaded (defaults to null) + */ + CubeTexture.prototype.updateURL = function (url, forcedExtension, onLoad) { + if (this.url) { + this.releaseInternalTexture(); + this.getScene().markAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].MATERIAL_TextureDirtyFlag); + } + this.url = url; + this.delayLoadState = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].DELAYLOADSTATE_NOTLOADED; + this._prefiltered = false; + if (onLoad) { + this._delayedOnLoad = onLoad; + } + this.delayLoad(forcedExtension); + }; + /** + * Delays loading of the cube texture + * @param forcedExtension defines the extension to use + */ + CubeTexture.prototype.delayLoad = function (forcedExtension) { + if (this.delayLoadState !== _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].DELAYLOADSTATE_NOTLOADED) { + return; + } + var scene = this.getScene(); + if (!scene) { + return; + } + this.delayLoadState = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].DELAYLOADSTATE_LOADED; + this._texture = this._getFromCache(this.url, this._noMipmap); + if (!this._texture) { + if (this._prefiltered) { + this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, this._delayedOnLoad, undefined, this._format, undefined, this._createPolynomials); + } + else { + this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, this._delayedOnLoad, null, this._format, forcedExtension); + } + } + }; + /** + * Returns the reflection texture matrix + * @returns the reflection texture matrix + */ + CubeTexture.prototype.getReflectionTextureMatrix = function () { + return this._textureMatrix; + }; + /** + * Sets the reflection texture matrix + * @param value Reflection texture matrix + */ + CubeTexture.prototype.setReflectionTextureMatrix = function (value) { + var _this = this; + if (value.updateFlag === this._textureMatrix.updateFlag) { + return; + } + if (value.isIdentity() !== this._textureMatrix.isIdentity()) { + this.getScene().markAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].MATERIAL_TextureDirtyFlag, function (mat) { return mat.getActiveTextures().indexOf(_this) !== -1; }); + } + this._textureMatrix = value; + }; + /** + * Parses text to create a cube texture + * @param parsedTexture define the serialized text to read from + * @param scene defines the hosting scene + * @param rootUrl defines the root url of the cube texture + * @returns a cube texture + */ + CubeTexture.Parse = function (parsedTexture, scene, rootUrl) { + var texture = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(function () { + var prefiltered = false; + if (parsedTexture.prefiltered) { + prefiltered = parsedTexture.prefiltered; + } + return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered); + }, parsedTexture, scene); + // Local Cubemaps + if (parsedTexture.boundingBoxPosition) { + texture.boundingBoxPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].FromArray(parsedTexture.boundingBoxPosition); + } + if (parsedTexture.boundingBoxSize) { + texture.boundingBoxSize = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].FromArray(parsedTexture.boundingBoxSize); + } + // Animations + if (parsedTexture.animations) { + for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) { + var parsedAnimation = parsedTexture.animations[animationIndex]; + var internalClass = _Misc_typeStore__WEBPACK_IMPORTED_MODULE_7__["_TypeStore"].GetClass("BABYLON.Animation"); + if (internalClass) { + texture.animations.push(internalClass.Parse(parsedAnimation)); + } + } + } + return texture; + }; + /** + * Makes a clone, or deep copy, of the cube texture + * @returns a new cube texture + */ + CubeTexture.prototype.clone = function () { + var _this = this; + var scene = this.getScene(); + var uniqueId = 0; + var newCubeTexture = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Clone(function () { + if (!scene) { + return _this; + } + var cubeTexture = new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files); + uniqueId = cubeTexture.uniqueId; + return cubeTexture; + }, this); + newCubeTexture.uniqueId = uniqueId; + return newCubeTexture; + }; + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])("rotationY") + ], CubeTexture.prototype, "rotationY", null); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsMatrix"])("textureMatrix") + ], CubeTexture.prototype, "_textureMatrix", void 0); + return CubeTexture; +}(_Materials_Textures_baseTexture__WEBPACK_IMPORTED_MODULE_4__["BaseTexture"])); + +_Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_5__["Texture"]._CubeTextureParser = CubeTexture.Parse; +// Some exporters relies on Tools.Instantiate +_Misc_typeStore__WEBPACK_IMPORTED_MODULE_7__["_TypeStore"].RegisteredTypes["BABYLON.CubeTexture"] = CubeTexture; + + +/***/ }), + +/***/ "./Materials/Textures/dynamicTexture.ts": +/*!**********************************************!*\ + !*** ./Materials/Textures/dynamicTexture.ts ***! + \**********************************************/ +/*! exports provided: DynamicTexture */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DynamicTexture", function() { return DynamicTexture; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/logger */ "./Misc/logger.ts"); +/* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Materials/Textures/texture */ "./Materials/Textures/texture.ts"); +/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Engines/constants */ "./Engines/constants.ts"); + + + + +/** + * A class extending Texture allowing drawing on a texture + * @see http://doc.babylonjs.com/how_to/dynamictexture + */ +var DynamicTexture = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](DynamicTexture, _super); + /** + * Creates a DynamicTexture + * @param name defines the name of the texture + * @param options provides 3 alternatives for width and height of texture, a canvas, object with width and height properties, number for both width and height + * @param scene defines the scene where you want the texture + * @param generateMipMaps defines the use of MinMaps or not (default is false) + * @param samplingMode defines the sampling mode to use (default is Texture.TRILINEAR_SAMPLINGMODE) + * @param format defines the texture format to use (default is Engine.TEXTUREFORMAT_RGBA) + */ + function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) { + if (scene === void 0) { scene = null; } + if (samplingMode === void 0) { samplingMode = _Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].TEXTURE_TRILINEAR_SAMPLINGMODE; } + if (format === void 0) { format = _Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].TEXTUREFORMAT_RGBA; } + var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this; + _this.name = name; + _this._engine = _this.getScene().getEngine(); + _this.wrapU = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_2__["Texture"].CLAMP_ADDRESSMODE; + _this.wrapV = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_2__["Texture"].CLAMP_ADDRESSMODE; + _this._generateMipMaps = generateMipMaps; + if (options.getContext) { + _this._canvas = options; + _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode); + } + else { + _this._canvas = document.createElement("canvas"); + if (options.width || options.width === 0) { + _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode); + } + else { + _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode); + } + } + var textureSize = _this.getSize(); + _this._canvas.width = textureSize.width; + _this._canvas.height = textureSize.height; + _this._context = _this._canvas.getContext("2d"); + return _this; + } + /** + * Get the current class name of the texture useful for serialization or dynamic coding. + * @returns "DynamicTexture" + */ + DynamicTexture.prototype.getClassName = function () { + return "DynamicTexture"; + }; + Object.defineProperty(DynamicTexture.prototype, "canRescale", { + /** + * Gets the current state of canRescale + */ + get: function () { + return true; + }, + enumerable: true, + configurable: true + }); + DynamicTexture.prototype._recreate = function (textureSize) { + this._canvas.width = textureSize.width; + this._canvas.height = textureSize.height; + this.releaseInternalTexture(); + this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this.samplingMode); + }; + /** + * Scales the texture + * @param ratio the scale factor to apply to both width and height + */ + DynamicTexture.prototype.scale = function (ratio) { + var textureSize = this.getSize(); + textureSize.width *= ratio; + textureSize.height *= ratio; + this._recreate(textureSize); + }; + /** + * Resizes the texture + * @param width the new width + * @param height the new height + */ + DynamicTexture.prototype.scaleTo = function (width, height) { + var textureSize = this.getSize(); + textureSize.width = width; + textureSize.height = height; + this._recreate(textureSize); + }; + /** + * Gets the context of the canvas used by the texture + * @returns the canvas context of the dynamic texture + */ + DynamicTexture.prototype.getContext = function () { + return this._context; + }; + /** + * Clears the texture + */ + DynamicTexture.prototype.clear = function () { + var size = this.getSize(); + this._context.fillRect(0, 0, size.width, size.height); + }; + /** + * Updates the texture + * @param invertY defines the direction for the Y axis (default is true - y increases downwards) + * @param premulAlpha defines if alpha is stored as premultiplied (default is false) + */ + DynamicTexture.prototype.update = function (invertY, premulAlpha) { + if (premulAlpha === void 0) { premulAlpha = false; } + this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined); + }; + /** + * Draws text onto the texture + * @param text defines the text to be drawn + * @param x defines the placement of the text from the left + * @param y defines the placement of the text from the top when invertY is true and from the bottom when false + * @param font defines the font to be used with font-style, font-size, font-name + * @param color defines the color used for the text + * @param clearColor defines the color for the canvas, use null to not overwrite canvas + * @param invertY defines the direction for the Y axis (default is true - y increases downwards) + * @param update defines whether texture is immediately update (default is true) + */ + DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) { + if (update === void 0) { update = true; } + var size = this.getSize(); + if (clearColor) { + this._context.fillStyle = clearColor; + this._context.fillRect(0, 0, size.width, size.height); + } + this._context.font = font; + if (x === null || x === undefined) { + var textSize = this._context.measureText(text); + x = (size.width - textSize.width) / 2; + } + if (y === null || y === undefined) { + var fontSize = parseInt((font.replace(/\D/g, ''))); + y = (size.height / 2) + (fontSize / 3.65); + } + this._context.fillStyle = color; + this._context.fillText(text, x, y); + if (update) { + this.update(invertY); + } + }; + /** + * Clones the texture + * @returns the clone of the texture. + */ + DynamicTexture.prototype.clone = function () { + var scene = this.getScene(); + if (!scene) { + return this; + } + var textureSize = this.getSize(); + var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps); + // Base texture + newTexture.hasAlpha = this.hasAlpha; + newTexture.level = this.level; + // Dynamic Texture + newTexture.wrapU = this.wrapU; + newTexture.wrapV = this.wrapV; + return newTexture; + }; + /** + * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized + * @returns a serialized dynamic texture object + */ + DynamicTexture.prototype.serialize = function () { + var scene = this.getScene(); + if (scene && !scene.isReady()) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn("The scene must be ready before serializing the dynamic texture"); + } + var serializationObject = _super.prototype.serialize.call(this); + serializationObject.base64String = this._canvas.toDataURL(); + serializationObject.invertY = this._invertY; + serializationObject.samplingMode = this.samplingMode; + return serializationObject; + }; + /** @hidden */ + DynamicTexture.prototype._rebuild = function () { + this.update(); + }; + return DynamicTexture; +}(_Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_2__["Texture"])); + + + +/***/ }), + +/***/ "./Materials/Textures/equiRectangularCubeTexture.ts": +/*!**********************************************************!*\ + !*** ./Materials/Textures/equiRectangularCubeTexture.ts ***! + \**********************************************************/ +/*! exports provided: EquiRectangularCubeTexture */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EquiRectangularCubeTexture", function() { return EquiRectangularCubeTexture; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_HighDynamicRange_panoramaToCubemap__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/HighDynamicRange/panoramaToCubemap */ "./Misc/HighDynamicRange/panoramaToCubemap.ts"); +/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Engines/engine */ "./Engines/engine.ts"); +/* harmony import */ var _baseTexture__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./baseTexture */ "./Materials/Textures/baseTexture.ts"); +/* harmony import */ var _texture__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./texture */ "./Materials/Textures/texture.ts"); +/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Misc/tools */ "./Misc/tools.ts"); +/* harmony import */ var _Engines_Extensions_engine_rawTexture__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../Engines/Extensions/engine.rawTexture */ "./Engines/Extensions/engine.rawTexture.ts"); + + + + + + + +/** + * This represents a texture coming from an equirectangular image supported by the web browser canvas. + */ +var EquiRectangularCubeTexture = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](EquiRectangularCubeTexture, _super); + /** + * Instantiates an EquiRectangularCubeTexture from the following parameters. + * @param url The location of the image + * @param scene The scene the texture will be used in + * @param size The cubemap desired size (the more it increases the longer the generation will be) + * @param noMipmap Forces to not generate the mipmap if true + * @param gammaSpace Specifies if the texture will be used in gamma or linear space + * (the PBR material requires those textures in linear space, but the standard material would require them in Gamma space) + * @param onLoad — defines a callback called when texture is loaded + * @param onError — defines a callback called if there is an error + */ + function EquiRectangularCubeTexture(url, scene, size, noMipmap, gammaSpace, onLoad, onError) { + if (noMipmap === void 0) { noMipmap = false; } + if (gammaSpace === void 0) { gammaSpace = true; } + if (onLoad === void 0) { onLoad = null; } + if (onError === void 0) { onError = null; } + var _this = _super.call(this, scene) || this; + _this._onLoad = null; + _this._onError = null; + /** The texture coordinates mode. As this texture is stored in a cube format, please modify carefully. */ + _this.coordinatesMode = _texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].CUBIC_MODE; + if (!url) { + throw new Error('Image url is not set'); + } + _this.name = url; + _this.url = url; + _this._size = size; + _this._noMipmap = noMipmap; + _this.gammaSpace = gammaSpace; + _this._onLoad = onLoad; + _this._onError = onError; + _this.hasAlpha = false; + _this.isCube = true; + _this._texture = _this._getFromCache(url, _this._noMipmap); + if (!_this._texture) { + if (!scene.useDelayedTextureLoading) { + _this.loadImage(_this.loadTexture.bind(_this), _this._onError); + } + else { + _this.delayLoadState = _Engines_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].DELAYLOADSTATE_NOTLOADED; + } + } + else if (onLoad) { + if (_this._texture.isReady) { + _Misc_tools__WEBPACK_IMPORTED_MODULE_5__["Tools"].SetImmediate(function () { return onLoad(); }); + } + else { + _this._texture.onLoadedObservable.add(onLoad); + } + } + return _this; + } + /** + * Load the image data, by putting the image on a canvas and extracting its buffer. + */ + EquiRectangularCubeTexture.prototype.loadImage = function (loadTextureCallback, onError) { + var _this = this; + var canvas = document.createElement('canvas'); + var image = new Image(); + image.addEventListener('load', function () { + _this._width = image.width; + _this._height = image.height; + canvas.width = _this._width; + canvas.height = _this._height; + var ctx = canvas.getContext('2d'); + ctx.drawImage(image, 0, 0); + var imageData = ctx.getImageData(0, 0, image.width, image.height); + _this._buffer = imageData.data.buffer; + canvas.remove(); + loadTextureCallback(); + }); + image.addEventListener('error', function (error) { + if (onError) { + onError(_this.getClassName() + " could not be loaded", error); + } + }); + image.src = this.url; + }; + /** + * Convert the image buffer into a cubemap and create a CubeTexture. + */ + EquiRectangularCubeTexture.prototype.loadTexture = function () { + var _this = this; + var scene = this.getScene(); + var callback = function () { + var imageData = _this.getFloat32ArrayFromArrayBuffer(_this._buffer); + // Extract the raw linear data. + var data = _Misc_HighDynamicRange_panoramaToCubemap__WEBPACK_IMPORTED_MODULE_1__["PanoramaToCubeMapTools"].ConvertPanoramaToCubemap(imageData, _this._width, _this._height, _this._size); + var results = []; + // Push each faces. + for (var i = 0; i < 6; i++) { + var dataFace = data[EquiRectangularCubeTexture._FacesMapping[i]]; + results.push(dataFace); + } + return results; + }; + if (!scene) { + return; + } + this._texture = scene + .getEngine() + .createRawCubeTextureFromUrl(this.url, scene, this._size, _Engines_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].TEXTUREFORMAT_RGB, scene.getEngine().getCaps().textureFloat + ? _Engines_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].TEXTURETYPE_FLOAT + : _Engines_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].TEXTURETYPE_UNSIGNED_INTEGER, this._noMipmap, callback, null, this._onLoad, this._onError); + }; + /** + * Convert the ArrayBuffer into a Float32Array and drop the transparency channel. + * @param buffer The ArrayBuffer that should be converted. + * @returns The buffer as Float32Array. + */ + EquiRectangularCubeTexture.prototype.getFloat32ArrayFromArrayBuffer = function (buffer) { + var dataView = new DataView(buffer); + var floatImageData = new Float32Array((buffer.byteLength * 3) / 4); + var k = 0; + for (var i = 0; i < buffer.byteLength; i++) { + // We drop the transparency channel, because we do not need/want it + if ((i + 1) % 4 !== 0) { + floatImageData[k++] = dataView.getUint8(i) / 255; + } + } + return floatImageData; + }; + /** + * Get the current class name of the texture useful for serialization or dynamic coding. + * @returns "EquiRectangularCubeTexture" + */ + EquiRectangularCubeTexture.prototype.getClassName = function () { + return "EquiRectangularCubeTexture"; + }; + /** + * Create a clone of the current EquiRectangularCubeTexture and return it. + * @returns A clone of the current EquiRectangularCubeTexture. + */ + EquiRectangularCubeTexture.prototype.clone = function () { + var scene = this.getScene(); + if (!scene) { + return this; + } + var newTexture = new EquiRectangularCubeTexture(this.url, scene, this._size, this._noMipmap, this.gammaSpace); + // Base texture + newTexture.level = this.level; + newTexture.wrapU = this.wrapU; + newTexture.wrapV = this.wrapV; + newTexture.coordinatesIndex = this.coordinatesIndex; + newTexture.coordinatesMode = this.coordinatesMode; + return newTexture; + }; + /** The six faces of the cube. */ + EquiRectangularCubeTexture._FacesMapping = ['right', 'left', 'up', 'down', 'front', 'back']; + return EquiRectangularCubeTexture; +}(_baseTexture__WEBPACK_IMPORTED_MODULE_3__["BaseTexture"])); + + + +/***/ }), + +/***/ "./Materials/Textures/hdrCubeTexture.ts": +/*!**********************************************!*\ + !*** ./Materials/Textures/hdrCubeTexture.ts ***! + \**********************************************/ +/*! exports provided: HDRCubeTexture */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HDRCubeTexture", function() { return HDRCubeTexture; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Engines/engine */ "./Engines/engine.ts"); +/* harmony import */ var _Materials_Textures_baseTexture__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Materials/Textures/baseTexture */ "./Materials/Textures/baseTexture.ts"); +/* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Materials/Textures/texture */ "./Materials/Textures/texture.ts"); +/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Engines/constants */ "./Engines/constants.ts"); +/* harmony import */ var _Misc_HighDynamicRange_hdr__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../Misc/HighDynamicRange/hdr */ "./Misc/HighDynamicRange/hdr.ts"); +/* harmony import */ var _Misc_HighDynamicRange_cubemapToSphericalPolynomial__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../Misc/HighDynamicRange/cubemapToSphericalPolynomial */ "./Misc/HighDynamicRange/cubemapToSphericalPolynomial.ts"); +/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../Misc/typeStore */ "./Misc/typeStore.ts"); +/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../../Misc/tools */ "./Misc/tools.ts"); +/* harmony import */ var _Engines_Extensions_engine_rawTexture__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../../Engines/Extensions/engine.rawTexture */ "./Engines/Extensions/engine.rawTexture.ts"); + + + + + + + + + + + +/** + * This represents a texture coming from an HDR input. + * + * The only supported format is currently panorama picture stored in RGBE format. + * Example of such files can be found on HDRLib: http://hdrlib.com/ + */ +var HDRCubeTexture = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](HDRCubeTexture, _super); + /** + * Instantiates an HDRTexture from the following parameters. + * + * @param url The location of the HDR raw data (Panorama stored in RGBE format) + * @param scene The scene the texture will be used in + * @param size The cubemap desired size (the more it increases the longer the generation will be) + * @param noMipmap Forces to not generate the mipmap if true + * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process + * @param gammaSpace Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) + * @param reserved Reserved flag for internal use. + */ + function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) { + if (noMipmap === void 0) { noMipmap = false; } + if (generateHarmonics === void 0) { generateHarmonics = true; } + if (gammaSpace === void 0) { gammaSpace = false; } + if (reserved === void 0) { reserved = false; } + if (onLoad === void 0) { onLoad = null; } + if (onError === void 0) { onError = null; } + var _this = _super.call(this, scene) || this; + _this._generateHarmonics = true; + _this._onLoad = null; + _this._onError = null; + /** + * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully. + */ + _this.coordinatesMode = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].CUBIC_MODE; + _this._isBlocking = true; + _this._rotationY = 0; + /** + * Gets or sets the center of the bounding box associated with the cube texture + * It must define where the camera used to render the texture was set + */ + _this.boundingBoxPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); + if (!url) { + return _this; + } + _this.name = url; + _this.url = url; + _this.hasAlpha = false; + _this.isCube = true; + _this._textureMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Identity(); + _this._onLoad = onLoad; + _this._onError = onError; + _this.gammaSpace = gammaSpace; + _this._noMipmap = noMipmap; + _this._size = size; + _this._texture = _this._getFromCache(url, _this._noMipmap); + if (!_this._texture) { + if (!scene.useDelayedTextureLoading) { + _this.loadTexture(); + } + else { + _this.delayLoadState = _Engines_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].DELAYLOADSTATE_NOTLOADED; + } + } + else if (onLoad) { + if (_this._texture.isReady) { + _Misc_tools__WEBPACK_IMPORTED_MODULE_9__["Tools"].SetImmediate(function () { return onLoad(); }); + } + else { + _this._texture.onLoadedObservable.add(onLoad); + } + } + return _this; + } + Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", { + /** + * Gets wether or not the texture is blocking during loading. + */ + get: function () { + return this._isBlocking; + }, + /** + * Sets wether or not the texture is blocking during loading. + */ + set: function (value) { + this._isBlocking = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(HDRCubeTexture.prototype, "rotationY", { + /** + * Gets texture matrix rotation angle around Y axis radians. + */ + get: function () { + return this._rotationY; + }, + /** + * Sets texture matrix rotation angle around Y axis in radians. + */ + set: function (value) { + this._rotationY = value; + this.setReflectionTextureMatrix(_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].RotationY(this._rotationY)); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", { + get: function () { + return this._boundingBoxSize; + }, + /** + * Gets or sets the size of the bounding box associated with the cube texture + * When defined, the cubemap will switch to local mode + * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity + * @example https://www.babylonjs-playground.com/#RNASML + */ + set: function (value) { + if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) { + return; + } + this._boundingBoxSize = value; + var scene = this.getScene(); + if (scene) { + scene.markAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_5__["Constants"].MATERIAL_TextureDirtyFlag); + } + }, + enumerable: true, + configurable: true + }); + /** + * Get the current class name of the texture useful for serialization or dynamic coding. + * @returns "HDRCubeTexture" + */ + HDRCubeTexture.prototype.getClassName = function () { + return "HDRCubeTexture"; + }; + /** + * Occurs when the file is raw .hdr file. + */ + HDRCubeTexture.prototype.loadTexture = function () { + var _this = this; + var callback = function (buffer) { + _this.lodGenerationOffset = 0.0; + _this.lodGenerationScale = 0.8; + var scene = _this.getScene(); + if (!scene) { + return null; + } + // Extract the raw linear data. + var data = _Misc_HighDynamicRange_hdr__WEBPACK_IMPORTED_MODULE_6__["HDRTools"].GetCubeMapTextureData(buffer, _this._size); + // Generate harmonics if needed. + if (_this._generateHarmonics) { + var sphericalPolynomial = _Misc_HighDynamicRange_cubemapToSphericalPolynomial__WEBPACK_IMPORTED_MODULE_7__["CubeMapToSphericalPolynomialTools"].ConvertCubeMapToSphericalPolynomial(data); + _this.sphericalPolynomial = sphericalPolynomial; + } + var results = []; + var byteArray = null; + // Push each faces. + for (var j = 0; j < 6; j++) { + // Create uintarray fallback. + if (!scene.getEngine().getCaps().textureFloat) { + // 3 channels of 1 bytes per pixel in bytes. + var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3); + byteArray = new Uint8Array(byteBuffer); + } + var dataFace = (data[HDRCubeTexture._facesMapping[j]]); + // If special cases. + if (_this.gammaSpace || byteArray) { + for (var i = 0; i < _this._size * _this._size; i++) { + // Put in gamma space if requested. + if (_this.gammaSpace) { + dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], _Maths_math__WEBPACK_IMPORTED_MODULE_1__["ToGammaSpace"]); + dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], _Maths_math__WEBPACK_IMPORTED_MODULE_1__["ToGammaSpace"]); + dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], _Maths_math__WEBPACK_IMPORTED_MODULE_1__["ToGammaSpace"]); + } + // Convert to int texture for fallback. + if (byteArray) { + var r = Math.max(dataFace[(i * 3) + 0] * 255, 0); + var g = Math.max(dataFace[(i * 3) + 1] * 255, 0); + var b = Math.max(dataFace[(i * 3) + 2] * 255, 0); + // May use luminance instead if the result is not accurate. + var max = Math.max(Math.max(r, g), b); + if (max > 255) { + var scale = 255 / max; + r *= scale; + g *= scale; + b *= scale; + } + byteArray[(i * 3) + 0] = r; + byteArray[(i * 3) + 1] = g; + byteArray[(i * 3) + 2] = b; + } + } + } + if (byteArray) { + results.push(byteArray); + } + else { + results.push(dataFace); + } + } + return results; + }; + var scene = this.getScene(); + if (scene) { + this._texture = scene.getEngine().createRawCubeTextureFromUrl(this.url, scene, this._size, _Engines_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].TEXTUREFORMAT_RGB, scene.getEngine().getCaps().textureFloat ? _Engines_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].TEXTURETYPE_FLOAT : _Engines_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, null, this._onLoad, this._onError); + } + }; + HDRCubeTexture.prototype.clone = function () { + var scene = this.getScene(); + if (!scene) { + return this; + } + var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace); + // Base texture + newTexture.level = this.level; + newTexture.wrapU = this.wrapU; + newTexture.wrapV = this.wrapV; + newTexture.coordinatesIndex = this.coordinatesIndex; + newTexture.coordinatesMode = this.coordinatesMode; + return newTexture; + }; + // Methods + HDRCubeTexture.prototype.delayLoad = function () { + if (this.delayLoadState !== _Engines_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].DELAYLOADSTATE_NOTLOADED) { + return; + } + this.delayLoadState = _Engines_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].DELAYLOADSTATE_LOADED; + this._texture = this._getFromCache(this.url, this._noMipmap); + if (!this._texture) { + this.loadTexture(); + } + }; + /** + * Get the texture reflection matrix used to rotate/transform the reflection. + * @returns the reflection matrix + */ + HDRCubeTexture.prototype.getReflectionTextureMatrix = function () { + return this._textureMatrix; + }; + /** + * Set the texture reflection matrix used to rotate/transform the reflection. + * @param value Define the reflection matrix to set + */ + HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) { + var _this = this; + this._textureMatrix = value; + if (value.updateFlag === this._textureMatrix.updateFlag) { + return; + } + if (value.isIdentity() !== this._textureMatrix.isIdentity()) { + this.getScene().markAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_5__["Constants"].MATERIAL_TextureDirtyFlag, function (mat) { return mat.getActiveTextures().indexOf(_this) !== -1; }); + } + }; + /** + * Parses a JSON representation of an HDR Texture in order to create the texture + * @param parsedTexture Define the JSON representation + * @param scene Define the scene the texture should be created in + * @param rootUrl Define the root url in case we need to load relative dependencies + * @returns the newly created texture after parsing + */ + HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) { + var texture = null; + if (parsedTexture.name && !parsedTexture.isRenderTarget) { + texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace); + texture.name = parsedTexture.name; + texture.hasAlpha = parsedTexture.hasAlpha; + texture.level = parsedTexture.level; + texture.coordinatesMode = parsedTexture.coordinatesMode; + texture.isBlocking = parsedTexture.isBlocking; + } + if (texture) { + if (parsedTexture.boundingBoxPosition) { + texture.boundingBoxPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].FromArray(parsedTexture.boundingBoxPosition); + } + if (parsedTexture.boundingBoxSize) { + texture.boundingBoxSize = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].FromArray(parsedTexture.boundingBoxSize); + } + if (parsedTexture.rotationY) { + texture.rotationY = parsedTexture.rotationY; + } + } + return texture; + }; + HDRCubeTexture.prototype.serialize = function () { + if (!this.name) { + return null; + } + var serializationObject = {}; + serializationObject.name = this.name; + serializationObject.hasAlpha = this.hasAlpha; + serializationObject.isCube = true; + serializationObject.level = this.level; + serializationObject.size = this._size; + serializationObject.coordinatesMode = this.coordinatesMode; + serializationObject.useInGammaSpace = this.gammaSpace; + serializationObject.generateHarmonics = this._generateHarmonics; + serializationObject.customType = "BABYLON.HDRCubeTexture"; + serializationObject.noMipmap = this._noMipmap; + serializationObject.isBlocking = this._isBlocking; + serializationObject.rotationY = this._rotationY; + return serializationObject; + }; + HDRCubeTexture._facesMapping = [ + "right", + "left", + "up", + "down", + "front", + "back" + ]; + return HDRCubeTexture; +}(_Materials_Textures_baseTexture__WEBPACK_IMPORTED_MODULE_3__["BaseTexture"])); + +_Misc_typeStore__WEBPACK_IMPORTED_MODULE_8__["_TypeStore"].RegisteredTypes["BABYLON.HDRCubeTexture"] = HDRCubeTexture; + + +/***/ }), + +/***/ "./Materials/Textures/htmlElementTexture.ts": +/*!**************************************************!*\ + !*** ./Materials/Textures/htmlElementTexture.ts ***! + \**************************************************/ +/*! exports provided: HtmlElementTexture */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HtmlElementTexture", function() { return HtmlElementTexture; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Materials_Textures_baseTexture__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Materials/Textures/baseTexture */ "./Materials/Textures/baseTexture.ts"); +/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Engines/constants */ "./Engines/constants.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); + + + + +/** + * This represents the smallest workload to use an already existing element (Canvas or Video) as a texture. + * To be as efficient as possible depending on your constraints nothing aside the first upload + * is automatically managed. + * It is a cheap VideoTexture or DynamicTexture if you prefer to keep full control of the elements + * in your application. + * + * As the update is not automatic, you need to call them manually. + */ +var HtmlElementTexture = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](HtmlElementTexture, _super); + /** + * Instantiates a HtmlElementTexture from the following parameters. + * + * @param name Defines the name of the texture + * @param element Defines the video or canvas the texture is filled with + * @param options Defines the other none mandatory texture creation options + */ + function HtmlElementTexture(name, element, options) { + var _this = _super.call(this, options.scene) || this; + if (!element || (!options.engine && !options.scene)) { + return _this; + } + options = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, HtmlElementTexture.DefaultOptions, options); + _this._engine = options.engine || options.scene.getEngine(); + _this._generateMipMaps = options.generateMipMaps; + _this._samplingMode = options.samplingMode; + _this._textureMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"].Identity(); + _this.name = name; + _this.element = element; + _this._isVideo = (element instanceof HTMLVideoElement); + _this.anisotropicFilteringLevel = 1; + _this._createInternalTexture(); + return _this; + } + HtmlElementTexture.prototype._createInternalTexture = function () { + var width = 0; + var height = 0; + if (this._isVideo) { + width = this.element.videoWidth; + height = this.element.videoHeight; + } + else { + width = this.element.width; + height = this.element.height; + } + this._texture = this._engine.createDynamicTexture(width, height, this._generateMipMaps, this._samplingMode); + this.update(); + }; + /** + * Returns the texture matrix used in most of the material. + */ + HtmlElementTexture.prototype.getTextureMatrix = function () { + return this._textureMatrix; + }; + /** + * Updates the content of the texture. + * @param invertY Defines wether the texture should be inverted on Y (false by default on video and true on canvas) + */ + HtmlElementTexture.prototype.update = function (invertY) { + if (invertY === void 0) { invertY = null; } + if (this._texture == null) { + return; + } + if (this._isVideo) { + var videoElement = this.element; + if (videoElement.readyState < videoElement.HAVE_CURRENT_DATA) { + return; + } + this._engine.updateVideoTexture(this._texture, videoElement, invertY === null ? true : invertY); + } + else { + var canvasElement = this.element; + this._engine.updateDynamicTexture(this._texture, canvasElement, invertY === null ? true : invertY, false); + } + }; + HtmlElementTexture.DefaultOptions = { + generateMipMaps: false, + samplingMode: _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTURE_BILINEAR_SAMPLINGMODE, + engine: null, + scene: null + }; + return HtmlElementTexture; +}(_Materials_Textures_baseTexture__WEBPACK_IMPORTED_MODULE_1__["BaseTexture"])); + + + +/***/ }), + +/***/ "./Materials/Textures/index.ts": +/*!*************************************!*\ + !*** ./Materials/Textures/index.ts ***! + \*************************************/ +/*! exports provided: BaseTexture, CubeTexture, DynamicTexture, EquiRectangularCubeTexture, HDRCubeTexture, InternalTexture, MirrorTexture, MultiRenderTarget, RawTexture, RenderTargetTexture, Texture, ColorGradingTexture, RawCubeTexture, RawTexture3D, RefractionTexture, VideoTexture, HtmlElementTexture, _DDSTextureLoader, _ENVTextureLoader, _KTXTextureLoader, _TGATextureLoader, CustomProceduralTexture, NoiseProceduralTexture, ProceduralTexture, ProceduralTextureSceneComponent */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _baseTexture__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./baseTexture */ "./Materials/Textures/baseTexture.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BaseTexture", function() { return _baseTexture__WEBPACK_IMPORTED_MODULE_0__["BaseTexture"]; }); + +/* harmony import */ var _colorGradingTexture__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./colorGradingTexture */ "./Materials/Textures/colorGradingTexture.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ColorGradingTexture", function() { return _colorGradingTexture__WEBPACK_IMPORTED_MODULE_1__["ColorGradingTexture"]; }); + +/* harmony import */ var _cubeTexture__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./cubeTexture */ "./Materials/Textures/cubeTexture.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CubeTexture", function() { return _cubeTexture__WEBPACK_IMPORTED_MODULE_2__["CubeTexture"]; }); + +/* harmony import */ var _dynamicTexture__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./dynamicTexture */ "./Materials/Textures/dynamicTexture.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DynamicTexture", function() { return _dynamicTexture__WEBPACK_IMPORTED_MODULE_3__["DynamicTexture"]; }); + +/* harmony import */ var _equiRectangularCubeTexture__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./equiRectangularCubeTexture */ "./Materials/Textures/equiRectangularCubeTexture.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EquiRectangularCubeTexture", function() { return _equiRectangularCubeTexture__WEBPACK_IMPORTED_MODULE_4__["EquiRectangularCubeTexture"]; }); + +/* harmony import */ var _hdrCubeTexture__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./hdrCubeTexture */ "./Materials/Textures/hdrCubeTexture.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HDRCubeTexture", function() { return _hdrCubeTexture__WEBPACK_IMPORTED_MODULE_5__["HDRCubeTexture"]; }); + +/* harmony import */ var _internalTexture__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./internalTexture */ "./Materials/Textures/internalTexture.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InternalTexture", function() { return _internalTexture__WEBPACK_IMPORTED_MODULE_6__["InternalTexture"]; }); + +/* harmony import */ var _Loaders_index__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Loaders/index */ "./Materials/Textures/Loaders/index.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_DDSTextureLoader", function() { return _Loaders_index__WEBPACK_IMPORTED_MODULE_7__["_DDSTextureLoader"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_ENVTextureLoader", function() { return _Loaders_index__WEBPACK_IMPORTED_MODULE_7__["_ENVTextureLoader"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_KTXTextureLoader", function() { return _Loaders_index__WEBPACK_IMPORTED_MODULE_7__["_KTXTextureLoader"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_TGATextureLoader", function() { return _Loaders_index__WEBPACK_IMPORTED_MODULE_7__["_TGATextureLoader"]; }); + +/* harmony import */ var _mirrorTexture__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./mirrorTexture */ "./Materials/Textures/mirrorTexture.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MirrorTexture", function() { return _mirrorTexture__WEBPACK_IMPORTED_MODULE_8__["MirrorTexture"]; }); + +/* harmony import */ var _multiRenderTarget__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./multiRenderTarget */ "./Materials/Textures/multiRenderTarget.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MultiRenderTarget", function() { return _multiRenderTarget__WEBPACK_IMPORTED_MODULE_9__["MultiRenderTarget"]; }); + +/* harmony import */ var _Procedurals_index__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./Procedurals/index */ "./Materials/Textures/Procedurals/index.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CustomProceduralTexture", function() { return _Procedurals_index__WEBPACK_IMPORTED_MODULE_10__["CustomProceduralTexture"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NoiseProceduralTexture", function() { return _Procedurals_index__WEBPACK_IMPORTED_MODULE_10__["NoiseProceduralTexture"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ProceduralTexture", function() { return _Procedurals_index__WEBPACK_IMPORTED_MODULE_10__["ProceduralTexture"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ProceduralTextureSceneComponent", function() { return _Procedurals_index__WEBPACK_IMPORTED_MODULE_10__["ProceduralTextureSceneComponent"]; }); + +/* harmony import */ var _rawCubeTexture__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./rawCubeTexture */ "./Materials/Textures/rawCubeTexture.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RawCubeTexture", function() { return _rawCubeTexture__WEBPACK_IMPORTED_MODULE_11__["RawCubeTexture"]; }); + +/* harmony import */ var _rawTexture__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./rawTexture */ "./Materials/Textures/rawTexture.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RawTexture", function() { return _rawTexture__WEBPACK_IMPORTED_MODULE_12__["RawTexture"]; }); + +/* harmony import */ var _rawTexture3D__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./rawTexture3D */ "./Materials/Textures/rawTexture3D.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RawTexture3D", function() { return _rawTexture3D__WEBPACK_IMPORTED_MODULE_13__["RawTexture3D"]; }); + +/* harmony import */ var _refractionTexture__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./refractionTexture */ "./Materials/Textures/refractionTexture.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RefractionTexture", function() { return _refractionTexture__WEBPACK_IMPORTED_MODULE_14__["RefractionTexture"]; }); + +/* harmony import */ var _renderTargetTexture__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./renderTargetTexture */ "./Materials/Textures/renderTargetTexture.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RenderTargetTexture", function() { return _renderTargetTexture__WEBPACK_IMPORTED_MODULE_15__["RenderTargetTexture"]; }); + +/* harmony import */ var _texture__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./texture */ "./Materials/Textures/texture.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Texture", function() { return _texture__WEBPACK_IMPORTED_MODULE_16__["Texture"]; }); + +/* harmony import */ var _videoTexture__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./videoTexture */ "./Materials/Textures/videoTexture.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VideoTexture", function() { return _videoTexture__WEBPACK_IMPORTED_MODULE_17__["VideoTexture"]; }); + +/* harmony import */ var _htmlElementTexture__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./htmlElementTexture */ "./Materials/Textures/htmlElementTexture.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HtmlElementTexture", function() { return _htmlElementTexture__WEBPACK_IMPORTED_MODULE_18__["HtmlElementTexture"]; }); + + + + + + + + + + + + + + + + + + + + + + +/***/ }), + +/***/ "./Materials/Textures/internalTexture.ts": +/*!***********************************************!*\ + !*** ./Materials/Textures/internalTexture.ts ***! + \***********************************************/ +/*! exports provided: InternalTexture */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InternalTexture", function() { return InternalTexture; }); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _Materials_Textures_renderTargetCreationOptions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Materials/Textures/renderTargetCreationOptions */ "./Materials/Textures/renderTargetCreationOptions.ts"); +/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Engines/constants */ "./Engines/constants.ts"); +/* harmony import */ var _Misc_devTools__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Misc/devTools */ "./Misc/devTools.ts"); + + + + +/** + * Class used to store data associated with WebGL texture data for the engine + * This class should not be used directly + */ +var InternalTexture = /** @class */ (function () { + /** + * Creates a new InternalTexture + * @param engine defines the engine to use + * @param dataSource defines the type of data that will be used + * @param delayAllocation if the texture allocation should be delayed (default: false) + */ + function InternalTexture(engine, dataSource, delayAllocation) { + if (delayAllocation === void 0) { delayAllocation = false; } + /** + * Defines if the texture is ready + */ + this.isReady = false; + /** + * Defines if the texture is a cube texture + */ + this.isCube = false; + /** + * Defines if the texture contains 3D data + */ + this.is3D = false; + /** + * Defines if the texture contains multiview data + */ + this.isMultiview = false; + /** + * Gets the URL used to load this texture + */ + this.url = ""; + /** + * Gets the sampling mode of the texture + */ + this.samplingMode = -1; + /** + * Gets a boolean indicating if the texture needs mipmaps generation + */ + this.generateMipMaps = false; + /** + * Gets the number of samples used by the texture (WebGL2+ only) + */ + this.samples = 0; + /** + * Gets the type of the texture (int, float...) + */ + this.type = -1; + /** + * Gets the format of the texture (RGB, RGBA...) + */ + this.format = -1; + /** + * Observable called when the texture is loaded + */ + this.onLoadedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](); + /** + * Gets the width of the texture + */ + this.width = 0; + /** + * Gets the height of the texture + */ + this.height = 0; + /** + * Gets the depth of the texture + */ + this.depth = 0; + /** + * Gets the initial width of the texture (It could be rescaled if the current system does not support non power of two textures) + */ + this.baseWidth = 0; + /** + * Gets the initial height of the texture (It could be rescaled if the current system does not support non power of two textures) + */ + this.baseHeight = 0; + /** + * Gets the initial depth of the texture (It could be rescaled if the current system does not support non power of two textures) + */ + this.baseDepth = 0; + /** + * Gets a boolean indicating if the texture is inverted on Y axis + */ + this.invertY = false; + // Private + /** @hidden */ + this._invertVScale = false; + /** @hidden */ + this._associatedChannel = -1; + /** @hidden */ + this._dataSource = InternalTexture.DATASOURCE_UNKNOWN; + /** @hidden */ + this._buffer = null; + /** @hidden */ + this._bufferView = null; + /** @hidden */ + this._bufferViewArray = null; + /** @hidden */ + this._bufferViewArrayArray = null; + /** @hidden */ + this._size = 0; + /** @hidden */ + this._extension = ""; + /** @hidden */ + this._files = null; + /** @hidden */ + this._workingCanvas = null; + /** @hidden */ + this._workingContext = null; + /** @hidden */ + this._framebuffer = null; + /** @hidden */ + this._depthStencilBuffer = null; + /** @hidden */ + this._MSAAFramebuffer = null; + /** @hidden */ + this._MSAARenderBuffer = null; + /** @hidden */ + this._attachments = null; + /** @hidden */ + this._cachedCoordinatesMode = null; + /** @hidden */ + this._cachedWrapU = null; + /** @hidden */ + this._cachedWrapV = null; + /** @hidden */ + this._cachedWrapR = null; + /** @hidden */ + this._cachedAnisotropicFilteringLevel = null; + /** @hidden */ + this._isDisabled = false; + /** @hidden */ + this._compression = null; + /** @hidden */ + this._generateStencilBuffer = false; + /** @hidden */ + this._generateDepthBuffer = false; + /** @hidden */ + this._comparisonFunction = 0; + /** @hidden */ + this._sphericalPolynomial = null; + /** @hidden */ + this._lodGenerationScale = 0; + /** @hidden */ + this._lodGenerationOffset = 0; + // Multiview + /** @hidden */ + this._colorTextureArray = null; + /** @hidden */ + this._depthStencilTextureArray = null; + // The following three fields helps sharing generated fixed LODs for texture filtering + // In environment not supporting the textureLOD extension like EDGE. They are for internal use only. + // They are at the level of the gl texture to benefit from the cache. + /** @hidden */ + this._lodTextureHigh = null; + /** @hidden */ + this._lodTextureMid = null; + /** @hidden */ + this._lodTextureLow = null; + /** @hidden */ + this._isRGBD = false; + /** @hidden */ + this._linearSpecularLOD = false; + /** @hidden */ + this._irradianceTexture = null; + /** @hidden */ + this._webGLTexture = null; + /** @hidden */ + this._references = 1; + this._engine = engine; + this._dataSource = dataSource; + if (!delayAllocation) { + this._webGLTexture = engine._createTexture(); + } + } + /** + * Gets the Engine the texture belongs to. + * @returns The babylon engine + */ + InternalTexture.prototype.getEngine = function () { + return this._engine; + }; + Object.defineProperty(InternalTexture.prototype, "dataSource", { + /** + * Gets the data source type of the texture (can be one of the InternalTexture.DATASOURCE_XXXX) + */ + get: function () { + return this._dataSource; + }, + enumerable: true, + configurable: true + }); + /** + * Increments the number of references (ie. the number of Texture that point to it) + */ + InternalTexture.prototype.incrementReferences = function () { + this._references++; + }; + /** + * Change the size of the texture (not the size of the content) + * @param width defines the new width + * @param height defines the new height + * @param depth defines the new depth (1 by default) + */ + InternalTexture.prototype.updateSize = function (width, height, depth) { + if (depth === void 0) { depth = 1; } + this.width = width; + this.height = height; + this.depth = depth; + this.baseWidth = width; + this.baseHeight = height; + this.baseDepth = depth; + this._size = width * height * depth; + }; + /** @hidden */ + InternalTexture.prototype._rebuild = function () { + var _this = this; + var proxy; + this.isReady = false; + this._cachedCoordinatesMode = null; + this._cachedWrapU = null; + this._cachedWrapV = null; + this._cachedAnisotropicFilteringLevel = null; + switch (this._dataSource) { + case InternalTexture.DATASOURCE_TEMP: + return; + case InternalTexture.DATASOURCE_URL: + proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () { + proxy._swapAndDie(_this); + _this.isReady = true; + }, null, this._buffer, undefined, this.format); + return; + case InternalTexture.DATASOURCE_RAW: + proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression); + proxy._swapAndDie(this); + this.isReady = true; + return; + case InternalTexture.DATASOURCE_RAW3D: + proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression); + proxy._swapAndDie(this); + this.isReady = true; + return; + case InternalTexture.DATASOURCE_DYNAMIC: + proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode); + proxy._swapAndDie(this); + this._engine.updateDynamicTexture(this, this._engine.getRenderingCanvas(), this.invertY, undefined, undefined, true); + // The engine will make sure to update content so no need to flag it as isReady = true + return; + case InternalTexture.DATASOURCE_RENDERTARGET: + var options = new _Materials_Textures_renderTargetCreationOptions__WEBPACK_IMPORTED_MODULE_1__["RenderTargetCreationOptions"](); + options.generateDepthBuffer = this._generateDepthBuffer; + options.generateMipMaps = this.generateMipMaps; + options.generateStencilBuffer = this._generateStencilBuffer; + options.samplingMode = this.samplingMode; + options.type = this.type; + if (this.isCube) { + proxy = this._engine.createRenderTargetCubeTexture(this.width, options); + } + else { + var size = { + width: this.width, + height: this.height + }; + proxy = this._engine.createRenderTargetTexture(size, options); + } + proxy._swapAndDie(this); + this.isReady = true; + return; + case InternalTexture.DATASOURCE_DEPTHTEXTURE: + var depthTextureOptions = { + bilinearFiltering: this.samplingMode !== _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTURE_BILINEAR_SAMPLINGMODE, + comparisonFunction: this._comparisonFunction, + generateStencil: this._generateStencilBuffer, + isCube: this.isCube + }; + proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions); + proxy._swapAndDie(this); + this.isReady = true; + return; + case InternalTexture.DATASOURCE_CUBE: + proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () { + proxy._swapAndDie(_this); + _this.isReady = true; + }, null, this.format, this._extension); + return; + case InternalTexture.DATASOURCE_CUBERAW: + proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression); + proxy._swapAndDie(this); + this.isReady = true; + return; + case InternalTexture.DATASOURCE_CUBERAW_RGBD: + proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression); + InternalTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () { + proxy._swapAndDie(_this); + _this.isReady = true; + }); + return; + case InternalTexture.DATASOURCE_CUBEPREFILTERED: + proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) { + if (proxy) { + proxy._swapAndDie(_this); + } + _this.isReady = true; + }, null, this.format, this._extension); + proxy._sphericalPolynomial = this._sphericalPolynomial; + return; + } + }; + /** @hidden */ + InternalTexture.prototype._swapAndDie = function (target) { + target._webGLTexture = this._webGLTexture; + target._isRGBD = this._isRGBD; + if (this._framebuffer) { + target._framebuffer = this._framebuffer; + } + if (this._depthStencilBuffer) { + target._depthStencilBuffer = this._depthStencilBuffer; + } + if (this._lodTextureHigh) { + if (target._lodTextureHigh) { + target._lodTextureHigh.dispose(); + } + target._lodTextureHigh = this._lodTextureHigh; + } + if (this._lodTextureMid) { + if (target._lodTextureMid) { + target._lodTextureMid.dispose(); + } + target._lodTextureMid = this._lodTextureMid; + } + if (this._lodTextureLow) { + if (target._lodTextureLow) { + target._lodTextureLow.dispose(); + } + target._lodTextureLow = this._lodTextureLow; + } + if (this._irradianceTexture) { + if (target._irradianceTexture) { + target._irradianceTexture.dispose(); + } + target._irradianceTexture = this._irradianceTexture; + } + var cache = this._engine.getLoadedTexturesCache(); + var index = cache.indexOf(this); + if (index !== -1) { + cache.splice(index, 1); + } + }; + /** + * Dispose the current allocated resources + */ + InternalTexture.prototype.dispose = function () { + if (!this._webGLTexture) { + return; + } + this._references--; + if (this._references === 0) { + this._engine._releaseTexture(this); + this._webGLTexture = null; + } + }; + /** @hidden */ + InternalTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) { + throw _Misc_devTools__WEBPACK_IMPORTED_MODULE_3__["_DevTools"].WarnImport("environmentTextureTools"); + }; + /** + * The source of the texture data is unknown + */ + InternalTexture.DATASOURCE_UNKNOWN = 0; + /** + * Texture data comes from an URL + */ + InternalTexture.DATASOURCE_URL = 1; + /** + * Texture data is only used for temporary storage + */ + InternalTexture.DATASOURCE_TEMP = 2; + /** + * Texture data comes from raw data (ArrayBuffer) + */ + InternalTexture.DATASOURCE_RAW = 3; + /** + * Texture content is dynamic (video or dynamic texture) + */ + InternalTexture.DATASOURCE_DYNAMIC = 4; + /** + * Texture content is generated by rendering to it + */ + InternalTexture.DATASOURCE_RENDERTARGET = 5; + /** + * Texture content is part of a multi render target process + */ + InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6; + /** + * Texture data comes from a cube data file + */ + InternalTexture.DATASOURCE_CUBE = 7; + /** + * Texture data comes from a raw cube data + */ + InternalTexture.DATASOURCE_CUBERAW = 8; + /** + * Texture data come from a prefiltered cube data file + */ + InternalTexture.DATASOURCE_CUBEPREFILTERED = 9; + /** + * Texture content is raw 3D data + */ + InternalTexture.DATASOURCE_RAW3D = 10; + /** + * Texture content is a depth texture + */ + InternalTexture.DATASOURCE_DEPTHTEXTURE = 11; + /** + * Texture data comes from a raw cube data encoded with RGBD + */ + InternalTexture.DATASOURCE_CUBERAW_RGBD = 12; + return InternalTexture; +}()); + + + +/***/ }), + +/***/ "./Materials/Textures/mirrorTexture.ts": +/*!*********************************************!*\ + !*** ./Materials/Textures/mirrorTexture.ts ***! + \*********************************************/ +/*! exports provided: MirrorTexture */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MirrorTexture", function() { return MirrorTexture; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Materials/Textures/texture */ "./Materials/Textures/texture.ts"); +/* harmony import */ var _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Materials/Textures/renderTargetTexture */ "./Materials/Textures/renderTargetTexture.ts"); +/* harmony import */ var _PostProcesses_blurPostProcess__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../PostProcesses/blurPostProcess */ "./PostProcesses/blurPostProcess.ts"); +/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Engines/constants */ "./Engines/constants.ts"); + + + + + + +/** + * Mirror texture can be used to simulate the view from a mirror in a scene. + * It will dynamically be rendered every frame to adapt to the camera point of view. + * You can then easily use it as a reflectionTexture on a flat surface. + * In case the surface is not a plane, please consider relying on reflection probes. + * @see https://doc.babylonjs.com/how_to/reflect#mirrors + */ +var MirrorTexture = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](MirrorTexture, _super); + /** + * Instantiates a Mirror Texture. + * Mirror texture can be used to simulate the view from a mirror in a scene. + * It will dynamically be rendered every frame to adapt to the camera point of view. + * You can then easily use it as a reflectionTexture on a flat surface. + * In case the surface is not a plane, please consider relying on reflection probes. + * @see https://doc.babylonjs.com/how_to/reflect#mirrors + * @param name + * @param size + * @param scene + * @param generateMipMaps + * @param type + * @param samplingMode + * @param generateDepthBuffer + */ + function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) { + if (type === void 0) { type = _Engines_constants__WEBPACK_IMPORTED_MODULE_5__["Constants"].TEXTURETYPE_UNSIGNED_INT; } + if (samplingMode === void 0) { samplingMode = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_2__["Texture"].BILINEAR_SAMPLINGMODE; } + if (generateDepthBuffer === void 0) { generateDepthBuffer = true; } + var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this; + _this.scene = scene; + /** + * Define the reflection plane we want to use. The mirrorPlane is usually set to the constructed reflector. + * It is possible to directly set the mirrorPlane by directly using a Plane(a, b, c, d) where a, b and c give the plane normal vector (a, b, c) and d is a scalar displacement from the mirrorPlane to the origin. However in all but the very simplest of situations it is more straight forward to set it to the reflector as stated in the doc. + * @see https://doc.babylonjs.com/how_to/reflect#mirrors + */ + _this.mirrorPlane = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Plane"](0, 1, 0, 1); + _this._transformMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Zero(); + _this._mirrorMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Zero(); + _this._adaptiveBlurKernel = 0; + _this._blurKernelX = 0; + _this._blurKernelY = 0; + _this._blurRatio = 1.0; + _this.ignoreCameraViewport = true; + _this._updateGammaSpace(); + _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () { + _this._updateGammaSpace; + }); + _this.onBeforeRenderObservable.add(function () { + _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix); + _this._savedViewMatrix = scene.getViewMatrix(); + _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix); + scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix()); + scene.clipPlane = _this.mirrorPlane; + scene.getEngine().cullBackFaces = false; + scene._mirroredCameraPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix); + }); + _this.onAfterRenderObservable.add(function () { + scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix()); + scene.getEngine().cullBackFaces = true; + scene._mirroredCameraPosition = null; + scene.clipPlane = null; + }); + return _this; + } + Object.defineProperty(MirrorTexture.prototype, "blurRatio", { + get: function () { + return this._blurRatio; + }, + /** + * Define the blur ratio used to blur the reflection if needed. + */ + set: function (value) { + if (this._blurRatio === value) { + return; + } + this._blurRatio = value; + this._preparePostProcesses(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", { + /** + * Define the adaptive blur kernel used to blur the reflection if needed. + * This will autocompute the closest best match for the `blurKernel` + */ + set: function (value) { + this._adaptiveBlurKernel = value; + this._autoComputeBlurKernel(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(MirrorTexture.prototype, "blurKernel", { + /** + * Define the blur kernel used to blur the reflection if needed. + * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you. + */ + set: function (value) { + this.blurKernelX = value; + this.blurKernelY = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(MirrorTexture.prototype, "blurKernelX", { + get: function () { + return this._blurKernelX; + }, + /** + * Define the blur kernel on the X Axis used to blur the reflection if needed. + * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you. + */ + set: function (value) { + if (this._blurKernelX === value) { + return; + } + this._blurKernelX = value; + this._preparePostProcesses(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(MirrorTexture.prototype, "blurKernelY", { + get: function () { + return this._blurKernelY; + }, + /** + * Define the blur kernel on the Y Axis used to blur the reflection if needed. + * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you. + */ + set: function (value) { + if (this._blurKernelY === value) { + return; + } + this._blurKernelY = value; + this._preparePostProcesses(); + }, + enumerable: true, + configurable: true + }); + MirrorTexture.prototype._autoComputeBlurKernel = function () { + var engine = this.getScene().getEngine(); + var dw = this.getRenderWidth() / engine.getRenderWidth(); + var dh = this.getRenderHeight() / engine.getRenderHeight(); + this.blurKernelX = this._adaptiveBlurKernel * dw; + this.blurKernelY = this._adaptiveBlurKernel * dh; + }; + MirrorTexture.prototype._onRatioRescale = function () { + if (this._sizeRatio) { + this.resize(this._initialSizeParameter); + if (!this._adaptiveBlurKernel) { + this._preparePostProcesses(); + } + } + if (this._adaptiveBlurKernel) { + this._autoComputeBlurKernel(); + } + }; + MirrorTexture.prototype._updateGammaSpace = function () { + this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess; + }; + MirrorTexture.prototype._preparePostProcesses = function () { + this.clearPostProcesses(true); + if (this._blurKernelX && this._blurKernelY) { + var engine = this.getScene().getEngine(); + var textureType = engine.getCaps().textureFloatRender ? _Engines_constants__WEBPACK_IMPORTED_MODULE_5__["Constants"].TEXTURETYPE_FLOAT : _Engines_constants__WEBPACK_IMPORTED_MODULE_5__["Constants"].TEXTURETYPE_HALF_FLOAT; + this._blurX = new _PostProcesses_blurPostProcess__WEBPACK_IMPORTED_MODULE_4__["BlurPostProcess"]("horizontal blur", new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector2"](1.0, 0), this._blurKernelX, this._blurRatio, null, _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_2__["Texture"].BILINEAR_SAMPLINGMODE, engine, false, textureType); + this._blurX.autoClear = false; + if (this._blurRatio === 1 && this.samples < 2 && this._texture) { + this._blurX.inputTexture = this._texture; + } + else { + this._blurX.alwaysForcePOT = true; + } + this._blurY = new _PostProcesses_blurPostProcess__WEBPACK_IMPORTED_MODULE_4__["BlurPostProcess"]("vertical blur", new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector2"](0, 1.0), this._blurKernelY, this._blurRatio, null, _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_2__["Texture"].BILINEAR_SAMPLINGMODE, engine, false, textureType); + this._blurY.autoClear = false; + this._blurY.alwaysForcePOT = this._blurRatio !== 1; + this.addPostProcess(this._blurX); + this.addPostProcess(this._blurY); + } + else { + if (this._blurY) { + this.removePostProcess(this._blurY); + this._blurY.dispose(); + this._blurY = null; + } + if (this._blurX) { + this.removePostProcess(this._blurX); + this._blurX.dispose(); + this._blurX = null; + } + } + }; + /** + * Clone the mirror texture. + * @returns the cloned texture + */ + MirrorTexture.prototype.clone = function () { + var scene = this.getScene(); + if (!scene) { + return this; + } + var textureSize = this.getSize(); + var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer); + // Base texture + newTexture.hasAlpha = this.hasAlpha; + newTexture.level = this.level; + // Mirror Texture + newTexture.mirrorPlane = this.mirrorPlane.clone(); + if (this.renderList) { + newTexture.renderList = this.renderList.slice(0); + } + return newTexture; + }; + /** + * Serialize the texture to a JSON representation you could use in Parse later on + * @returns the serialized JSON representation + */ + MirrorTexture.prototype.serialize = function () { + if (!this.name) { + return null; + } + var serializationObject = _super.prototype.serialize.call(this); + serializationObject.mirrorPlane = this.mirrorPlane.asArray(); + return serializationObject; + }; + /** + * Dispose the texture and release its associated resources. + */ + MirrorTexture.prototype.dispose = function () { + _super.prototype.dispose.call(this); + this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver); + }; + return MirrorTexture; +}(_Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_3__["RenderTargetTexture"])); + +_Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_2__["Texture"]._CreateMirror = function (name, renderTargetSize, scene, generateMipMaps) { + return new MirrorTexture(name, renderTargetSize, scene, generateMipMaps); +}; + + +/***/ }), + +/***/ "./Materials/Textures/multiRenderTarget.ts": +/*!*************************************************!*\ + !*** ./Materials/Textures/multiRenderTarget.ts ***! + \*************************************************/ +/*! exports provided: MultiRenderTarget */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MultiRenderTarget", function() { return MultiRenderTarget; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Materials/Textures/texture */ "./Materials/Textures/texture.ts"); +/* harmony import */ var _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Materials/Textures/renderTargetTexture */ "./Materials/Textures/renderTargetTexture.ts"); +/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Engines/constants */ "./Engines/constants.ts"); +/* harmony import */ var _Engines_Extensions_engine_multiRender__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Engines/Extensions/engine.multiRender */ "./Engines/Extensions/engine.multiRender.ts"); + + + + + +/** + * A multi render target, like a render target provides the ability to render to a texture. + * Unlike the render target, it can render to several draw buffers in one draw. + * This is specially interesting in deferred rendering or for any effects requiring more than + * just one color from a single pass. + */ +var MultiRenderTarget = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](MultiRenderTarget, _super); + /** + * Instantiate a new multi render target texture. + * A multi render target, like a render target provides the ability to render to a texture. + * Unlike the render target, it can render to several draw buffers in one draw. + * This is specially interesting in deferred rendering or for any effects requiring more than + * just one color from a single pass. + * @param name Define the name of the texture + * @param size Define the size of the buffers to render to + * @param count Define the number of target we are rendering into + * @param scene Define the scene the texture belongs to + * @param options Define the options used to create the multi render target + */ + function MultiRenderTarget(name, size, count, scene, options) { + var _this = this; + var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false; + var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false; + var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio; + _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this; + _this._engine = scene.getEngine(); + if (!_this.isSupported) { + _this.dispose(); + return; + } + var types = []; + var samplingModes = []; + for (var i = 0; i < count; i++) { + if (options && options.types && options.types[i] !== undefined) { + types.push(options.types[i]); + } + else { + types.push(options && options.defaultType ? options.defaultType : _Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].TEXTURETYPE_UNSIGNED_INT); + } + if (options && options.samplingModes && options.samplingModes[i] !== undefined) { + samplingModes.push(options.samplingModes[i]); + } + else { + samplingModes.push(_Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_1__["Texture"].BILINEAR_SAMPLINGMODE); + } + } + var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer; + var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer; + _this._size = size; + _this._multiRenderTargetOptions = { + samplingModes: samplingModes, + generateMipMaps: generateMipMaps, + generateDepthBuffer: generateDepthBuffer, + generateStencilBuffer: generateStencilBuffer, + generateDepthTexture: generateDepthTexture, + types: types, + textureCount: count + }; + _this._createInternalTextures(); + _this._createTextures(); + return _this; + } + Object.defineProperty(MultiRenderTarget.prototype, "isSupported", { + /** + * Get if draw buffers are currently supported by the used hardware and browser. + */ + get: function () { + return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(MultiRenderTarget.prototype, "textures", { + /** + * Get the list of textures generated by the multi render target. + */ + get: function () { + return this._textures; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", { + /** + * Get the depth texture generated by the multi render target if options.generateDepthTexture has been set + */ + get: function () { + return this._textures[this._textures.length - 1]; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(MultiRenderTarget.prototype, "wrapU", { + /** + * Set the wrapping mode on U of all the textures we are rendering to. + * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE) + */ + set: function (wrap) { + if (this._textures) { + for (var i = 0; i < this._textures.length; i++) { + this._textures[i].wrapU = wrap; + } + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(MultiRenderTarget.prototype, "wrapV", { + /** + * Set the wrapping mode on V of all the textures we are rendering to. + * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE) + */ + set: function (wrap) { + if (this._textures) { + for (var i = 0; i < this._textures.length; i++) { + this._textures[i].wrapV = wrap; + } + } + }, + enumerable: true, + configurable: true + }); + /** @hidden */ + MultiRenderTarget.prototype._rebuild = function () { + this.releaseInternalTextures(); + this._createInternalTextures(); + for (var i = 0; i < this._internalTextures.length; i++) { + var texture = this._textures[i]; + texture._texture = this._internalTextures[i]; + } + // Keeps references to frame buffer and stencil/depth buffer + this._texture = this._internalTextures[0]; + }; + MultiRenderTarget.prototype._createInternalTextures = function () { + this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions); + }; + MultiRenderTarget.prototype._createTextures = function () { + this._textures = []; + for (var i = 0; i < this._internalTextures.length; i++) { + var texture = new _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_1__["Texture"](null, this.getScene()); + texture._texture = this._internalTextures[i]; + this._textures.push(texture); + } + // Keeps references to frame buffer and stencil/depth buffer + this._texture = this._internalTextures[0]; + }; + Object.defineProperty(MultiRenderTarget.prototype, "samples", { + /** + * Define the number of samples used if MSAA is enabled. + */ + get: function () { + return this._samples; + }, + set: function (value) { + if (this._samples === value) { + return; + } + this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value); + }, + enumerable: true, + configurable: true + }); + /** + * Resize all the textures in the multi render target. + * Be carrefull as it will recreate all the data in the new texture. + * @param size Define the new size + */ + MultiRenderTarget.prototype.resize = function (size) { + this.releaseInternalTextures(); + this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions); + this._createInternalTextures(); + }; + MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) { + var _this = this; + engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () { + _this.onAfterRenderObservable.notifyObservers(faceIndex); + }); + }; + /** + * Dispose the render targets and their associated resources + */ + MultiRenderTarget.prototype.dispose = function () { + this.releaseInternalTextures(); + _super.prototype.dispose.call(this); + }; + /** + * Release all the underlying texture used as draw buffers. + */ + MultiRenderTarget.prototype.releaseInternalTextures = function () { + if (!this._internalTextures) { + return; + } + for (var i = this._internalTextures.length - 1; i >= 0; i--) { + if (this._internalTextures[i] !== undefined) { + this._internalTextures[i].dispose(); + this._internalTextures.splice(i, 1); + } + } + }; + return MultiRenderTarget; +}(_Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_2__["RenderTargetTexture"])); + + + +/***/ }), + +/***/ "./Materials/Textures/rawCubeTexture.ts": +/*!**********************************************!*\ + !*** ./Materials/Textures/rawCubeTexture.ts ***! + \**********************************************/ +/*! exports provided: RawCubeTexture */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RawCubeTexture", function() { return RawCubeTexture; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _Misc_environmentTextureTools__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/environmentTextureTools */ "./Misc/environmentTextureTools.ts"); +/* harmony import */ var _internalTexture__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./internalTexture */ "./Materials/Textures/internalTexture.ts"); +/* harmony import */ var _cubeTexture__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./cubeTexture */ "./Materials/Textures/cubeTexture.ts"); +/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Engines/constants */ "./Engines/constants.ts"); +/* harmony import */ var _Engines_Extensions_engine_rawTexture__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../Engines/Extensions/engine.rawTexture */ "./Engines/Extensions/engine.rawTexture.ts"); + + + + + + + +/** + * Raw cube texture where the raw buffers are passed in + */ +var RawCubeTexture = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](RawCubeTexture, _super); + /** + * Creates a cube texture where the raw buffers are passed in. + * @param scene defines the scene the texture is attached to + * @param data defines the array of data to use to create each face + * @param size defines the size of the textures + * @param format defines the format of the data + * @param type defines the type of the data (like Engine.TEXTURETYPE_UNSIGNED_INT) + * @param generateMipMaps defines if the engine should generate the mip levels + * @param invertY defines if data must be stored with Y axis inverted + * @param samplingMode defines the required sampling mode (like Texture.NEAREST_SAMPLINGMODE) + * @param compression defines the compression used (null by default) + */ + function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) { + if (format === void 0) { format = _Engines_constants__WEBPACK_IMPORTED_MODULE_5__["Constants"].TEXTUREFORMAT_RGBA; } + if (type === void 0) { type = _Engines_constants__WEBPACK_IMPORTED_MODULE_5__["Constants"].TEXTURETYPE_UNSIGNED_INT; } + if (generateMipMaps === void 0) { generateMipMaps = false; } + if (invertY === void 0) { invertY = false; } + if (samplingMode === void 0) { samplingMode = _Engines_constants__WEBPACK_IMPORTED_MODULE_5__["Constants"].TEXTURE_TRILINEAR_SAMPLINGMODE; } + if (compression === void 0) { compression = null; } + var _this = _super.call(this, "", scene) || this; + _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression); + return _this; + } + /** + * Updates the raw cube texture. + * @param data defines the data to store + * @param format defines the data format + * @param type defines the type fo the data (Engine.TEXTURETYPE_UNSIGNED_INT by default) + * @param invertY defines if data must be stored with Y axis inverted + * @param compression defines the compression used (null by default) + * @param level defines which level of the texture to update + */ + RawCubeTexture.prototype.update = function (data, format, type, invertY, compression) { + if (compression === void 0) { compression = null; } + this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression); + }; + /** + * Updates a raw cube texture with RGBD encoded data. + * @param data defines the array of data [mipmap][face] to use to create each face + * @param sphericalPolynomial defines the spherical polynomial for irradiance + * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness + * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness + * @returns a promsie that resolves when the operation is complete + */ + RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) { + if (sphericalPolynomial === void 0) { sphericalPolynomial = null; } + if (lodScale === void 0) { lodScale = 0.8; } + if (lodOffset === void 0) { lodOffset = 0; } + return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset); + }; + /** + * Clones the raw cube texture. + * @return a new cube texture + */ + RawCubeTexture.prototype.clone = function () { + var _this = this; + return _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Clone(function () { + var scene = _this.getScene(); + var internalTexture = _this._texture; + var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression); + if (internalTexture.dataSource === _internalTexture__WEBPACK_IMPORTED_MODULE_3__["InternalTexture"].DATASOURCE_CUBERAW_RGBD) { + texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset); + } + return texture; + }, this); + }; + /** @hidden */ + RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) { + internalTexture._dataSource = _internalTexture__WEBPACK_IMPORTED_MODULE_3__["InternalTexture"].DATASOURCE_CUBERAW_RGBD; + internalTexture._bufferViewArrayArray = data; + internalTexture._lodGenerationScale = lodScale; + internalTexture._lodGenerationOffset = lodOffset; + internalTexture._sphericalPolynomial = sphericalPolynomial; + return _Misc_environmentTextureTools__WEBPACK_IMPORTED_MODULE_2__["EnvironmentTextureTools"].UploadLevelsAsync(internalTexture, data).then(function () { + internalTexture.isReady = true; + }); + }; + return RawCubeTexture; +}(_cubeTexture__WEBPACK_IMPORTED_MODULE_4__["CubeTexture"])); + + + +/***/ }), + +/***/ "./Materials/Textures/rawTexture.ts": +/*!******************************************!*\ + !*** ./Materials/Textures/rawTexture.ts ***! + \******************************************/ +/*! exports provided: RawTexture */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RawTexture", function() { return RawTexture; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _texture__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./texture */ "./Materials/Textures/texture.ts"); +/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Engines/constants */ "./Engines/constants.ts"); +/* harmony import */ var _Engines_Extensions_engine_rawTexture__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Engines/Extensions/engine.rawTexture */ "./Engines/Extensions/engine.rawTexture.ts"); + + + + +/** + * Raw texture can help creating a texture directly from an array of data. + * This can be super useful if you either get the data from an uncompressed source or + * if you wish to create your texture pixel by pixel. + */ +var RawTexture = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](RawTexture, _super); + /** + * Instantiates a new RawTexture. + * Raw texture can help creating a texture directly from an array of data. + * This can be super useful if you either get the data from an uncompressed source or + * if you wish to create your texture pixel by pixel. + * @param data define the array of data to use to create the texture + * @param width define the width of the texture + * @param height define the height of the texture + * @param format define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx) + * @param scene define the scene the texture belongs to + * @param generateMipMaps define whether mip maps should be generated or not + * @param invertY define if the data should be flipped on Y when uploaded to the GPU + * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE) + * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx) + */ + function RawTexture(data, width, height, + /** + * Define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx) + */ + format, scene, generateMipMaps, invertY, samplingMode, type) { + if (generateMipMaps === void 0) { generateMipMaps = true; } + if (invertY === void 0) { invertY = false; } + if (samplingMode === void 0) { samplingMode = _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTURE_TRILINEAR_SAMPLINGMODE; } + if (type === void 0) { type = _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTURETYPE_UNSIGNED_INT; } + var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this; + _this.format = format; + _this._engine = scene.getEngine(); + _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type); + _this.wrapU = _texture__WEBPACK_IMPORTED_MODULE_1__["Texture"].CLAMP_ADDRESSMODE; + _this.wrapV = _texture__WEBPACK_IMPORTED_MODULE_1__["Texture"].CLAMP_ADDRESSMODE; + return _this; + } + /** + * Updates the texture underlying data. + * @param data Define the new data of the texture + */ + RawTexture.prototype.update = function (data) { + this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, null, this._texture.type); + }; + /** + * Creates a luminance texture from some data. + * @param data Define the texture data + * @param width Define the width of the texture + * @param height Define the height of the texture + * @param scene Define the scene the texture belongs to + * @param generateMipMaps Define whether or not to create mip maps for the texture + * @param invertY define if the data should be flipped on Y when uploaded to the GPU + * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE) + * @returns the luminance texture + */ + RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) { + if (generateMipMaps === void 0) { generateMipMaps = true; } + if (invertY === void 0) { invertY = false; } + if (samplingMode === void 0) { samplingMode = _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTURE_TRILINEAR_SAMPLINGMODE; } + return new RawTexture(data, width, height, _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode); + }; + /** + * Creates a luminance alpha texture from some data. + * @param data Define the texture data + * @param width Define the width of the texture + * @param height Define the height of the texture + * @param scene Define the scene the texture belongs to + * @param generateMipMaps Define whether or not to create mip maps for the texture + * @param invertY define if the data should be flipped on Y when uploaded to the GPU + * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE) + * @returns the luminance alpha texture + */ + RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) { + if (generateMipMaps === void 0) { generateMipMaps = true; } + if (invertY === void 0) { invertY = false; } + if (samplingMode === void 0) { samplingMode = _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTURE_TRILINEAR_SAMPLINGMODE; } + return new RawTexture(data, width, height, _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode); + }; + /** + * Creates an alpha texture from some data. + * @param data Define the texture data + * @param width Define the width of the texture + * @param height Define the height of the texture + * @param scene Define the scene the texture belongs to + * @param generateMipMaps Define whether or not to create mip maps for the texture + * @param invertY define if the data should be flipped on Y when uploaded to the GPU + * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE) + * @returns the alpha texture + */ + RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) { + if (generateMipMaps === void 0) { generateMipMaps = true; } + if (invertY === void 0) { invertY = false; } + if (samplingMode === void 0) { samplingMode = _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTURE_TRILINEAR_SAMPLINGMODE; } + return new RawTexture(data, width, height, _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode); + }; + /** + * Creates a RGB texture from some data. + * @param data Define the texture data + * @param width Define the width of the texture + * @param height Define the height of the texture + * @param scene Define the scene the texture belongs to + * @param generateMipMaps Define whether or not to create mip maps for the texture + * @param invertY define if the data should be flipped on Y when uploaded to the GPU + * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE) + * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx) + * @returns the RGB alpha texture + */ + RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) { + if (generateMipMaps === void 0) { generateMipMaps = true; } + if (invertY === void 0) { invertY = false; } + if (samplingMode === void 0) { samplingMode = _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTURE_TRILINEAR_SAMPLINGMODE; } + if (type === void 0) { type = _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTURETYPE_UNSIGNED_INT; } + return new RawTexture(data, width, height, _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type); + }; + /** + * Creates a RGBA texture from some data. + * @param data Define the texture data + * @param width Define the width of the texture + * @param height Define the height of the texture + * @param scene Define the scene the texture belongs to + * @param generateMipMaps Define whether or not to create mip maps for the texture + * @param invertY define if the data should be flipped on Y when uploaded to the GPU + * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE) + * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx) + * @returns the RGBA texture + */ + RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) { + if (generateMipMaps === void 0) { generateMipMaps = true; } + if (invertY === void 0) { invertY = false; } + if (samplingMode === void 0) { samplingMode = _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTURE_TRILINEAR_SAMPLINGMODE; } + if (type === void 0) { type = _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTURETYPE_UNSIGNED_INT; } + return new RawTexture(data, width, height, _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type); + }; + /** + * Creates a R texture from some data. + * @param data Define the texture data + * @param width Define the width of the texture + * @param height Define the height of the texture + * @param scene Define the scene the texture belongs to + * @param generateMipMaps Define whether or not to create mip maps for the texture + * @param invertY define if the data should be flipped on Y when uploaded to the GPU + * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE) + * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx) + * @returns the R texture + */ + RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) { + if (generateMipMaps === void 0) { generateMipMaps = true; } + if (invertY === void 0) { invertY = false; } + if (samplingMode === void 0) { samplingMode = _texture__WEBPACK_IMPORTED_MODULE_1__["Texture"].TRILINEAR_SAMPLINGMODE; } + if (type === void 0) { type = _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTURETYPE_FLOAT; } + return new RawTexture(data, width, height, _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type); + }; + return RawTexture; +}(_texture__WEBPACK_IMPORTED_MODULE_1__["Texture"])); + + + +/***/ }), + +/***/ "./Materials/Textures/rawTexture3D.ts": +/*!********************************************!*\ + !*** ./Materials/Textures/rawTexture3D.ts ***! + \********************************************/ +/*! exports provided: RawTexture3D */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RawTexture3D", function() { return RawTexture3D; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _texture__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./texture */ "./Materials/Textures/texture.ts"); +/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Engines/constants */ "./Engines/constants.ts"); +/* harmony import */ var _Engines_Extensions_engine_rawTexture__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Engines/Extensions/engine.rawTexture */ "./Engines/Extensions/engine.rawTexture.ts"); + + + + +/** + * Class used to store 3D textures containing user data + */ +var RawTexture3D = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](RawTexture3D, _super); + /** + * Create a new RawTexture3D + * @param data defines the data of the texture + * @param width defines the width of the texture + * @param height defines the height of the texture + * @param depth defines the depth of the texture + * @param format defines the texture format to use + * @param scene defines the hosting scene + * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default) + * @param invertY defines if texture must be stored with Y axis inverted + * @param samplingMode defines the sampling mode to use (Texture.TRILINEAR_SAMPLINGMODE by default) + * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...) + */ + function RawTexture3D(data, width, height, depth, + /** Gets or sets the texture format to use */ + format, scene, generateMipMaps, invertY, samplingMode, textureType) { + if (generateMipMaps === void 0) { generateMipMaps = true; } + if (invertY === void 0) { invertY = false; } + if (samplingMode === void 0) { samplingMode = _texture__WEBPACK_IMPORTED_MODULE_1__["Texture"].TRILINEAR_SAMPLINGMODE; } + if (textureType === void 0) { textureType = _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTURETYPE_UNSIGNED_INT; } + var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this; + _this.format = format; + _this._engine = scene.getEngine(); + _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType); + _this.is3D = true; + return _this; + } + /** + * Update the texture with new data + * @param data defines the data to store in the texture + */ + RawTexture3D.prototype.update = function (data) { + if (!this._texture) { + return; + } + this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, null, this._texture.type); + }; + return RawTexture3D; +}(_texture__WEBPACK_IMPORTED_MODULE_1__["Texture"])); + + + +/***/ }), + +/***/ "./Materials/Textures/refractionTexture.ts": +/*!*************************************************!*\ + !*** ./Materials/Textures/refractionTexture.ts ***! + \*************************************************/ +/*! exports provided: RefractionTexture */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RefractionTexture", function() { return RefractionTexture; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Materials/Textures/renderTargetTexture */ "./Materials/Textures/renderTargetTexture.ts"); + + + +/** + * Creates a refraction texture used by refraction channel of the standard material. + * It is like a mirror but to see through a material. + * @see https://doc.babylonjs.com/how_to/reflect#refraction + */ +var RefractionTexture = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](RefractionTexture, _super); + /** + * Creates a refraction texture used by refraction channel of the standard material. + * It is like a mirror but to see through a material. + * @see https://doc.babylonjs.com/how_to/reflect#refraction + * @param name Define the texture name + * @param size Define the size of the underlying texture + * @param scene Define the scene the refraction belongs to + * @param generateMipMaps Define if we need to generate mips level for the refraction + */ + function RefractionTexture(name, size, scene, generateMipMaps) { + var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this; + /** + * Define the reflection plane we want to use. The refractionPlane is usually set to the constructed refractor. + * It is possible to directly set the refractionPlane by directly using a Plane(a, b, c, d) where a, b and c give the plane normal vector (a, b, c) and d is a scalar displacement from the refractionPlane to the origin. However in all but the very simplest of situations it is more straight forward to set it to the refractor as stated in the doc. + * @see https://doc.babylonjs.com/how_to/reflect#refraction + */ + _this.refractionPlane = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Plane"](0, 1, 0, 1); + /** + * Define how deep under the surface we should see. + */ + _this.depth = 2.0; + _this.onBeforeRenderObservable.add(function () { + scene.clipPlane = _this.refractionPlane; + }); + _this.onAfterRenderObservable.add(function () { + scene.clipPlane = null; + }); + return _this; + } + /** + * Clone the refraction texture. + * @returns the cloned texture + */ + RefractionTexture.prototype.clone = function () { + var scene = this.getScene(); + if (!scene) { + return this; + } + var textureSize = this.getSize(); + var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps); + // Base texture + newTexture.hasAlpha = this.hasAlpha; + newTexture.level = this.level; + // Refraction Texture + newTexture.refractionPlane = this.refractionPlane.clone(); + if (this.renderList) { + newTexture.renderList = this.renderList.slice(0); + } + newTexture.depth = this.depth; + return newTexture; + }; + /** + * Serialize the texture to a JSON representation you could use in Parse later on + * @returns the serialized JSON representation + */ + RefractionTexture.prototype.serialize = function () { + if (!this.name) { + return null; + } + var serializationObject = _super.prototype.serialize.call(this); + serializationObject.mirrorPlane = this.refractionPlane.asArray(); + serializationObject.depth = this.depth; + return serializationObject; + }; + return RefractionTexture; +}(_Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_2__["RenderTargetTexture"])); + + + +/***/ }), + +/***/ "./Materials/Textures/renderTargetCreationOptions.ts": +/*!***********************************************************!*\ + !*** ./Materials/Textures/renderTargetCreationOptions.ts ***! + \***********************************************************/ +/*! exports provided: RenderTargetCreationOptions */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RenderTargetCreationOptions", function() { return RenderTargetCreationOptions; }); +/** + * Define options used to create a render target texture + */ +var RenderTargetCreationOptions = /** @class */ (function () { + function RenderTargetCreationOptions() { + } + return RenderTargetCreationOptions; +}()); + + + +/***/ }), + +/***/ "./Materials/Textures/renderTargetTexture.ts": +/*!***************************************************!*\ + !*** ./Materials/Textures/renderTargetTexture.ts ***! + \***************************************************/ +/*! exports provided: RenderTargetTexture */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RenderTargetTexture", function() { return RenderTargetTexture; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/tools */ "./Misc/tools.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Materials/Textures/texture */ "./Materials/Textures/texture.ts"); +/* harmony import */ var _PostProcesses_postProcessManager__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../PostProcesses/postProcessManager */ "./PostProcesses/postProcessManager.ts"); +/* harmony import */ var _Rendering_renderingManager__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../Rendering/renderingManager */ "./Rendering/renderingManager.ts"); +/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../Engines/constants */ "./Engines/constants.ts"); +/* harmony import */ var _Engines_Extensions_engine_renderTarget__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../Engines/Extensions/engine.renderTarget */ "./Engines/Extensions/engine.renderTarget.ts"); + + + + + + + + + +/** + * This Helps creating a texture that will be created from a camera in your scene. + * It is basically a dynamic texture that could be used to create special effects for instance. + * Actually, It is the base of lot of effects in the framework like post process, shadows, effect layers and rendering pipelines... + */ +var RenderTargetTexture = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](RenderTargetTexture, _super); + /** + * Instantiate a render target texture. This is mainly used to render of screen the scene to for instance apply post processse + * or used a shadow, depth texture... + * @param name The friendly name of the texture + * @param size The size of the RTT (number if square, or {width: number, height:number} or {ratio:} to define a ratio from the main scene) + * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised. + * @param generateMipMaps True if mip maps need to be generated after render. + * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT + * @param type The type of the buffer in the RTT (int, half float, float...) + * @param isCube True if a cube texture needs to be created + * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...) + * @param generateDepthBuffer True to generate a depth buffer + * @param generateStencilBuffer True to generate a stencil buffer + * @param isMulti True if multiple textures need to be created (Draw Buffers) + * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...) + * @param delayAllocation if the texture allocation should be delayed (default: false) + */ + function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format, delayAllocation) { + if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; } + if (type === void 0) { type = _Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_UNSIGNED_INT; } + if (isCube === void 0) { isCube = false; } + if (samplingMode === void 0) { samplingMode = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].TRILINEAR_SAMPLINGMODE; } + if (generateDepthBuffer === void 0) { generateDepthBuffer = true; } + if (generateStencilBuffer === void 0) { generateStencilBuffer = false; } + if (isMulti === void 0) { isMulti = false; } + if (format === void 0) { format = _Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RGBA; } + if (delayAllocation === void 0) { delayAllocation = false; } + var _this = _super.call(this, null, scene, !generateMipMaps) || this; + _this.isCube = isCube; + /** + * Define if particles should be rendered in your texture. + */ + _this.renderParticles = true; + /** + * Define if sprites should be rendered in your texture. + */ + _this.renderSprites = false; + /** + * Override the default coordinates mode to projection for RTT as it is the most common case for rendered textures. + */ + _this.coordinatesMode = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].PROJECTION_MODE; + /** + * Define if the camera viewport should be respected while rendering the texture or if the render should be done to the entire texture. + */ + _this.ignoreCameraViewport = false; + /** + * An event triggered when the texture is unbind. + */ + _this.onBeforeBindObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + /** + * An event triggered when the texture is unbind. + */ + _this.onAfterUnbindObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + /** + * An event triggered before rendering the texture + */ + _this.onBeforeRenderObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + /** + * An event triggered after rendering the texture + */ + _this.onAfterRenderObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + /** + * An event triggered after the texture clear + */ + _this.onClearObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + _this._currentRefreshId = -1; + _this._refreshRate = 1; + _this._samples = 1; + /** + * Gets or sets the center of the bounding box associated with the texture (when in cube mode) + * It must define where the camera used to render the texture is set + */ + _this.boundingBoxPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(); + scene = _this.getScene(); + if (!scene) { + return _this; + } + _this.renderList = new Array(); + _this._engine = scene.getEngine(); + _this.name = name; + _this.isRenderTarget = true; + _this._initialSizeParameter = size; + _this._processSizeParameter(size); + _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () { + }); + _this._generateMipMaps = generateMipMaps ? true : false; + _this._doNotChangeAspectRatio = doNotChangeAspectRatio; + // Rendering groups + _this._renderingManager = new _Rendering_renderingManager__WEBPACK_IMPORTED_MODULE_6__["RenderingManager"](scene); + _this._renderingManager._useSceneAutoClearSetup = true; + if (isMulti) { + return _this; + } + _this._renderTargetOptions = { + generateMipMaps: generateMipMaps, + type: type, + format: format, + samplingMode: samplingMode, + generateDepthBuffer: generateDepthBuffer, + generateStencilBuffer: generateStencilBuffer + }; + if (samplingMode === _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].NEAREST_SAMPLINGMODE) { + _this.wrapU = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].CLAMP_ADDRESSMODE; + _this.wrapV = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].CLAMP_ADDRESSMODE; + } + if (!delayAllocation) { + if (isCube) { + _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions); + _this.coordinatesMode = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].INVCUBIC_MODE; + _this._textureMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"].Identity(); + } + else { + _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions); + } + } + return _this; + } + Object.defineProperty(RenderTargetTexture.prototype, "renderList", { + /** + * Use this list to define the list of mesh you want to render. + */ + get: function () { + return this._renderList; + }, + set: function (value) { + this._renderList = value; + if (this._renderList) { + this._hookArray(this._renderList); + } + }, + enumerable: true, + configurable: true + }); + RenderTargetTexture.prototype._hookArray = function (array) { + var _this = this; + var oldPush = array.push; + array.push = function () { + var items = []; + for (var _i = 0; _i < arguments.length; _i++) { + items[_i] = arguments[_i]; + } + var wasEmpty = array.length === 0; + var result = oldPush.apply(array, items); + if (wasEmpty) { + _this.getScene().meshes.forEach(function (mesh) { + mesh._markSubMeshesAsLightDirty(); + }); + } + return result; + }; + var oldSplice = array.splice; + array.splice = function (index, deleteCount) { + var deleted = oldSplice.apply(array, [index, deleteCount]); + if (array.length === 0) { + _this.getScene().meshes.forEach(function (mesh) { + mesh._markSubMeshesAsLightDirty(); + }); + } + return deleted; + }; + }; + Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", { + /** + * Set a after unbind callback in the texture. + * This has been kept for backward compatibility and use of onAfterUnbindObservable is recommended. + */ + set: function (callback) { + if (this._onAfterUnbindObserver) { + this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver); + } + this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", { + /** + * Set a before render callback in the texture. + * This has been kept for backward compatibility and use of onBeforeRenderObservable is recommended. + */ + set: function (callback) { + if (this._onBeforeRenderObserver) { + this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver); + } + this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", { + /** + * Set a after render callback in the texture. + * This has been kept for backward compatibility and use of onAfterRenderObservable is recommended. + */ + set: function (callback) { + if (this._onAfterRenderObserver) { + this.onAfterRenderObservable.remove(this._onAfterRenderObserver); + } + this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(RenderTargetTexture.prototype, "onClear", { + /** + * Set a clear callback in the texture. + * This has been kept for backward compatibility and use of onClearObservable is recommended. + */ + set: function (callback) { + if (this._onClearObserver) { + this.onClearObservable.remove(this._onClearObserver); + } + this._onClearObserver = this.onClearObservable.add(callback); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", { + /** + * Gets render target creation options that were used. + */ + get: function () { + return this._renderTargetOptions; + }, + enumerable: true, + configurable: true + }); + RenderTargetTexture.prototype._onRatioRescale = function () { + if (this._sizeRatio) { + this.resize(this._initialSizeParameter); + } + }; + Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", { + get: function () { + return this._boundingBoxSize; + }, + /** + * Gets or sets the size of the bounding box associated with the texture (when in cube mode) + * When defined, the cubemap will switch to local mode + * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity + * @example https://www.babylonjs-playground.com/#RNASML + */ + set: function (value) { + if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) { + return; + } + this._boundingBoxSize = value; + var scene = this.getScene(); + if (scene) { + scene.markAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].MATERIAL_TextureDirtyFlag); + } + }, + enumerable: true, + configurable: true + }); + /** + * Creates a depth stencil texture. + * This is only available in WebGL 2 or with the depth texture extension available. + * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode + * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture + * @param generateStencil Specifies whether or not a stencil should be allocated in the texture + */ + RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) { + if (comparisonFunction === void 0) { comparisonFunction = 0; } + if (bilinearFiltering === void 0) { bilinearFiltering = true; } + if (generateStencil === void 0) { generateStencil = false; } + if (!this.getScene()) { + return; + } + var engine = this.getScene().getEngine(); + this.depthStencilTexture = engine.createDepthStencilTexture(this._size, { + bilinearFiltering: bilinearFiltering, + comparisonFunction: comparisonFunction, + generateStencil: generateStencil, + isCube: this.isCube + }); + engine.setFrameBufferDepthStencilTexture(this); + }; + RenderTargetTexture.prototype._processSizeParameter = function (size) { + if (size.ratio) { + this._sizeRatio = size.ratio; + this._size = { + width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio), + height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio) + }; + } + else { + this._size = size; + } + }; + Object.defineProperty(RenderTargetTexture.prototype, "samples", { + /** + * Define the number of samples to use in case of MSAA. + * It defaults to one meaning no MSAA has been enabled. + */ + get: function () { + return this._samples; + }, + set: function (value) { + if (this._samples === value) { + return; + } + var scene = this.getScene(); + if (!scene) { + return; + } + this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value); + }, + enumerable: true, + configurable: true + }); + /** + * Resets the refresh counter of the texture and start bak from scratch. + * Could be useful to regenerate the texture if it is setup to render only once. + */ + RenderTargetTexture.prototype.resetRefreshCounter = function () { + this._currentRefreshId = -1; + }; + Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", { + /** + * Define the refresh rate of the texture or the rendering frequency. + * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on... + */ + get: function () { + return this._refreshRate; + }, + set: function (value) { + this._refreshRate = value; + this.resetRefreshCounter(); + }, + enumerable: true, + configurable: true + }); + /** + * Adds a post process to the render target rendering passes. + * @param postProcess define the post process to add + */ + RenderTargetTexture.prototype.addPostProcess = function (postProcess) { + if (!this._postProcessManager) { + var scene = this.getScene(); + if (!scene) { + return; + } + this._postProcessManager = new _PostProcesses_postProcessManager__WEBPACK_IMPORTED_MODULE_5__["PostProcessManager"](scene); + this._postProcesses = new Array(); + } + this._postProcesses.push(postProcess); + this._postProcesses[0].autoClear = false; + }; + /** + * Clear all the post processes attached to the render target + * @param dispose define if the cleared post processesshould also be disposed (false by default) + */ + RenderTargetTexture.prototype.clearPostProcesses = function (dispose) { + if (dispose === void 0) { dispose = false; } + if (!this._postProcesses) { + return; + } + if (dispose) { + for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) { + var postProcess = _a[_i]; + postProcess.dispose(); + } + } + this._postProcesses = []; + }; + /** + * Remove one of the post process from the list of attached post processes to the texture + * @param postProcess define the post process to remove from the list + */ + RenderTargetTexture.prototype.removePostProcess = function (postProcess) { + if (!this._postProcesses) { + return; + } + var index = this._postProcesses.indexOf(postProcess); + if (index === -1) { + return; + } + this._postProcesses.splice(index, 1); + if (this._postProcesses.length > 0) { + this._postProcesses[0].autoClear = false; + } + }; + /** @hidden */ + RenderTargetTexture.prototype._shouldRender = function () { + if (this._currentRefreshId === -1) { // At least render once + this._currentRefreshId = 1; + return true; + } + if (this.refreshRate === this._currentRefreshId) { + this._currentRefreshId = 1; + return true; + } + this._currentRefreshId++; + return false; + }; + /** + * Gets the actual render size of the texture. + * @returns the width of the render size + */ + RenderTargetTexture.prototype.getRenderSize = function () { + return this.getRenderWidth(); + }; + /** + * Gets the actual render width of the texture. + * @returns the width of the render size + */ + RenderTargetTexture.prototype.getRenderWidth = function () { + if (this._size.width) { + return this._size.width; + } + return this._size; + }; + /** + * Gets the actual render height of the texture. + * @returns the height of the render size + */ + RenderTargetTexture.prototype.getRenderHeight = function () { + if (this._size.width) { + return this._size.height; + } + return this._size; + }; + Object.defineProperty(RenderTargetTexture.prototype, "canRescale", { + /** + * Get if the texture can be rescaled or not. + */ + get: function () { + return true; + }, + enumerable: true, + configurable: true + }); + /** + * Resize the texture using a ratio. + * @param ratio the ratio to apply to the texture size in order to compute the new target size + */ + RenderTargetTexture.prototype.scale = function (ratio) { + var newSize = this.getRenderSize() * ratio; + this.resize(newSize); + }; + /** + * Get the texture reflection matrix used to rotate/transform the reflection. + * @returns the reflection matrix + */ + RenderTargetTexture.prototype.getReflectionTextureMatrix = function () { + if (this.isCube) { + return this._textureMatrix; + } + return _super.prototype.getReflectionTextureMatrix.call(this); + }; + /** + * Resize the texture to a new desired size. + * Be carrefull as it will recreate all the data in the new texture. + * @param size Define the new size. It can be: + * - a number for squared texture, + * - an object containing { width: number, height: number } + * - or an object containing a ratio { ratio: number } + */ + RenderTargetTexture.prototype.resize = function (size) { + var wasCube = this.isCube; + this.releaseInternalTexture(); + var scene = this.getScene(); + if (!scene) { + return; + } + this._processSizeParameter(size); + if (wasCube) { + this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions); + } + else { + this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions); + } + }; + /** + * Renders all the objects from the render list into the texture. + * @param useCameraPostProcess Define if camera post processes should be used during the rendering + * @param dumpForDebug Define if the rendering result should be dumped (copied) for debugging purpose + */ + RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) { + if (useCameraPostProcess === void 0) { useCameraPostProcess = false; } + if (dumpForDebug === void 0) { dumpForDebug = false; } + var scene = this.getScene(); + if (!scene) { + return; + } + var engine = scene.getEngine(); + if (this.useCameraPostProcesses !== undefined) { + useCameraPostProcess = this.useCameraPostProcesses; + } + if (this._waitingRenderList) { + this.renderList = []; + for (var index = 0; index < this._waitingRenderList.length; index++) { + var id = this._waitingRenderList[index]; + var mesh_1 = scene.getMeshByID(id); + if (mesh_1) { + this.renderList.push(mesh_1); + } + } + delete this._waitingRenderList; + } + // Is predicate defined? + if (this.renderListPredicate) { + if (this.renderList) { + this.renderList.length = 0; // Clear previous renderList + } + else { + this.renderList = []; + } + var scene = this.getScene(); + if (!scene) { + return; + } + var sceneMeshes = scene.meshes; + for (var index = 0; index < sceneMeshes.length; index++) { + var mesh = sceneMeshes[index]; + if (this.renderListPredicate(mesh)) { + this.renderList.push(mesh); + } + } + } + this.onBeforeBindObservable.notifyObservers(this); + // Set custom projection. + // Needs to be before binding to prevent changing the aspect ratio. + var camera; + if (this.activeCamera) { + camera = this.activeCamera; + engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight()); + if (this.activeCamera !== scene.activeCamera) { + scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true)); + } + } + else { + camera = scene.activeCamera; + if (camera) { + engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight()); + } + } + // Prepare renderingManager + this._renderingManager.reset(); + var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data; + var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length; + var sceneRenderId = scene.getRenderId(); + for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) { + var mesh = currentRenderList[meshIndex]; + if (mesh) { + if (!mesh.isReady(this.refreshRate === 0)) { + this.resetRefreshCounter(); + continue; + } + mesh._preActivateForIntermediateRendering(sceneRenderId); + var isMasked = void 0; + if (!this.renderList && camera) { + isMasked = ((mesh.layerMask & camera.layerMask) === 0); + } + else { + isMasked = false; + } + if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) { + if (mesh._activate(sceneRenderId, true)) { + if (!mesh.isAnInstance) { + mesh._internalAbstractMeshDataInfo._onlyForInstancesIntermediate = false; + } + else { + mesh = mesh.sourceMesh; + } + mesh._internalAbstractMeshDataInfo._isActiveIntermediate = true; + for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) { + var subMesh = mesh.subMeshes[subIndex]; + scene._activeIndices.addCount(subMesh.indexCount, false); + this._renderingManager.dispatch(subMesh, mesh); + } + } + } + } + } + for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) { + var particleSystem = scene.particleSystems[particleIndex]; + var emitter = particleSystem.emitter; + if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) { + continue; + } + if (currentRenderList.indexOf(emitter) >= 0) { + this._renderingManager.dispatchParticles(particleSystem); + } + } + if (this.isCube) { + for (var face = 0; face < 6; face++) { + this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug); + scene.incrementRenderId(); + scene.resetCachedMaterial(); + } + } + else { + this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug); + } + this.onAfterUnbindObservable.notifyObservers(this); + if (scene.activeCamera) { + // Do not avoid setting uniforms when multiple scenes are active as another camera may have overwrite these + if (scene.getEngine().scenes.length > 1 || (this.activeCamera && this.activeCamera !== scene.activeCamera)) { + scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true)); + } + engine.setViewport(scene.activeCamera.viewport); + } + scene.resetCachedMaterial(); + }; + RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) { + var minimum = 128; + var x = renderDimension * scale; + var curved = _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].NearestPOT(x + (minimum * minimum / (minimum + x))); + // Ensure we don't exceed the render dimension (while staying POT) + return Math.min(_Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].FloorPOT(renderDimension), curved); + }; + /** + * @hidden + * @param faceIndex face index to bind to if this is a cubetexture + */ + RenderTargetTexture.prototype._bindFrameBuffer = function (faceIndex) { + if (faceIndex === void 0) { faceIndex = 0; } + var scene = this.getScene(); + if (!scene) { + return; + } + var engine = scene.getEngine(); + if (this._texture) { + engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined); + } + }; + RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) { + var _this = this; + if (!this._texture) { + return; + } + engine.unBindFramebuffer(this._texture, this.isCube, function () { + _this.onAfterRenderObservable.notifyObservers(faceIndex); + }); + }; + RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) { + var scene = this.getScene(); + if (!scene) { + return; + } + var engine = scene.getEngine(); + if (!this._texture) { + return; + } + // Bind + if (this._postProcessManager) { + this._postProcessManager._prepareFrame(this._texture, this._postProcesses); + } + else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) { + this._bindFrameBuffer(faceIndex); + } + this.onBeforeRenderObservable.notifyObservers(faceIndex); + // Clear + if (this.onClearObservable.hasObservers()) { + this.onClearObservable.notifyObservers(engine); + } + else { + engine.clear(this.clearColor || scene.clearColor, true, true, true); + } + if (!this._doNotChangeAspectRatio) { + scene.updateTransformMatrix(true); + } + // Before Camera Draw + for (var _i = 0, _a = scene._beforeRenderTargetDrawStage; _i < _a.length; _i++) { + var step = _a[_i]; + step.action(this); + } + // Render + this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites); + // After Camera Draw + for (var _b = 0, _c = scene._afterRenderTargetDrawStage; _b < _c.length; _b++) { + var step = _c[_b]; + step.action(this); + } + if (this._postProcessManager) { + this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport); + } + else if (useCameraPostProcess) { + scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex); + } + if (!this._doNotChangeAspectRatio) { + scene.updateTransformMatrix(true); + } + // Dump ? + if (dumpForDebug) { + _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine); + } + // Unbind + if (!this.isCube || faceIndex === 5) { + if (this.isCube) { + if (faceIndex === 5) { + engine.generateMipMapsForCubemap(this._texture); + } + } + this.unbindFrameBuffer(engine, faceIndex); + } + else { + this.onAfterRenderObservable.notifyObservers(faceIndex); + } + }; + /** + * Overrides the default sort function applied in the renderging group to prepare the meshes. + * This allowed control for front to back rendering or reversly depending of the special needs. + * + * @param renderingGroupId The rendering group id corresponding to its index + * @param opaqueSortCompareFn The opaque queue comparison function use to sort. + * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort. + * @param transparentSortCompareFn The transparent queue comparison function use to sort. + */ + RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) { + if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; } + if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; } + if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; } + this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn); + }; + /** + * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups. + * + * @param renderingGroupId The rendering group id corresponding to its index + * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true. + */ + RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) { + this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil); + this._renderingManager._useSceneAutoClearSetup = false; + }; + /** + * Clones the texture. + * @returns the cloned texture + */ + RenderTargetTexture.prototype.clone = function () { + var textureSize = this.getSize(); + var newTexture = new RenderTargetTexture(this.name, textureSize, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer); + // Base texture + newTexture.hasAlpha = this.hasAlpha; + newTexture.level = this.level; + // RenderTarget Texture + newTexture.coordinatesMode = this.coordinatesMode; + if (this.renderList) { + newTexture.renderList = this.renderList.slice(0); + } + return newTexture; + }; + /** + * Serialize the texture to a JSON representation we can easily use in the resepective Parse function. + * @returns The JSON representation of the texture + */ + RenderTargetTexture.prototype.serialize = function () { + if (!this.name) { + return null; + } + var serializationObject = _super.prototype.serialize.call(this); + serializationObject.renderTargetSize = this.getRenderSize(); + serializationObject.renderList = []; + if (this.renderList) { + for (var index = 0; index < this.renderList.length; index++) { + serializationObject.renderList.push(this.renderList[index].id); + } + } + return serializationObject; + }; + /** + * This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore + */ + RenderTargetTexture.prototype.disposeFramebufferObjects = function () { + var objBuffer = this.getInternalTexture(); + var scene = this.getScene(); + if (objBuffer && scene) { + scene.getEngine()._releaseFramebufferObjects(objBuffer); + } + }; + /** + * Dispose the texture and release its associated resources. + */ + RenderTargetTexture.prototype.dispose = function () { + if (this._postProcessManager) { + this._postProcessManager.dispose(); + this._postProcessManager = null; + } + this.clearPostProcesses(true); + if (this._resizeObserver) { + this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver); + this._resizeObserver = null; + } + this.renderList = null; + // Remove from custom render targets + var scene = this.getScene(); + if (!scene) { + return; + } + var index = scene.customRenderTargets.indexOf(this); + if (index >= 0) { + scene.customRenderTargets.splice(index, 1); + } + for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) { + var camera = _a[_i]; + index = camera.customRenderTargets.indexOf(this); + if (index >= 0) { + camera.customRenderTargets.splice(index, 1); + } + } + if (this.depthStencilTexture) { + this.getScene().getEngine()._releaseTexture(this.depthStencilTexture); + } + _super.prototype.dispose.call(this); + }; + /** @hidden */ + RenderTargetTexture.prototype._rebuild = function () { + if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) { + this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE; + } + if (this._postProcessManager) { + this._postProcessManager._rebuild(); + } + }; + /** + * Clear the info related to rendering groups preventing retention point in material dispose. + */ + RenderTargetTexture.prototype.freeRenderingGroups = function () { + if (this._renderingManager) { + this._renderingManager.freeRenderingGroups(); + } + }; + /** + * Gets the number of views the corresponding to the texture (eg. a MultiviewRenderTarget will have > 1) + * @returns the view count + */ + RenderTargetTexture.prototype.getViewCount = function () { + return 1; + }; + /** + * The texture will only be rendered once which can be useful to improve performance if everything in your render is static for instance. + */ + RenderTargetTexture.REFRESHRATE_RENDER_ONCE = 0; + /** + * The texture will only be rendered rendered every frame and is recomended for dynamic contents. + */ + RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME = 1; + /** + * The texture will be rendered every 2 frames which could be enough if your dynamic objects are not + * the central point of your effect and can save a lot of performances. + */ + RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2; + return RenderTargetTexture; +}(_Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"])); + +_Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"]._CreateRenderTargetTexture = function (name, renderTargetSize, scene, generateMipMaps) { + return new RenderTargetTexture(name, renderTargetSize, scene, generateMipMaps); +}; + + +/***/ }), + +/***/ "./Materials/Textures/texture.ts": +/*!***************************************!*\ + !*** ./Materials/Textures/texture.ts ***! + \***************************************/ +/*! exports provided: Texture */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Texture", function() { return Texture; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Misc/tools */ "./Misc/tools.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Materials_Textures_baseTexture__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Materials/Textures/baseTexture */ "./Materials/Textures/baseTexture.ts"); +/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../Engines/constants */ "./Engines/constants.ts"); +/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../Misc/typeStore */ "./Misc/typeStore.ts"); +/* harmony import */ var _Misc_devTools__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../Misc/devTools */ "./Misc/devTools.ts"); + + + + + + + + + +/** + * This represents a texture in babylon. It can be easily loaded from a network, base64 or html input. + * @see http://doc.babylonjs.com/babylon101/materials#texture + */ +var Texture = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Texture, _super); + /** + * Instantiates a new texture. + * This represents a texture in babylon. It can be easily loaded from a network, base64 or html input. + * @see http://doc.babylonjs.com/babylon101/materials#texture + * @param url define the url of the picture to load as a texture + * @param scene define the scene the texture will belong to + * @param noMipmap define if the texture will require mip maps or not + * @param invertY define if the texture needs to be inverted on the y axis during loading + * @param samplingMode define the sampling mode we want for the texture while fectching from it (Texture.NEAREST_SAMPLINGMODE...) + * @param onLoad define a callback triggered when the texture has been loaded + * @param onError define a callback triggered when an error occurred during the loading session + * @param buffer define the buffer to load the texture from in case the texture is loaded from a buffer representation + * @param deleteBuffer define if the buffer we are loading the texture from should be deleted after load + * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...) + */ + function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) { + if (noMipmap === void 0) { noMipmap = false; } + if (invertY === void 0) { invertY = true; } + if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; } + if (onLoad === void 0) { onLoad = null; } + if (onError === void 0) { onError = null; } + if (buffer === void 0) { buffer = null; } + if (deleteBuffer === void 0) { deleteBuffer = false; } + var _this = _super.call(this, scene) || this; + /** + * Define the url of the texture. + */ + _this.url = null; + /** + * Define an offset on the texture to offset the u coordinates of the UVs + * @see http://doc.babylonjs.com/how_to/more_materials#offsetting + */ + _this.uOffset = 0; + /** + * Define an offset on the texture to offset the v coordinates of the UVs + * @see http://doc.babylonjs.com/how_to/more_materials#offsetting + */ + _this.vOffset = 0; + /** + * Define an offset on the texture to scale the u coordinates of the UVs + * @see http://doc.babylonjs.com/how_to/more_materials#tiling + */ + _this.uScale = 1.0; + /** + * Define an offset on the texture to scale the v coordinates of the UVs + * @see http://doc.babylonjs.com/how_to/more_materials#tiling + */ + _this.vScale = 1.0; + /** + * Define an offset on the texture to rotate around the u coordinates of the UVs + * @see http://doc.babylonjs.com/how_to/more_materials + */ + _this.uAng = 0; + /** + * Define an offset on the texture to rotate around the v coordinates of the UVs + * @see http://doc.babylonjs.com/how_to/more_materials + */ + _this.vAng = 0; + /** + * Define an offset on the texture to rotate around the w coordinates of the UVs (in case of 3d texture) + * @see http://doc.babylonjs.com/how_to/more_materials + */ + _this.wAng = 0; + /** + * Defines the center of rotation (U) + */ + _this.uRotationCenter = 0.5; + /** + * Defines the center of rotation (V) + */ + _this.vRotationCenter = 0.5; + /** + * Defines the center of rotation (W) + */ + _this.wRotationCenter = 0.5; + /** + * List of inspectable custom properties (used by the Inspector) + * @see https://doc.babylonjs.com/how_to/debug_layer#extensibility + */ + _this.inspectableCustomProperties = null; + _this._noMipmap = false; + /** @hidden */ + _this._invertY = false; + _this._rowGenerationMatrix = null; + _this._cachedTextureMatrix = null; + _this._projectionModeMatrix = null; + _this._t0 = null; + _this._t1 = null; + _this._t2 = null; + _this._cachedUOffset = -1; + _this._cachedVOffset = -1; + _this._cachedUScale = 0; + _this._cachedVScale = 0; + _this._cachedUAng = -1; + _this._cachedVAng = -1; + _this._cachedWAng = -1; + _this._cachedProjectionMatrixId = -1; + _this._cachedCoordinatesMode = -1; + /** @hidden */ + _this._initialSamplingMode = Texture.BILINEAR_SAMPLINGMODE; + /** @hidden */ + _this._buffer = null; + _this._deleteBuffer = false; + _this._format = null; + _this._delayedOnLoad = null; + _this._delayedOnError = null; + /** + * Observable triggered once the texture has been loaded. + */ + _this.onLoadObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); + _this._isBlocking = true; + _this.name = url || ""; + _this.url = url; + _this._noMipmap = noMipmap; + _this._invertY = invertY; + _this._initialSamplingMode = samplingMode; + _this._buffer = buffer; + _this._deleteBuffer = deleteBuffer; + if (format) { + _this._format = format; + } + scene = _this.getScene(); + if (!scene) { + return _this; + } + scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this); + var load = function () { + if (_this._texture && _this._texture._invertVScale) { + _this.vScale = -1; + } + if (_this.onLoadObservable.hasObservers()) { + _this.onLoadObservable.notifyObservers(_this); + } + if (onLoad) { + onLoad(); + } + if (!_this.isBlocking && scene) { + scene.resetCachedMaterial(); + } + }; + if (!_this.url) { + _this._delayedOnLoad = load; + _this._delayedOnError = onError; + return _this; + } + _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode, invertY); + if (!_this._texture) { + if (!scene.useDelayedTextureLoading) { + _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, samplingMode, load, onError, _this._buffer, undefined, _this._format); + if (deleteBuffer) { + delete _this._buffer; + } + } + else { + _this.delayLoadState = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].DELAYLOADSTATE_NOTLOADED; + _this._delayedOnLoad = load; + _this._delayedOnError = onError; + } + } + else { + if (_this._texture.isReady) { + _Misc_tools__WEBPACK_IMPORTED_MODULE_3__["Tools"].SetImmediate(function () { return load(); }); + } + else { + _this._texture.onLoadedObservable.add(load); + } + } + return _this; + } + Object.defineProperty(Texture.prototype, "noMipmap", { + /** + * Are mip maps generated for this texture or not. + */ + get: function () { + return this._noMipmap; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Texture.prototype, "isBlocking", { + get: function () { + return this._isBlocking; + }, + /** + * Is the texture preventing material to render while loading. + * If false, a default texture will be used instead of the loading one during the preparation step. + */ + set: function (value) { + this._isBlocking = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Texture.prototype, "samplingMode", { + /** + * Get the current sampling mode associated with the texture. + */ + get: function () { + if (!this._texture) { + return this._initialSamplingMode; + } + return this._texture.samplingMode; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Texture.prototype, "invertY", { + /** + * Gets a boolean indicating if the texture needs to be inverted on the y axis during loading + */ + get: function () { + return this._invertY; + }, + enumerable: true, + configurable: true + }); + /** + * Update the url (and optional buffer) of this texture if url was null during construction. + * @param url the url of the texture + * @param buffer the buffer of the texture (defaults to null) + * @param onLoad callback called when the texture is loaded (defaults to null) + */ + Texture.prototype.updateURL = function (url, buffer, onLoad) { + if (buffer === void 0) { buffer = null; } + if (this.url) { + this.releaseInternalTexture(); + this.getScene().markAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].MATERIAL_TextureDirtyFlag); + } + this.url = url; + this._buffer = buffer; + this.delayLoadState = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].DELAYLOADSTATE_NOTLOADED; + if (onLoad) { + this._delayedOnLoad = onLoad; + } + this.delayLoad(); + }; + /** + * Finish the loading sequence of a texture flagged as delayed load. + * @hidden + */ + Texture.prototype.delayLoad = function () { + if (this.delayLoadState !== _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].DELAYLOADSTATE_NOTLOADED) { + return; + } + var scene = this.getScene(); + if (!scene) { + return; + } + this.delayLoadState = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].DELAYLOADSTATE_LOADED; + this._texture = this._getFromCache(this.url, this._noMipmap, this.samplingMode, this._invertY); + if (!this._texture) { + this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this.samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format); + if (this._deleteBuffer) { + delete this._buffer; + } + } + else { + if (this._delayedOnLoad) { + if (this._texture.isReady) { + _Misc_tools__WEBPACK_IMPORTED_MODULE_3__["Tools"].SetImmediate(this._delayedOnLoad); + } + else { + this._texture.onLoadedObservable.add(this._delayedOnLoad); + } + } + } + this._delayedOnLoad = null; + this._delayedOnError = null; + }; + Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) { + x *= this.uScale; + y *= this.vScale; + x -= this.uRotationCenter * this.uScale; + y -= this.vRotationCenter * this.vScale; + z -= this.wRotationCenter; + _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"].TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t); + t.x += this.uRotationCenter * this.uScale + this.uOffset; + t.y += this.vRotationCenter * this.vScale + this.vOffset; + t.z += this.wRotationCenter; + }; + /** + * Get the current texture matrix which includes the requested offsetting, tiling and rotation components. + * @returns the transform matrix of the texture. + */ + Texture.prototype.getTextureMatrix = function () { + var _this = this; + if (this.uOffset === this._cachedUOffset && + this.vOffset === this._cachedVOffset && + this.uScale === this._cachedUScale && + this.vScale === this._cachedVScale && + this.uAng === this._cachedUAng && + this.vAng === this._cachedVAng && + this.wAng === this._cachedWAng) { + return this._cachedTextureMatrix; + } + this._cachedUOffset = this.uOffset; + this._cachedVOffset = this.vOffset; + this._cachedUScale = this.uScale; + this._cachedVScale = this.vScale; + this._cachedUAng = this.uAng; + this._cachedVAng = this.vAng; + this._cachedWAng = this.wAng; + if (!this._cachedTextureMatrix) { + this._cachedTextureMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"].Zero(); + this._rowGenerationMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"](); + this._t0 = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"].Zero(); + this._t1 = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"].Zero(); + this._t2 = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"].Zero(); + } + _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"].RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix); + this._prepareRowForTextureGeneration(0, 0, 0, this._t0); + this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1); + this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2); + this._t1.subtractInPlace(this._t0); + this._t2.subtractInPlace(this._t0); + _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"].FromValuesToRef(this._t1.x, this._t1.y, this._t1.z, 0.0, this._t2.x, this._t2.y, this._t2.z, 0.0, this._t0.x, this._t0.y, this._t0.z, 0.0, 0.0, 0.0, 0.0, 1.0, this._cachedTextureMatrix); + var scene = this.getScene(); + if (!scene) { + return this._cachedTextureMatrix; + } + scene.markAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].MATERIAL_TextureDirtyFlag, function (mat) { + return mat.hasTexture(_this); + }); + return this._cachedTextureMatrix; + }; + /** + * Get the current matrix used to apply reflection. This is useful to rotate an environment texture for instance. + * @returns The reflection texture transform + */ + Texture.prototype.getReflectionTextureMatrix = function () { + var _this = this; + var scene = this.getScene(); + if (!scene) { + return this._cachedTextureMatrix; + } + if (this.uOffset === this._cachedUOffset && + this.vOffset === this._cachedVOffset && + this.uScale === this._cachedUScale && + this.vScale === this._cachedVScale && + this.coordinatesMode === this._cachedCoordinatesMode) { + if (this.coordinatesMode === Texture.PROJECTION_MODE) { + if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) { + return this._cachedTextureMatrix; + } + } + else { + return this._cachedTextureMatrix; + } + } + if (!this._cachedTextureMatrix) { + this._cachedTextureMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"].Zero(); + } + if (!this._projectionModeMatrix) { + this._projectionModeMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"].Zero(); + } + this._cachedUOffset = this.uOffset; + this._cachedVOffset = this.vOffset; + this._cachedUScale = this.uScale; + this._cachedVScale = this.vScale; + this._cachedCoordinatesMode = this.coordinatesMode; + switch (this.coordinatesMode) { + case Texture.PLANAR_MODE: + _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"].IdentityToRef(this._cachedTextureMatrix); + this._cachedTextureMatrix[0] = this.uScale; + this._cachedTextureMatrix[5] = this.vScale; + this._cachedTextureMatrix[12] = this.uOffset; + this._cachedTextureMatrix[13] = this.vOffset; + break; + case Texture.PROJECTION_MODE: + _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"].FromValuesToRef(0.5, 0.0, 0.0, 0.0, 0.0, -0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.5, 1.0, 1.0, this._projectionModeMatrix); + var projectionMatrix = scene.getProjectionMatrix(); + this._cachedProjectionMatrixId = projectionMatrix.updateFlag; + projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix); + break; + default: + _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"].IdentityToRef(this._cachedTextureMatrix); + break; + } + scene.markAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].MATERIAL_TextureDirtyFlag, function (mat) { + return (mat.getActiveTextures().indexOf(_this) !== -1); + }); + return this._cachedTextureMatrix; + }; + /** + * Clones the texture. + * @returns the cloned texture + */ + Texture.prototype.clone = function () { + var _this = this; + return _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Clone(function () { + return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this.samplingMode, undefined, undefined, _this._texture ? _this._texture._buffer : undefined); + }, this); + }; + /** + * Serialize the texture to a JSON representation we can easily use in the resepective Parse function. + * @returns The JSON representation of the texture + */ + Texture.prototype.serialize = function () { + var serializationObject = _super.prototype.serialize.call(this); + if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") { + serializationObject.base64String = this._buffer; + serializationObject.name = serializationObject.name.replace("data:", ""); + } + serializationObject.invertY = this._invertY; + serializationObject.samplingMode = this.samplingMode; + return serializationObject; + }; + /** + * Get the current class name of the texture useful for serialization or dynamic coding. + * @returns "Texture" + */ + Texture.prototype.getClassName = function () { + return "Texture"; + }; + /** + * Dispose the texture and release its associated resources. + */ + Texture.prototype.dispose = function () { + _super.prototype.dispose.call(this); + this.onLoadObservable.clear(); + this._delayedOnLoad = null; + this._delayedOnError = null; + }; + /** + * Parse the JSON representation of a texture in order to recreate the texture in the given scene. + * @param parsedTexture Define the JSON representation of the texture + * @param scene Define the scene the parsed texture should be instantiated in + * @param rootUrl Define the root url of the parsing sequence in the case of relative dependencies + * @returns The parsed texture if successful + */ + Texture.Parse = function (parsedTexture, scene, rootUrl) { + if (parsedTexture.customType) { + var customTexture = _Misc_tools__WEBPACK_IMPORTED_MODULE_3__["Tools"].Instantiate(parsedTexture.customType); + // Update Sampling Mode + var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl); + if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) { + if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) { + parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode); + } + } + return parsedCustomTexture; + } + if (parsedTexture.isCube && !parsedTexture.isRenderTarget) { + return Texture._CubeTextureParser(parsedTexture, scene, rootUrl); + } + if (!parsedTexture.name && !parsedTexture.isRenderTarget) { + return null; + } + var texture = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(function () { + var generateMipMaps = true; + if (parsedTexture.noMipmap) { + generateMipMaps = false; + } + if (parsedTexture.mirrorPlane) { + var mirrorTexture = Texture._CreateMirror(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps); + mirrorTexture._waitingRenderList = parsedTexture.renderList; + mirrorTexture.mirrorPlane = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Plane"].FromArray(parsedTexture.mirrorPlane); + return mirrorTexture; + } + else if (parsedTexture.isRenderTarget) { + var renderTargetTexture = null; + if (parsedTexture.isCube) { + // Search for an existing reflection probe (which contains a cube render target texture) + if (scene.reflectionProbes) { + for (var index = 0; index < scene.reflectionProbes.length; index++) { + var probe = scene.reflectionProbes[index]; + if (probe.name === parsedTexture.name) { + return probe.cubeTexture; + } + } + } + } + else { + renderTargetTexture = Texture._CreateRenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps); + renderTargetTexture._waitingRenderList = parsedTexture.renderList; + } + return renderTargetTexture; + } + else { + var texture; + if (parsedTexture.base64String) { + texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps); + } + else { + var url = rootUrl + parsedTexture.name; + if (Texture.UseSerializedUrlIfAny && parsedTexture.url) { + url = parsedTexture.url; + } + texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY); + } + return texture; + } + }, parsedTexture, scene); + // Update Sampling Mode + if (parsedTexture.samplingMode) { + var sampling = parsedTexture.samplingMode; + if (texture && texture.samplingMode !== sampling) { + texture.updateSamplingMode(sampling); + } + } + // Animations + if (texture && parsedTexture.animations) { + for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) { + var parsedAnimation = parsedTexture.animations[animationIndex]; + var internalClass = _Misc_typeStore__WEBPACK_IMPORTED_MODULE_7__["_TypeStore"].GetClass("BABYLON.Animation"); + if (internalClass) { + texture.animations.push(internalClass.Parse(parsedAnimation)); + } + } + } + return texture; + }; + /** + * Creates a texture from its base 64 representation. + * @param data Define the base64 payload without the data: prefix + * @param name Define the name of the texture in the scene useful fo caching purpose for instance + * @param scene Define the scene the texture should belong to + * @param noMipmap Forces the texture to not create mip map information if true + * @param invertY define if the texture needs to be inverted on the y axis during loading + * @param samplingMode define the sampling mode we want for the texture while fectching from it (Texture.NEAREST_SAMPLINGMODE...) + * @param onLoad define a callback triggered when the texture has been loaded + * @param onError define a callback triggered when an error occurred during the loading session + * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...) + * @returns the created texture + */ + Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) { + if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; } + if (onLoad === void 0) { onLoad = null; } + if (onError === void 0) { onError = null; } + if (format === void 0) { format = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTUREFORMAT_RGBA; } + return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format); + }; + /** + * Creates a texture from its data: representation. (data: will be added in case only the payload has been passed in) + * @param data Define the base64 payload without the data: prefix + * @param name Define the name of the texture in the scene useful fo caching purpose for instance + * @param buffer define the buffer to load the texture from in case the texture is loaded from a buffer representation + * @param scene Define the scene the texture should belong to + * @param deleteBuffer define if the buffer we are loading the texture from should be deleted after load + * @param noMipmap Forces the texture to not create mip map information if true + * @param invertY define if the texture needs to be inverted on the y axis during loading + * @param samplingMode define the sampling mode we want for the texture while fectching from it (Texture.NEAREST_SAMPLINGMODE...) + * @param onLoad define a callback triggered when the texture has been loaded + * @param onError define a callback triggered when an error occurred during the loading session + * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...) + * @returns the created texture + */ + Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) { + if (deleteBuffer === void 0) { deleteBuffer = false; } + if (noMipmap === void 0) { noMipmap = false; } + if (invertY === void 0) { invertY = true; } + if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; } + if (onLoad === void 0) { onLoad = null; } + if (onError === void 0) { onError = null; } + if (format === void 0) { format = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTUREFORMAT_RGBA; } + if (name.substr(0, 5) !== "data:") { + name = "data:" + name; + } + return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format); + }; + /** @hidden */ + Texture._CubeTextureParser = function (jsonTexture, scene, rootUrl) { + throw _Misc_devTools__WEBPACK_IMPORTED_MODULE_8__["_DevTools"].WarnImport("CubeTexture"); + }; + /** @hidden */ + Texture._CreateMirror = function (name, renderTargetSize, scene, generateMipMaps) { + throw _Misc_devTools__WEBPACK_IMPORTED_MODULE_8__["_DevTools"].WarnImport("MirrorTexture"); + }; + /** @hidden */ + Texture._CreateRenderTargetTexture = function (name, renderTargetSize, scene, generateMipMaps) { + throw _Misc_devTools__WEBPACK_IMPORTED_MODULE_8__["_DevTools"].WarnImport("RenderTargetTexture"); + }; + /** nearest is mag = nearest and min = nearest and mip = linear */ + Texture.NEAREST_SAMPLINGMODE = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_NEAREST_SAMPLINGMODE; + /** nearest is mag = nearest and min = nearest and mip = linear */ + Texture.NEAREST_NEAREST_MIPLINEAR = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear + /** Bilinear is mag = linear and min = linear and mip = nearest */ + Texture.BILINEAR_SAMPLINGMODE = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_BILINEAR_SAMPLINGMODE; + /** Bilinear is mag = linear and min = linear and mip = nearest */ + Texture.LINEAR_LINEAR_MIPNEAREST = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest + /** Trilinear is mag = linear and min = linear and mip = linear */ + Texture.TRILINEAR_SAMPLINGMODE = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_TRILINEAR_SAMPLINGMODE; + /** Trilinear is mag = linear and min = linear and mip = linear */ + Texture.LINEAR_LINEAR_MIPLINEAR = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear + /** mag = nearest and min = nearest and mip = nearest */ + Texture.NEAREST_NEAREST_MIPNEAREST = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_NEAREST_NEAREST_MIPNEAREST; + /** mag = nearest and min = linear and mip = nearest */ + Texture.NEAREST_LINEAR_MIPNEAREST = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_NEAREST_LINEAR_MIPNEAREST; + /** mag = nearest and min = linear and mip = linear */ + Texture.NEAREST_LINEAR_MIPLINEAR = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_NEAREST_LINEAR_MIPLINEAR; + /** mag = nearest and min = linear and mip = none */ + Texture.NEAREST_LINEAR = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_NEAREST_LINEAR; + /** mag = nearest and min = nearest and mip = none */ + Texture.NEAREST_NEAREST = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_NEAREST_NEAREST; + /** mag = linear and min = nearest and mip = nearest */ + Texture.LINEAR_NEAREST_MIPNEAREST = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_LINEAR_NEAREST_MIPNEAREST; + /** mag = linear and min = nearest and mip = linear */ + Texture.LINEAR_NEAREST_MIPLINEAR = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_LINEAR_NEAREST_MIPLINEAR; + /** mag = linear and min = linear and mip = none */ + Texture.LINEAR_LINEAR = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_LINEAR_LINEAR; + /** mag = linear and min = nearest and mip = none */ + Texture.LINEAR_NEAREST = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_LINEAR_NEAREST; + /** Explicit coordinates mode */ + Texture.EXPLICIT_MODE = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_EXPLICIT_MODE; + /** Spherical coordinates mode */ + Texture.SPHERICAL_MODE = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_SPHERICAL_MODE; + /** Planar coordinates mode */ + Texture.PLANAR_MODE = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_PLANAR_MODE; + /** Cubic coordinates mode */ + Texture.CUBIC_MODE = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_CUBIC_MODE; + /** Projection coordinates mode */ + Texture.PROJECTION_MODE = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_PROJECTION_MODE; + /** Inverse Cubic coordinates mode */ + Texture.SKYBOX_MODE = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_SKYBOX_MODE; + /** Inverse Cubic coordinates mode */ + Texture.INVCUBIC_MODE = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_INVCUBIC_MODE; + /** Equirectangular coordinates mode */ + Texture.EQUIRECTANGULAR_MODE = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_EQUIRECTANGULAR_MODE; + /** Equirectangular Fixed coordinates mode */ + Texture.FIXED_EQUIRECTANGULAR_MODE = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_FIXED_EQUIRECTANGULAR_MODE; + /** Equirectangular Fixed Mirrored coordinates mode */ + Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE; + /** Texture is not repeating outside of 0..1 UVs */ + Texture.CLAMP_ADDRESSMODE = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_CLAMP_ADDRESSMODE; + /** Texture is repeating outside of 0..1 UVs */ + Texture.WRAP_ADDRESSMODE = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_WRAP_ADDRESSMODE; + /** Texture is repeating and mirrored */ + Texture.MIRROR_ADDRESSMODE = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_MIRROR_ADDRESSMODE; + /** + * Gets or sets a boolean which defines if the texture url must be build from the serialized URL instead of just using the name and loading them side by side with the scene file + */ + Texture.UseSerializedUrlIfAny = false; + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], Texture.prototype, "url", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], Texture.prototype, "uOffset", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], Texture.prototype, "vOffset", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], Texture.prototype, "uScale", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], Texture.prototype, "vScale", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], Texture.prototype, "uAng", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], Texture.prototype, "vAng", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], Texture.prototype, "wAng", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], Texture.prototype, "uRotationCenter", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], Texture.prototype, "vRotationCenter", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], Texture.prototype, "wRotationCenter", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], Texture.prototype, "isBlocking", null); + return Texture; +}(_Materials_Textures_baseTexture__WEBPACK_IMPORTED_MODULE_5__["BaseTexture"])); + +// References the dependencies. +_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"]._TextureParser = Texture.Parse; + + +/***/ }), + +/***/ "./Materials/Textures/videoTexture.ts": +/*!********************************************!*\ + !*** ./Materials/Textures/videoTexture.ts ***! + \********************************************/ +/*! exports provided: VideoTexture */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VideoTexture", function() { return VideoTexture; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/tools */ "./Misc/tools.ts"); +/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Misc/logger */ "./Misc/logger.ts"); +/* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Materials/Textures/texture */ "./Materials/Textures/texture.ts"); + + + + + +/** + * If you want to display a video in your scene, this is the special texture for that. + * This special texture works similar to other textures, with the exception of a few parameters. + * @see https://doc.babylonjs.com/how_to/video_texture + */ +var VideoTexture = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](VideoTexture, _super); + /** + * Creates a video texture. + * If you want to display a video in your scene, this is the special texture for that. + * This special texture works similar to other textures, with the exception of a few parameters. + * @see https://doc.babylonjs.com/how_to/video_texture + * @param name optional name, will detect from video source, if not defined + * @param src can be used to provide an url, array of urls or an already setup HTML video element. + * @param scene is obviously the current scene. + * @param generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated). + * @param invertY is false by default but can be used to invert video on Y axis + * @param samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default + * @param settings allows finer control over video usage + */ + function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) { + if (generateMipMaps === void 0) { generateMipMaps = false; } + if (invertY === void 0) { invertY = false; } + if (samplingMode === void 0) { samplingMode = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].TRILINEAR_SAMPLINGMODE; } + if (settings === void 0) { settings = { + autoPlay: true, + loop: true, + autoUpdateTexture: true, + }; } + var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this; + _this._onUserActionRequestedObservable = null; + _this._stillImageCaptured = false; + _this._displayingPosterTexture = false; + _this._createInternalTexture = function () { + if (_this._texture != null) { + if (_this._displayingPosterTexture) { + _this._texture.dispose(); + _this._displayingPosterTexture = false; + } + else { + return; + } + } + if (!_this._engine.needPOTTextures || + (_Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].IsExponentOfTwo(_this.video.videoWidth) && _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].IsExponentOfTwo(_this.video.videoHeight))) { + _this.wrapU = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].WRAP_ADDRESSMODE; + _this.wrapV = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].WRAP_ADDRESSMODE; + } + else { + _this.wrapU = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].CLAMP_ADDRESSMODE; + _this.wrapV = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].CLAMP_ADDRESSMODE; + _this._generateMipMaps = false; + } + _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this.samplingMode); + if (!_this.video.autoplay && !_this._settings.poster) { + var oldHandler_1 = _this.video.onplaying; + var error_1 = false; + var oldMuted_1 = _this.video.muted; + _this.video.muted = true; + _this.video.onplaying = function () { + _this.video.muted = oldMuted_1; + _this.video.onplaying = oldHandler_1; + _this._texture.isReady = true; + _this._updateInternalTexture(); + if (!error_1) { + _this.video.pause(); + } + if (_this.onLoadObservable.hasObservers()) { + _this.onLoadObservable.notifyObservers(_this); + } + }; + var playing = _this.video.play(); + if (playing) { + playing.then(function () { + // Everything is good. + }) + .catch(function () { + error_1 = true; + // On Chrome for instance, new policies might prevent playing without user interaction. + if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) { + _this._onUserActionRequestedObservable.notifyObservers(_this); + } + }); + } + else { + _this.video.onplaying = oldHandler_1; + _this._texture.isReady = true; + _this._updateInternalTexture(); + if (_this.onLoadObservable.hasObservers()) { + _this.onLoadObservable.notifyObservers(_this); + } + } + } + else { + _this._texture.isReady = true; + _this._updateInternalTexture(); + if (_this.onLoadObservable.hasObservers()) { + _this.onLoadObservable.notifyObservers(_this); + } + } + }; + _this.reset = function () { + if (_this._texture == null) { + return; + } + if (!_this._displayingPosterTexture) { + _this._texture.dispose(); + _this._texture = null; + } + }; + _this._updateInternalTexture = function () { + if (_this._texture == null || !_this._texture.isReady) { + return; + } + if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) { + return; + } + if (_this._displayingPosterTexture) { + return; + } + _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY); + }; + _this._engine = _this.getScene().getEngine(); + _this._generateMipMaps = generateMipMaps; + _this._initialSamplingMode = samplingMode; + _this.autoUpdateTexture = settings.autoUpdateTexture; + _this.name = name || _this._getName(src); + _this.video = _this._getVideo(src); + _this._settings = settings; + if (settings.poster) { + _this.video.poster = settings.poster; + } + if (settings.autoPlay !== undefined) { + _this.video.autoplay = settings.autoPlay; + } + if (settings.loop !== undefined) { + _this.video.loop = settings.loop; + } + _this.video.setAttribute("playsinline", ""); + _this.video.addEventListener("paused", _this._updateInternalTexture); + _this.video.addEventListener("seeked", _this._updateInternalTexture); + _this.video.addEventListener("emptied", _this.reset); + _this._createInternalTextureOnEvent = (settings.poster && !settings.autoPlay) ? "play" : "canplay"; + _this.video.addEventListener(_this._createInternalTextureOnEvent, _this._createInternalTexture); + var videoHasEnoughData = (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA); + if (settings.poster && + (!settings.autoPlay || !videoHasEnoughData)) { + _this._texture = _this._engine.createTexture(settings.poster, false, true, scene); + _this._displayingPosterTexture = true; + } + else if (videoHasEnoughData) { + _this._createInternalTexture(); + } + return _this; + } + Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", { + /** + * Event triggerd when a dom action is required by the user to play the video. + * This happens due to recent changes in browser policies preventing video to auto start. + */ + get: function () { + if (!this._onUserActionRequestedObservable) { + this._onUserActionRequestedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); + } + return this._onUserActionRequestedObservable; + }, + enumerable: true, + configurable: true + }); + VideoTexture.prototype._getName = function (src) { + if (src instanceof HTMLVideoElement) { + return src.currentSrc; + } + if (typeof src === "object") { + return src.toString(); + } + return src; + }; + VideoTexture.prototype._getVideo = function (src) { + if (src instanceof HTMLVideoElement) { + _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].SetCorsBehavior(src.currentSrc, src); + return src; + } + var video = document.createElement("video"); + if (typeof src === "string") { + _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].SetCorsBehavior(src, video); + video.src = src; + } + else { + _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].SetCorsBehavior(src[0], video); + src.forEach(function (url) { + var source = document.createElement("source"); + source.src = url; + video.appendChild(source); + }); + } + return video; + }; + /** + * @hidden Internal method to initiate `update`. + */ + VideoTexture.prototype._rebuild = function () { + this.update(); + }; + /** + * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false. + */ + VideoTexture.prototype.update = function () { + if (!this.autoUpdateTexture) { + // Expecting user to call `updateTexture` manually + return; + } + this.updateTexture(true); + }; + /** + * Update Texture in `manual` mode. Does not do anything if not visible or paused. + * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise. + */ + VideoTexture.prototype.updateTexture = function (isVisible) { + if (!isVisible) { + return; + } + if (this.video.paused && this._stillImageCaptured) { + return; + } + this._stillImageCaptured = true; + this._updateInternalTexture(); + }; + /** + * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported. + * @param url New url. + */ + VideoTexture.prototype.updateURL = function (url) { + this.video.src = url; + }; + /** + * Dispose the texture and release its associated resources. + */ + VideoTexture.prototype.dispose = function () { + _super.prototype.dispose.call(this); + if (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(); + }; + /** + * Creates a video texture straight from a stream. + * @param scene Define the scene the texture should be created in + * @param stream Define the stream the texture should be created from + * @returns The created video texture as a promise + */ + VideoTexture.CreateFromStreamAsync = function (scene, stream) { + var video = document.createElement("video"); + video.setAttribute('autoplay', ''); + video.setAttribute('muted', 'true'); + video.setAttribute('playsinline', ''); + video.muted = true; + if (video.mozSrcObject !== undefined) { + // hack for Firefox < 19 + video.mozSrcObject = stream; + } + else { + if (typeof video.srcObject == "object") { + video.srcObject = stream; + } + else { + window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL; + video.src = (window.URL && window.URL.createObjectURL(stream)); + } + } + return new Promise(function (resolve) { + var onPlaying = function () { + resolve(new VideoTexture("video", video, scene, true, true)); + video.removeEventListener("playing", onPlaying); + }; + video.addEventListener("playing", onPlaying); + video.play(); + }); + }; + /** + * Creates a video texture straight from your WebCam video feed. + * @param scene Define the scene the texture should be created in + * @param constraints Define the constraints to use to create the web cam feed from WebRTC + * @param audioConstaints Define the audio constraints to use to create the web cam feed from WebRTC + * @returns The created video texture as a promise + */ + VideoTexture.CreateFromWebCamAsync = function (scene, constraints, audioConstaints) { + var _this = this; + if (audioConstaints === void 0) { audioConstaints = false; } + var constraintsDeviceId; + if (constraints && constraints.deviceId) { + constraintsDeviceId = { + exact: constraints.deviceId, + }; + } + if (navigator.mediaDevices) { + return navigator.mediaDevices.getUserMedia({ + video: constraints, + audio: audioConstaints + }) + .then(function (stream) { + return _this.CreateFromStreamAsync(scene, stream); + }); + } + else { + navigator.getUserMedia = + navigator.getUserMedia || + navigator.webkitGetUserMedia || + navigator.mozGetUserMedia || + navigator.msGetUserMedia; + if (navigator.getUserMedia) { + navigator.getUserMedia({ + video: { + deviceId: constraintsDeviceId, + width: { + min: (constraints && constraints.minWidth) || 256, + max: (constraints && constraints.maxWidth) || 640, + }, + height: { + min: (constraints && constraints.minHeight) || 256, + max: (constraints && constraints.maxHeight) || 480, + }, + }, + audio: audioConstaints + }, function (stream) { + return _this.CreateFromStreamAsync(scene, stream); + }, function (e) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_3__["Logger"].Error(e.name); + }); + } + } + return Promise.reject("No support for userMedia on this device"); + }; + /** + * Creates a video texture straight from your WebCam video feed. + * @param scene Define the scene the texture should be created in + * @param onReady Define a callback to triggered once the texture will be ready + * @param constraints Define the constraints to use to create the web cam feed from WebRTC + * @param audioConstaints Define the audio constraints to use to create the web cam feed from WebRTC + */ + VideoTexture.CreateFromWebCam = function (scene, onReady, constraints, audioConstaints) { + if (audioConstaints === void 0) { audioConstaints = false; } + this.CreateFromWebCamAsync(scene, constraints, audioConstaints) + .then(function (videoTexture) { + if (onReady) { + onReady(videoTexture); + } + }) + .catch(function (err) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_3__["Logger"].Error(err.name); + }); + }; + return VideoTexture; +}(_Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"])); + + + +/***/ }), + +/***/ "./Materials/colorCurves.ts": +/*!**********************************!*\ + !*** ./Materials/colorCurves.ts ***! + \**********************************/ +/*! exports provided: ColorCurves */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorCurves", function() { return ColorCurves; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); + + + +/** + * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT). + * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects. + * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image; + * corresponding to low luminance, medium luminance, and high luminance areas respectively. + */ +var ColorCurves = /** @class */ (function () { + function ColorCurves() { + this._dirty = true; + this._tempColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color4"](0, 0, 0, 0); + this._globalCurve = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color4"](0, 0, 0, 0); + this._highlightsCurve = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color4"](0, 0, 0, 0); + this._midtonesCurve = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color4"](0, 0, 0, 0); + this._shadowsCurve = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color4"](0, 0, 0, 0); + this._positiveCurve = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color4"](0, 0, 0, 0); + this._negativeCurve = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color4"](0, 0, 0, 0); + this._globalHue = 30; + this._globalDensity = 0; + this._globalSaturation = 0; + this._globalExposure = 0; + this._highlightsHue = 30; + this._highlightsDensity = 0; + this._highlightsSaturation = 0; + this._highlightsExposure = 0; + this._midtonesHue = 30; + this._midtonesDensity = 0; + this._midtonesSaturation = 0; + this._midtonesExposure = 0; + this._shadowsHue = 30; + this._shadowsDensity = 0; + this._shadowsSaturation = 0; + this._shadowsExposure = 0; + } + Object.defineProperty(ColorCurves.prototype, "globalHue", { + /** + * Gets the global Hue value. + * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange). + */ + get: function () { + return this._globalHue; + }, + /** + * Sets the global Hue value. + * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange). + */ + set: function (value) { + this._globalHue = value; + this._dirty = true; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ColorCurves.prototype, "globalDensity", { + /** + * Gets the global Density value. + * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect. + * Values less than zero provide a filter of opposite hue. + */ + get: function () { + return this._globalDensity; + }, + /** + * Sets the global Density value. + * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect. + * Values less than zero provide a filter of opposite hue. + */ + set: function (value) { + this._globalDensity = value; + this._dirty = true; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ColorCurves.prototype, "globalSaturation", { + /** + * Gets the global Saturation value. + * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation. + */ + get: function () { + return this._globalSaturation; + }, + /** + * Sets the global Saturation value. + * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation. + */ + set: function (value) { + this._globalSaturation = value; + this._dirty = true; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ColorCurves.prototype, "globalExposure", { + /** + * Gets the global Exposure value. + * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure. + */ + get: function () { + return this._globalExposure; + }, + /** + * Sets the global Exposure value. + * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure. + */ + set: function (value) { + this._globalExposure = value; + this._dirty = true; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ColorCurves.prototype, "highlightsHue", { + /** + * Gets the highlights Hue value. + * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange). + */ + get: function () { + return this._highlightsHue; + }, + /** + * Sets the highlights Hue value. + * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange). + */ + set: function (value) { + this._highlightsHue = value; + this._dirty = true; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ColorCurves.prototype, "highlightsDensity", { + /** + * Gets the highlights Density value. + * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect. + * Values less than zero provide a filter of opposite hue. + */ + get: function () { + return this._highlightsDensity; + }, + /** + * Sets the highlights Density value. + * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect. + * Values less than zero provide a filter of opposite hue. + */ + set: function (value) { + this._highlightsDensity = value; + this._dirty = true; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", { + /** + * Gets the highlights Saturation value. + * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation. + */ + get: function () { + return this._highlightsSaturation; + }, + /** + * Sets the highlights Saturation value. + * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation. + */ + set: function (value) { + this._highlightsSaturation = value; + this._dirty = true; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ColorCurves.prototype, "highlightsExposure", { + /** + * Gets the highlights Exposure value. + * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure. + */ + get: function () { + return this._highlightsExposure; + }, + /** + * Sets the highlights Exposure value. + * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure. + */ + set: function (value) { + this._highlightsExposure = value; + this._dirty = true; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ColorCurves.prototype, "midtonesHue", { + /** + * Gets the midtones Hue value. + * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange). + */ + get: function () { + return this._midtonesHue; + }, + /** + * Sets the midtones Hue value. + * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange). + */ + set: function (value) { + this._midtonesHue = value; + this._dirty = true; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ColorCurves.prototype, "midtonesDensity", { + /** + * Gets the midtones Density value. + * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect. + * Values less than zero provide a filter of opposite hue. + */ + get: function () { + return this._midtonesDensity; + }, + /** + * Sets the midtones Density value. + * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect. + * Values less than zero provide a filter of opposite hue. + */ + set: function (value) { + this._midtonesDensity = value; + this._dirty = true; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", { + /** + * Gets the midtones Saturation value. + * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation. + */ + get: function () { + return this._midtonesSaturation; + }, + /** + * Sets the midtones Saturation value. + * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation. + */ + set: function (value) { + this._midtonesSaturation = value; + this._dirty = true; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ColorCurves.prototype, "midtonesExposure", { + /** + * Gets the midtones Exposure value. + * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure. + */ + get: function () { + return this._midtonesExposure; + }, + /** + * Sets the midtones Exposure value. + * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure. + */ + set: function (value) { + this._midtonesExposure = value; + this._dirty = true; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ColorCurves.prototype, "shadowsHue", { + /** + * Gets the shadows Hue value. + * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange). + */ + get: function () { + return this._shadowsHue; + }, + /** + * Sets the shadows Hue value. + * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange). + */ + set: function (value) { + this._shadowsHue = value; + this._dirty = true; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ColorCurves.prototype, "shadowsDensity", { + /** + * Gets the shadows Density value. + * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect. + * Values less than zero provide a filter of opposite hue. + */ + get: function () { + return this._shadowsDensity; + }, + /** + * Sets the shadows Density value. + * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect. + * Values less than zero provide a filter of opposite hue. + */ + set: function (value) { + this._shadowsDensity = value; + this._dirty = true; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", { + /** + * Gets the shadows Saturation value. + * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation. + */ + get: function () { + return this._shadowsSaturation; + }, + /** + * Sets the shadows Saturation value. + * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation. + */ + set: function (value) { + this._shadowsSaturation = value; + this._dirty = true; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ColorCurves.prototype, "shadowsExposure", { + /** + * Gets the shadows Exposure value. + * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure. + */ + get: function () { + return this._shadowsExposure; + }, + /** + * Sets the shadows Exposure value. + * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure. + */ + set: function (value) { + this._shadowsExposure = value; + this._dirty = true; + }, + enumerable: true, + configurable: true + }); + /** + * Returns the class name + * @returns The class name + */ + ColorCurves.prototype.getClassName = function () { + return "ColorCurves"; + }; + /** + * Binds the color curves to the shader. + * @param colorCurves The color curve to bind + * @param effect The effect to bind to + * @param positiveUniform The positive uniform shader parameter + * @param neutralUniform The neutral uniform shader parameter + * @param negativeUniform The negative uniform shader parameter + */ + ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) { + if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; } + if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; } + if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; } + if (colorCurves._dirty) { + colorCurves._dirty = false; + // Fill in global info. + colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve); + // Compute highlights info. + colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor); + colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve); + // Compute midtones info. + colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor); + colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve); + // Compute shadows info. + colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor); + colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve); + // Compute deltas (neutral is midtones). + colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve); + colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve); + } + if (effect) { + effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a); + effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a); + effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a); + } + }; + /** + * Prepare the list of uniforms associated with the ColorCurves effects. + * @param uniformsList The list of uniforms used in the effect + */ + ColorCurves.PrepareUniforms = function (uniformsList) { + uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative"); + }; + /** + * Returns color grading data based on a hue, density, saturation and exposure value. + * @param filterHue The hue of the color filter. + * @param filterDensity The density of the color filter. + * @param saturation The saturation. + * @param exposure The exposure. + * @param result The result data container. + */ + ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) { + if (hue == null) { + return; + } + hue = ColorCurves.clamp(hue, 0, 360); + density = ColorCurves.clamp(density, -100, 100); + saturation = ColorCurves.clamp(saturation, -100, 100); + exposure = ColorCurves.clamp(exposure, -100, 100); + // Remap the slider/config filter density with non-linear mapping and also scale by half + // so that the maximum filter density is only 50% control. This provides fine control + // for small values and reasonable range. + density = ColorCurves.applyColorGradingSliderNonlinear(density); + density *= 0.5; + exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure); + if (density < 0) { + density *= -1; + hue = (hue + 180) % 360; + } + ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result); + result.scaleToRef(2, result); + result.a = 1 + 0.01 * saturation; + }; + /** + * Takes an input slider value and returns an adjusted value that provides extra control near the centre. + * @param value The input slider value in range [-100,100]. + * @returns Adjusted value. + */ + ColorCurves.applyColorGradingSliderNonlinear = function (value) { + value /= 100; + var x = Math.abs(value); + x = Math.pow(x, 2); + if (value < 0) { + x *= -1; + } + x *= 100; + return x; + }; + /** + * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV). + * @param hue The hue (H) input. + * @param saturation The saturation (S) input. + * @param brightness The brightness (B) input. + * @result An RGBA color represented as Vector4. + */ + ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) { + var h = ColorCurves.clamp(hue, 0, 360); + var s = ColorCurves.clamp(saturation / 100, 0, 1); + var v = ColorCurves.clamp(brightness / 100, 0, 1); + if (s === 0) { + result.r = v; + result.g = v; + result.b = v; + } + else { + // sector 0 to 5 + h /= 60; + var i = Math.floor(h); + // fractional part of h + var f = h - i; + var p = v * (1 - s); + var q = v * (1 - s * f); + var t = v * (1 - s * (1 - f)); + switch (i) { + case 0: + result.r = v; + result.g = t; + result.b = p; + break; + case 1: + result.r = q; + result.g = v; + result.b = p; + break; + case 2: + result.r = p; + result.g = v; + result.b = t; + break; + case 3: + result.r = p; + result.g = q; + result.b = v; + break; + case 4: + result.r = t; + result.g = p; + result.b = v; + break; + default: // case 5: + result.r = v; + result.g = p; + result.b = q; + break; + } + } + result.a = 1; + }; + /** + * Returns a value clamped between min and max + * @param value The value to clamp + * @param min The minimum of value + * @param max The maximum of value + * @returns The clamped value. + */ + ColorCurves.clamp = function (value, min, max) { + return Math.min(Math.max(value, min), max); + }; + /** + * Clones the current color curve instance. + * @return The cloned curves + */ + ColorCurves.prototype.clone = function () { + return _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Clone(function () { return new ColorCurves(); }, this); + }; + /** + * Serializes the current color curve instance to a json representation. + * @return a JSON representation + */ + ColorCurves.prototype.serialize = function () { + return _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(this); + }; + /** + * Parses the color curve from a json representation. + * @param source the JSON source to parse + * @return The parsed curves + */ + ColorCurves.Parse = function (source) { + return _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(function () { return new ColorCurves(); }, source, null, null); + }; + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ColorCurves.prototype, "_globalHue", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ColorCurves.prototype, "_globalDensity", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ColorCurves.prototype, "_globalSaturation", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ColorCurves.prototype, "_globalExposure", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ColorCurves.prototype, "_highlightsHue", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ColorCurves.prototype, "_highlightsDensity", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ColorCurves.prototype, "_highlightsSaturation", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ColorCurves.prototype, "_highlightsExposure", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ColorCurves.prototype, "_midtonesHue", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ColorCurves.prototype, "_midtonesDensity", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ColorCurves.prototype, "_midtonesSaturation", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ColorCurves.prototype, "_midtonesExposure", void 0); + return ColorCurves; +}()); + +// References the dependencies. +_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"]._ColorCurvesParser = ColorCurves.Parse; + + +/***/ }), + +/***/ "./Materials/effect.ts": +/*!*****************************!*\ + !*** ./Materials/effect.ts ***! + \*****************************/ +/*! exports provided: EffectFallbacks, EffectCreationOptions, Effect */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EffectFallbacks", function() { return EffectFallbacks; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EffectCreationOptions", function() { return EffectCreationOptions; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Effect", function() { return Effect; }); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts"); +/* harmony import */ var _Misc_domManagement__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/domManagement */ "./Misc/domManagement.ts"); +/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts"); +/* harmony import */ var _Engines_Processors_shaderProcessor__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Engines/Processors/shaderProcessor */ "./Engines/Processors/shaderProcessor.ts"); + + + + + +/** + * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance. + * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog) + */ +var EffectFallbacks = /** @class */ (function () { + function EffectFallbacks() { + this._defines = {}; + this._currentRank = 32; + this._maxRank = -1; + this._mesh = null; + } + /** + * Removes the fallback from the bound mesh. + */ + EffectFallbacks.prototype.unBindMesh = function () { + this._mesh = null; + }; + /** + * Adds a fallback on the specified property. + * @param rank The rank of the fallback (Lower ranks will be fallbacked to first) + * @param define The name of the define in the shader + */ + EffectFallbacks.prototype.addFallback = function (rank, define) { + if (!this._defines[rank]) { + if (rank < this._currentRank) { + this._currentRank = rank; + } + if (rank > this._maxRank) { + this._maxRank = rank; + } + this._defines[rank] = new Array(); + } + this._defines[rank].push(define); + }; + /** + * Sets the mesh to use CPU skinning when needing to fallback. + * @param rank The rank of the fallback (Lower ranks will be fallbacked to first) + * @param mesh The mesh to use the fallbacks. + */ + EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) { + this._mesh = mesh; + if (rank < this._currentRank) { + this._currentRank = rank; + } + if (rank > this._maxRank) { + this._maxRank = rank; + } + }; + Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", { + /** + * Checks to see if more fallbacks are still availible. + */ + get: function () { + return this._currentRank <= this._maxRank; + }, + enumerable: true, + configurable: true + }); + /** + * Removes the defines that should be removed when falling back. + * @param currentDefines defines the current define statements for the shader. + * @param effect defines the current effect we try to compile + * @returns The resulting defines with defines of the current rank removed. + */ + EffectFallbacks.prototype.reduce = function (currentDefines, effect) { + // First we try to switch to CPU skinning + if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) { + this._mesh.computeBonesUsingShaders = false; + currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0"); + effect._bonesComputationForcedToCPU = true; + var scene = this._mesh.getScene(); + for (var index = 0; index < scene.meshes.length; index++) { + var otherMesh = scene.meshes[index]; + if (!otherMesh.material) { + continue; + } + if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) { + continue; + } + if (otherMesh.material.getEffect() === effect) { + otherMesh.computeBonesUsingShaders = false; + } + else if (otherMesh.subMeshes) { + for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) { + var subMesh = _a[_i]; + var subMeshEffect = subMesh.effect; + if (subMeshEffect === effect) { + otherMesh.computeBonesUsingShaders = false; + break; + } + } + } + } + } + else { + var currentFallbacks = this._defines[this._currentRank]; + if (currentFallbacks) { + for (var index = 0; index < currentFallbacks.length; index++) { + currentDefines = currentDefines.replace("#define " + currentFallbacks[index], ""); + } + } + this._currentRank++; + } + return currentDefines; + }; + return EffectFallbacks; +}()); + +/** + * Options to be used when creating an effect. + */ +var EffectCreationOptions = /** @class */ (function () { + function EffectCreationOptions() { + } + return EffectCreationOptions; +}()); + +/** + * Effect containing vertex and fragment shader that can be executed on an object. + */ +var Effect = /** @class */ (function () { + /** + * Instantiates an effect. + * An effect can be used to create/manage/execute vertex and fragment shaders. + * @param baseName Name of the effect. + * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect. + * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect. + * @param samplers List of sampler variables that will be passed to the shader. + * @param engine Engine to be used to render the effect + * @param defines Define statements to be added to the shader. + * @param fallbacks Possible fallbacks for this effect to improve performance when needed. + * @param onCompiled Callback that will be called when the shader is compiled. + * @param onError Callback that will be called if an error occurs during shader compilation. + * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10}) + */ + function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters, enableMatrixCaching) { + var _this = this; + if (samplers === void 0) { samplers = null; } + if (defines === void 0) { defines = null; } + if (fallbacks === void 0) { fallbacks = null; } + if (onCompiled === void 0) { onCompiled = null; } + if (onError === void 0) { onError = null; } + if (enableMatrixCaching === void 0) { enableMatrixCaching = true; } + /** + * Name of the effect. + */ + this.name = null; + /** + * String container all the define statements that should be set on the shader. + */ + this.defines = ""; + /** + * Callback that will be called when the shader is compiled. + */ + this.onCompiled = null; + /** + * Callback that will be called if an error occurs during shader compilation. + */ + this.onError = null; + /** + * Callback that will be called when effect is bound. + */ + this.onBind = null; + /** + * Unique ID of the effect. + */ + this.uniqueId = 0; + /** + * Observable that will be called when the shader is compiled. + * It is recommended to use executeWhenCompile() or to make sure that scene.isReady() is called to get this observable raised. + */ + this.onCompileObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](); + /** + * Observable that will be called if an error occurs during shader compilation. + */ + this.onErrorObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](); + /** @hidden */ + this._onBindObservable = null; + /** @hidden */ + this._bonesComputationForcedToCPU = false; + this._uniformBuffersNames = {}; + this._samplers = {}; + this._isReady = false; + this._compilationError = ""; + this._uniforms = {}; + /** + * Key for the effect. + * @hidden + */ + this._key = ""; + this._fallbacks = null; + this._vertexSourceCode = ""; + this._fragmentSourceCode = ""; + this._vertexSourceCodeOverride = ""; + this._fragmentSourceCodeOverride = ""; + this._transformFeedbackVaryings = null; + /** + * Compiled shader to webGL program. + * @hidden + */ + this._pipelineContext = null; + this._valueCache = {}; + this.name = baseName; + this._enableMatrixCaching = enableMatrixCaching; + if (attributesNamesOrOptions.attributes) { + var options = attributesNamesOrOptions; + this._engine = uniformsNamesOrEngine; + this._attributesNames = options.attributes; + this._uniformsNames = options.uniformsNames.concat(options.samplers); + this._samplerList = options.samplers.slice(); + this.defines = options.defines; + this.onError = options.onError; + this.onCompiled = options.onCompiled; + this._fallbacks = options.fallbacks; + this._indexParameters = options.indexParameters; + this._transformFeedbackVaryings = options.transformFeedbackVaryings; + if (options.uniformBuffersNames) { + for (var i = 0; i < options.uniformBuffersNames.length; i++) { + this._uniformBuffersNames[options.uniformBuffersNames[i]] = i; + } + } + } + else { + this._engine = engine; + this.defines = (defines == null ? "" : defines); + this._uniformsNames = uniformsNamesOrEngine.concat(samplers); + this._samplerList = samplers ? samplers.slice() : []; + this._attributesNames = attributesNamesOrOptions; + this.onError = onError; + this.onCompiled = onCompiled; + this._indexParameters = indexParameters; + this._fallbacks = fallbacks; + } + this.uniqueId = Effect._uniqueIdSeed++; + var vertexSource; + var fragmentSource; + if (baseName.vertexSource) { + vertexSource = "source:" + baseName.vertexSource; + } + else if (baseName.vertexElement) { + vertexSource = document.getElementById(baseName.vertexElement); + if (!vertexSource) { + vertexSource = baseName.vertexElement; + } + } + else { + vertexSource = baseName.vertex || baseName; + } + if (baseName.fragmentSource) { + fragmentSource = "source:" + baseName.fragmentSource; + } + else if (baseName.fragmentElement) { + fragmentSource = document.getElementById(baseName.fragmentElement); + if (!fragmentSource) { + fragmentSource = baseName.fragmentElement; + } + } + else { + fragmentSource = baseName.fragment || baseName; + } + var processorOptions = { + defines: this.defines.split("\n"), + indexParameters: this._indexParameters, + isFragment: false, + shouldUseHighPrecisionShader: this._engine._shouldUseHighPrecisionShader, + processor: this._engine._shaderProcessor, + supportsUniformBuffers: this._engine.supportsUniformBuffers, + shadersRepository: Effect.ShadersRepository, + includesShadersStore: Effect.IncludesShadersStore, + version: (this._engine.webGLVersion * 100).toString(), + platformName: this._engine.webGLVersion >= 2 ? "WEBGL2" : "WEBGL1" + }; + this._loadVertexShader(vertexSource, function (vertexCode) { + _this._loadFragmentShader(fragmentSource, function (fragmentCode) { + _Engines_Processors_shaderProcessor__WEBPACK_IMPORTED_MODULE_4__["ShaderProcessor"].Process(vertexCode, processorOptions, function (migratedVertexCode) { + processorOptions.isFragment = true; + _Engines_Processors_shaderProcessor__WEBPACK_IMPORTED_MODULE_4__["ShaderProcessor"].Process(fragmentCode, processorOptions, function (migratedFragmentCode) { + _this._useFinalCode(migratedVertexCode, migratedFragmentCode, baseName); + }); + }); + }); + }); + } + Object.defineProperty(Effect.prototype, "onBindObservable", { + /** + * Observable that will be called when effect is bound. + */ + get: function () { + if (!this._onBindObservable) { + this._onBindObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](); + } + return this._onBindObservable; + }, + enumerable: true, + configurable: true + }); + Effect.prototype._useFinalCode = function (migratedVertexCode, migratedFragmentCode, baseName) { + if (baseName) { + var vertex = baseName.vertexElement || baseName.vertex || baseName; + var fragment = baseName.fragmentElement || baseName.fragment || baseName; + this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode; + this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode; + } + else { + this._vertexSourceCode = migratedVertexCode; + this._fragmentSourceCode = migratedFragmentCode; + } + this._prepareEffect(); + }; + Object.defineProperty(Effect.prototype, "key", { + /** + * Unique key for this effect + */ + get: function () { + return this._key; + }, + enumerable: true, + configurable: true + }); + /** + * If the effect has been compiled and prepared. + * @returns if the effect is compiled and prepared. + */ + Effect.prototype.isReady = function () { + if (this._isReady) { + return true; + } + if (this._pipelineContext) { + return this._pipelineContext.isReady; + } + return false; + }; + /** + * The engine the effect was initialized with. + * @returns the engine. + */ + Effect.prototype.getEngine = function () { + return this._engine; + }; + /** + * The pipeline context for this effect + * @returns the associated pipeline context + */ + Effect.prototype.getPipelineContext = function () { + return this._pipelineContext; + }; + /** + * The set of names of attribute variables for the shader. + * @returns An array of attribute names. + */ + Effect.prototype.getAttributesNames = function () { + return this._attributesNames; + }; + /** + * Returns the attribute at the given index. + * @param index The index of the attribute. + * @returns The location of the attribute. + */ + Effect.prototype.getAttributeLocation = function (index) { + return this._attributes[index]; + }; + /** + * Returns the attribute based on the name of the variable. + * @param name of the attribute to look up. + * @returns the attribute location. + */ + Effect.prototype.getAttributeLocationByName = function (name) { + var index = this._attributesNames.indexOf(name); + return this._attributes[index]; + }; + /** + * The number of attributes. + * @returns the numnber of attributes. + */ + Effect.prototype.getAttributesCount = function () { + return this._attributes.length; + }; + /** + * Gets the index of a uniform variable. + * @param uniformName of the uniform to look up. + * @returns the index. + */ + Effect.prototype.getUniformIndex = function (uniformName) { + return this._uniformsNames.indexOf(uniformName); + }; + /** + * Returns the attribute based on the name of the variable. + * @param uniformName of the uniform to look up. + * @returns the location of the uniform. + */ + Effect.prototype.getUniform = function (uniformName) { + return this._uniforms[uniformName]; + }; + /** + * Returns an array of sampler variable names + * @returns The array of sampler variable neames. + */ + Effect.prototype.getSamplers = function () { + return this._samplerList; + }; + /** + * The error from the last compilation. + * @returns the error string. + */ + Effect.prototype.getCompilationError = function () { + return this._compilationError; + }; + /** + * Adds a callback to the onCompiled observable and call the callback imediatly if already ready. + * @param func The callback to be used. + */ + Effect.prototype.executeWhenCompiled = function (func) { + var _this = this; + if (this.isReady()) { + func(this); + return; + } + this.onCompileObservable.add(function (effect) { + func(effect); + }); + if (!this._pipelineContext || this._pipelineContext.isAsync) { + setTimeout(function () { + _this._checkIsReady(); + }, 16); + } + }; + Effect.prototype._checkIsReady = function () { + var _this = this; + if (this.isReady()) { + return; + } + setTimeout(function () { + _this._checkIsReady(); + }, 16); + }; + /** @hidden */ + Effect.prototype._loadVertexShader = function (vertex, callback) { + if (typeof (HTMLElement) !== "undefined") { + // DOM element ? + if (vertex instanceof HTMLElement) { + var vertexCode = _Misc_domManagement__WEBPACK_IMPORTED_MODULE_2__["DomManagement"].GetDOMTextContent(vertex); + callback(vertexCode); + return; + } + } + // Direct source ? + if (vertex.substr(0, 7) === "source:") { + callback(vertex.substr(7)); + return; + } + // Base64 encoded ? + if (vertex.substr(0, 7) === "base64:") { + var vertexBinary = window.atob(vertex.substr(7)); + callback(vertexBinary); + return; + } + // Is in local store ? + if (Effect.ShadersStore[vertex + "VertexShader"]) { + callback(Effect.ShadersStore[vertex + "VertexShader"]); + return; + } + var vertexShaderUrl; + if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) { + vertexShaderUrl = vertex; + } + else { + vertexShaderUrl = Effect.ShadersRepository + vertex; + } + // Vertex shader + this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback); + }; + /** @hidden */ + Effect.prototype._loadFragmentShader = function (fragment, callback) { + if (typeof (HTMLElement) !== "undefined") { + // DOM element ? + if (fragment instanceof HTMLElement) { + var fragmentCode = _Misc_domManagement__WEBPACK_IMPORTED_MODULE_2__["DomManagement"].GetDOMTextContent(fragment); + callback(fragmentCode); + return; + } + } + // Direct source ? + if (fragment.substr(0, 7) === "source:") { + callback(fragment.substr(7)); + return; + } + // Base64 encoded ? + if (fragment.substr(0, 7) === "base64:") { + var fragmentBinary = window.atob(fragment.substr(7)); + callback(fragmentBinary); + return; + } + // Is in local store ? + if (Effect.ShadersStore[fragment + "PixelShader"]) { + callback(Effect.ShadersStore[fragment + "PixelShader"]); + return; + } + if (Effect.ShadersStore[fragment + "FragmentShader"]) { + callback(Effect.ShadersStore[fragment + "FragmentShader"]); + return; + } + var fragmentShaderUrl; + if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) { + fragmentShaderUrl = fragment; + } + else { + fragmentShaderUrl = Effect.ShadersRepository + fragment; + } + // Fragment shader + this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback); + }; + /** @hidden */ + Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) { + // Rebuild shaders source code + var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : ""; + var prefix = shaderVersion + (defines ? defines + "\n" : ""); + vertexCode = prefix + vertexCode; + fragmentCode = prefix + fragmentCode; + // Number lines of shaders source code + var i = 2; + var regex = /\n/gm; + var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; }); + i = 2; + var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; }); + // Dump shaders name and formatted source code + if (this.name.vertexElement) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_3__["Logger"].Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode); + _Misc_logger__WEBPACK_IMPORTED_MODULE_3__["Logger"].Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode); + } + else if (this.name.vertex) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_3__["Logger"].Error("Vertex shader: " + this.name.vertex + formattedVertexCode); + _Misc_logger__WEBPACK_IMPORTED_MODULE_3__["Logger"].Error("Fragment shader: " + this.name.fragment + formattedFragmentCode); + } + else { + _Misc_logger__WEBPACK_IMPORTED_MODULE_3__["Logger"].Error("Vertex shader: " + this.name + formattedVertexCode); + _Misc_logger__WEBPACK_IMPORTED_MODULE_3__["Logger"].Error("Fragment shader: " + this.name + formattedFragmentCode); + } + }; + /** + * Recompiles the webGL program + * @param vertexSourceCode The source code for the vertex shader. + * @param fragmentSourceCode The source code for the fragment shader. + * @param onCompiled Callback called when completed. + * @param onError Callback called on error. + * @hidden + */ + Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) { + var _this = this; + this._isReady = false; + this._vertexSourceCodeOverride = vertexSourceCode; + this._fragmentSourceCodeOverride = fragmentSourceCode; + this.onError = function (effect, error) { + if (onError) { + onError(error); + } + }; + this.onCompiled = function () { + var scenes = _this.getEngine().scenes; + for (var i = 0; i < scenes.length; i++) { + scenes[i].markAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].MATERIAL_AllDirtyFlag); + } + _this._pipelineContext._handlesSpectorRebuildCallback(onCompiled); + }; + this._fallbacks = null; + this._prepareEffect(); + }; + /** + * Prepares the effect + * @hidden + */ + Effect.prototype._prepareEffect = function () { + var _this = this; + var attributesNames = this._attributesNames; + var defines = this.defines; + var fallbacks = this._fallbacks; + this._valueCache = {}; + var previousPipelineContext = this._pipelineContext; + try { + var engine_1 = this._engine; + this._pipelineContext = engine_1.createPipelineContext(); + var rebuildRebind = this._rebuildProgram.bind(this); + if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) { + engine_1._preparePipelineContext(this._pipelineContext, this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, true, rebuildRebind, null, this._transformFeedbackVaryings); + } + else { + engine_1._preparePipelineContext(this._pipelineContext, this._vertexSourceCode, this._fragmentSourceCode, false, rebuildRebind, defines, this._transformFeedbackVaryings); + } + engine_1._executeWhenRenderingStateIsCompiled(this._pipelineContext, function () { + if (engine_1.supportsUniformBuffers) { + for (var name in _this._uniformBuffersNames) { + _this.bindUniformBlock(name, _this._uniformBuffersNames[name]); + } + } + var uniforms = engine_1.getUniforms(_this._pipelineContext, _this._uniformsNames); + uniforms.forEach(function (uniform, index) { + _this._uniforms[_this._uniformsNames[index]] = uniform; + }); + _this._attributes = engine_1.getAttributes(_this._pipelineContext, attributesNames); + var index; + for (index = 0; index < _this._samplerList.length; index++) { + var sampler = _this.getUniform(_this._samplerList[index]); + if (sampler == null) { + _this._samplerList.splice(index, 1); + index--; + } + } + _this._samplerList.forEach(function (name, index) { + _this._samplers[name] = index; + }); + engine_1.bindSamplers(_this); + _this._compilationError = ""; + _this._isReady = true; + if (_this.onCompiled) { + _this.onCompiled(_this); + } + _this.onCompileObservable.notifyObservers(_this); + _this.onCompileObservable.clear(); + // Unbind mesh reference in fallbacks + if (_this._fallbacks) { + _this._fallbacks.unBindMesh(); + } + if (previousPipelineContext) { + _this.getEngine()._deletePipelineContext(previousPipelineContext); + } + }); + if (this._pipelineContext.isAsync) { + this._checkIsReady(); + } + } + catch (e) { + this._compilationError = e.message; + // Let's go through fallbacks then + _Misc_logger__WEBPACK_IMPORTED_MODULE_3__["Logger"].Error("Unable to compile effect:"); + _Misc_logger__WEBPACK_IMPORTED_MODULE_3__["Logger"].Error("Uniforms: " + this._uniformsNames.map(function (uniform) { + return " " + uniform; + })); + _Misc_logger__WEBPACK_IMPORTED_MODULE_3__["Logger"].Error("Attributes: " + attributesNames.map(function (attribute) { + return " " + attribute; + })); + _Misc_logger__WEBPACK_IMPORTED_MODULE_3__["Logger"].Error("Error: " + this._compilationError); + if (previousPipelineContext) { + this._pipelineContext = previousPipelineContext; + this._isReady = true; + if (this.onError) { + this.onError(this, this._compilationError); + } + this.onErrorObservable.notifyObservers(this); + } + if (fallbacks && fallbacks.isMoreFallbacks) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_3__["Logger"].Error("Trying next fallback."); + this.defines = fallbacks.reduce(this.defines, this); + this._prepareEffect(); + } + else { // Sorry we did everything we can + if (this.onError) { + this.onError(this, this._compilationError); + } + this.onErrorObservable.notifyObservers(this); + this.onErrorObservable.clear(); + // Unbind mesh reference in fallbacks + if (this._fallbacks) { + this._fallbacks.unBindMesh(); + } + } + } + }; + Object.defineProperty(Effect.prototype, "isSupported", { + /** + * Checks if the effect is supported. (Must be called after compilation) + */ + get: function () { + return this._compilationError === ""; + }, + enumerable: true, + configurable: true + }); + /** + * Binds a texture to the engine to be used as output of the shader. + * @param channel Name of the output variable. + * @param texture Texture to bind. + * @hidden + */ + Effect.prototype._bindTexture = function (channel, texture) { + this._engine._bindTexture(this._samplers[channel], texture); + }; + /** + * Sets a texture on the engine to be used in the shader. + * @param channel Name of the sampler variable. + * @param texture Texture to set. + */ + Effect.prototype.setTexture = function (channel, texture) { + this._engine.setTexture(this._samplers[channel], this._uniforms[channel], texture); + }; + /** + * Sets a depth stencil texture from a render target on the engine to be used in the shader. + * @param channel Name of the sampler variable. + * @param texture Texture to set. + */ + Effect.prototype.setDepthStencilTexture = function (channel, texture) { + this._engine.setDepthStencilTexture(this._samplers[channel], this._uniforms[channel], texture); + }; + /** + * Sets an array of textures on the engine to be used in the shader. + * @param channel Name of the variable. + * @param textures Textures to set. + */ + Effect.prototype.setTextureArray = function (channel, textures) { + var exName = channel + "Ex"; + if (this._samplerList.indexOf(exName) === -1) { + var initialPos = this._samplers[channel]; + for (var index = 1; index < textures.length; index++) { + this._samplerList.splice(initialPos + index, 0, exName); + this._samplers[exName] = initialPos + index; + } + } + this._engine.setTextureArray(this._samplers[channel], this._uniforms[channel], textures); + }; + /** + * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline) + * @param channel Name of the sampler variable. + * @param postProcess Post process to get the input texture from. + */ + Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) { + this._engine.setTextureFromPostProcess(this._samplers[channel], postProcess); + }; + /** + * (Warning! setTextureFromPostProcessOutput may be desired instead) + * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput) + * @param channel Name of the sampler variable. + * @param postProcess Post process to get the output texture from. + */ + Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) { + this._engine.setTextureFromPostProcessOutput(this._samplers[channel], postProcess); + }; + /** @hidden */ + Effect.prototype._cacheMatrix = function (uniformName, matrix) { + var cache = this._valueCache[uniformName]; + var flag = matrix.updateFlag; + if (cache !== undefined && cache === flag) { + return false; + } + this._valueCache[uniformName] = flag; + return true; + }; + /** @hidden */ + Effect.prototype._cacheFloat2 = function (uniformName, x, y) { + var cache = this._valueCache[uniformName]; + if (!cache) { + cache = [x, y]; + this._valueCache[uniformName] = cache; + return true; + } + var changed = false; + if (cache[0] !== x) { + cache[0] = x; + changed = true; + } + if (cache[1] !== y) { + cache[1] = y; + changed = true; + } + return changed; + }; + /** @hidden */ + Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) { + var cache = this._valueCache[uniformName]; + if (!cache) { + cache = [x, y, z]; + this._valueCache[uniformName] = cache; + return true; + } + var changed = false; + if (cache[0] !== x) { + cache[0] = x; + changed = true; + } + if (cache[1] !== y) { + cache[1] = y; + changed = true; + } + if (cache[2] !== z) { + cache[2] = z; + changed = true; + } + return changed; + }; + /** @hidden */ + Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) { + var cache = this._valueCache[uniformName]; + if (!cache) { + cache = [x, y, z, w]; + this._valueCache[uniformName] = cache; + return true; + } + var changed = false; + if (cache[0] !== x) { + cache[0] = x; + changed = true; + } + if (cache[1] !== y) { + cache[1] = y; + changed = true; + } + if (cache[2] !== z) { + cache[2] = z; + changed = true; + } + if (cache[3] !== w) { + cache[3] = w; + changed = true; + } + return changed; + }; + /** + * Binds a buffer to a uniform. + * @param buffer Buffer to bind. + * @param name Name of the uniform variable to bind to. + */ + Effect.prototype.bindUniformBuffer = function (buffer, name) { + var bufferName = this._uniformBuffersNames[name]; + if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) { + return; + } + Effect._baseCache[bufferName] = buffer; + this._engine.bindUniformBufferBase(buffer, bufferName); + }; + /** + * Binds block to a uniform. + * @param blockName Name of the block to bind. + * @param index Index to bind. + */ + Effect.prototype.bindUniformBlock = function (blockName, index) { + this._engine.bindUniformBlock(this._pipelineContext, blockName, index); + }; + /** + * Sets an interger value on a uniform variable. + * @param uniformName Name of the variable. + * @param value Value to be set. + * @returns this effect. + */ + Effect.prototype.setInt = function (uniformName, value) { + var cache = this._valueCache[uniformName]; + if (cache !== undefined && cache === value) { + return this; + } + this._valueCache[uniformName] = value; + this._engine.setInt(this._uniforms[uniformName], value); + return this; + }; + /** + * Sets an int array on a uniform variable. + * @param uniformName Name of the variable. + * @param array array to be set. + * @returns this effect. + */ + Effect.prototype.setIntArray = function (uniformName, array) { + this._valueCache[uniformName] = null; + this._engine.setIntArray(this._uniforms[uniformName], array); + return this; + }; + /** + * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + * @returns this effect. + */ + Effect.prototype.setIntArray2 = function (uniformName, array) { + this._valueCache[uniformName] = null; + this._engine.setIntArray2(this._uniforms[uniformName], array); + return this; + }; + /** + * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + * @returns this effect. + */ + Effect.prototype.setIntArray3 = function (uniformName, array) { + this._valueCache[uniformName] = null; + this._engine.setIntArray3(this._uniforms[uniformName], array); + return this; + }; + /** + * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + * @returns this effect. + */ + Effect.prototype.setIntArray4 = function (uniformName, array) { + this._valueCache[uniformName] = null; + this._engine.setIntArray4(this._uniforms[uniformName], array); + return this; + }; + /** + * Sets an float array on a uniform variable. + * @param uniformName Name of the variable. + * @param array array to be set. + * @returns this effect. + */ + Effect.prototype.setFloatArray = function (uniformName, array) { + this._valueCache[uniformName] = null; + this._engine.setFloatArray(this._uniforms[uniformName], array); + return this; + }; + /** + * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + * @returns this effect. + */ + Effect.prototype.setFloatArray2 = function (uniformName, array) { + this._valueCache[uniformName] = null; + this._engine.setFloatArray2(this._uniforms[uniformName], array); + return this; + }; + /** + * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + * @returns this effect. + */ + Effect.prototype.setFloatArray3 = function (uniformName, array) { + this._valueCache[uniformName] = null; + this._engine.setFloatArray3(this._uniforms[uniformName], array); + return this; + }; + /** + * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + * @returns this effect. + */ + Effect.prototype.setFloatArray4 = function (uniformName, array) { + this._valueCache[uniformName] = null; + this._engine.setFloatArray4(this._uniforms[uniformName], array); + return this; + }; + /** + * Sets an array on a uniform variable. + * @param uniformName Name of the variable. + * @param array array to be set. + * @returns this effect. + */ + Effect.prototype.setArray = function (uniformName, array) { + this._valueCache[uniformName] = null; + this._engine.setArray(this._uniforms[uniformName], array); + return this; + }; + /** + * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + * @returns this effect. + */ + Effect.prototype.setArray2 = function (uniformName, array) { + this._valueCache[uniformName] = null; + this._engine.setArray2(this._uniforms[uniformName], array); + return this; + }; + /** + * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + * @returns this effect. + */ + Effect.prototype.setArray3 = function (uniformName, array) { + this._valueCache[uniformName] = null; + this._engine.setArray3(this._uniforms[uniformName], array); + return this; + }; + /** + * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader) + * @param uniformName Name of the variable. + * @param array array to be set. + * @returns this effect. + */ + Effect.prototype.setArray4 = function (uniformName, array) { + this._valueCache[uniformName] = null; + this._engine.setArray4(this._uniforms[uniformName], array); + return this; + }; + /** + * Sets matrices on a uniform variable. + * @param uniformName Name of the variable. + * @param matrices matrices to be set. + * @returns this effect. + */ + Effect.prototype.setMatrices = function (uniformName, matrices) { + if (!matrices) { + return this; + } + this._valueCache[uniformName] = null; + this._engine.setMatrices(this._uniforms[uniformName], matrices); + return this; + }; + /** + * Sets matrix on a uniform variable. + * @param uniformName Name of the variable. + * @param matrix matrix to be set. + * @returns this effect. + */ + Effect.prototype.setMatrix = function (uniformName, matrix) { + if (!this._enableMatrixCaching || this._cacheMatrix(uniformName, matrix)) { + this._engine.setMatrix(this._uniforms[uniformName], matrix); + } + return this; + }; + /** + * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix) + * @param uniformName Name of the variable. + * @param matrix matrix to be set. + * @returns this effect. + */ + Effect.prototype.setMatrix3x3 = function (uniformName, matrix) { + this._valueCache[uniformName] = null; + this._engine.setMatrix3x3(this._uniforms[uniformName], matrix); + return this; + }; + /** + * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix) + * @param uniformName Name of the variable. + * @param matrix matrix to be set. + * @returns this effect. + */ + Effect.prototype.setMatrix2x2 = function (uniformName, matrix) { + this._valueCache[uniformName] = null; + this._engine.setMatrix2x2(this._uniforms[uniformName], matrix); + return this; + }; + /** + * Sets a float on a uniform variable. + * @param uniformName Name of the variable. + * @param value value to be set. + * @returns this effect. + */ + Effect.prototype.setFloat = function (uniformName, value) { + var cache = this._valueCache[uniformName]; + if (cache !== undefined && cache === value) { + return this; + } + this._valueCache[uniformName] = value; + this._engine.setFloat(this._uniforms[uniformName], value); + return this; + }; + /** + * Sets a boolean on a uniform variable. + * @param uniformName Name of the variable. + * @param bool value to be set. + * @returns this effect. + */ + Effect.prototype.setBool = function (uniformName, bool) { + var cache = this._valueCache[uniformName]; + if (cache !== undefined && cache === bool) { + return this; + } + this._valueCache[uniformName] = bool; + this._engine.setBool(this._uniforms[uniformName], bool ? 1 : 0); + return this; + }; + /** + * Sets a Vector2 on a uniform variable. + * @param uniformName Name of the variable. + * @param vector2 vector2 to be set. + * @returns this effect. + */ + Effect.prototype.setVector2 = function (uniformName, vector2) { + if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) { + this._engine.setFloat2(this._uniforms[uniformName], vector2.x, vector2.y); + } + return this; + }; + /** + * Sets a float2 on a uniform variable. + * @param uniformName Name of the variable. + * @param x First float in float2. + * @param y Second float in float2. + * @returns this effect. + */ + Effect.prototype.setFloat2 = function (uniformName, x, y) { + if (this._cacheFloat2(uniformName, x, y)) { + this._engine.setFloat2(this._uniforms[uniformName], x, y); + } + return this; + }; + /** + * Sets a Vector3 on a uniform variable. + * @param uniformName Name of the variable. + * @param vector3 Value to be set. + * @returns this effect. + */ + Effect.prototype.setVector3 = function (uniformName, vector3) { + if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) { + this._engine.setFloat3(this._uniforms[uniformName], vector3.x, vector3.y, vector3.z); + } + return this; + }; + /** + * Sets a float3 on a uniform variable. + * @param uniformName Name of the variable. + * @param x First float in float3. + * @param y Second float in float3. + * @param z Third float in float3. + * @returns this effect. + */ + Effect.prototype.setFloat3 = function (uniformName, x, y, z) { + if (this._cacheFloat3(uniformName, x, y, z)) { + this._engine.setFloat3(this._uniforms[uniformName], x, y, z); + } + return this; + }; + /** + * Sets a Vector4 on a uniform variable. + * @param uniformName Name of the variable. + * @param vector4 Value to be set. + * @returns this effect. + */ + Effect.prototype.setVector4 = function (uniformName, vector4) { + if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) { + this._engine.setFloat4(this._uniforms[uniformName], vector4.x, vector4.y, vector4.z, vector4.w); + } + return this; + }; + /** + * Sets a float4 on a uniform variable. + * @param uniformName Name of the variable. + * @param x First float in float4. + * @param y Second float in float4. + * @param z Third float in float4. + * @param w Fourth float in float4. + * @returns this effect. + */ + Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) { + if (this._cacheFloat4(uniformName, x, y, z, w)) { + this._engine.setFloat4(this._uniforms[uniformName], x, y, z, w); + } + return this; + }; + /** + * Sets a Color3 on a uniform variable. + * @param uniformName Name of the variable. + * @param color3 Value to be set. + * @returns this effect. + */ + Effect.prototype.setColor3 = function (uniformName, color3) { + if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) { + this._engine.setColor3(this._uniforms[uniformName], color3); + } + return this; + }; + /** + * Sets a Color4 on a uniform variable. + * @param uniformName Name of the variable. + * @param color3 Value to be set. + * @param alpha Alpha value to be set. + * @returns this effect. + */ + Effect.prototype.setColor4 = function (uniformName, color3, alpha) { + if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) { + this._engine.setColor4(this._uniforms[uniformName], color3, alpha); + } + return this; + }; + /** + * Sets a Color4 on a uniform variable + * @param uniformName defines the name of the variable + * @param color4 defines the value to be set + * @returns this effect. + */ + Effect.prototype.setDirectColor4 = function (uniformName, color4) { + if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) { + this._engine.setDirectColor4(this._uniforms[uniformName], color4); + } + return this; + }; + /** Release all associated resources */ + Effect.prototype.dispose = function () { + this._engine._releaseEffect(this); + }; + /** + * This function will add a new shader to the shader store + * @param name the name of the shader + * @param pixelShader optional pixel shader content + * @param vertexShader optional vertex shader content + */ + Effect.RegisterShader = function (name, pixelShader, vertexShader) { + if (pixelShader) { + Effect.ShadersStore[name + "PixelShader"] = pixelShader; + } + if (vertexShader) { + Effect.ShadersStore[name + "VertexShader"] = vertexShader; + } + }; + /** + * Resets the cache of effects. + */ + Effect.ResetCache = function () { + Effect._baseCache = {}; + }; + /** + * Gets or sets the relative url used to load shaders if using the engine in non-minified mode + */ + Effect.ShadersRepository = "src/Shaders/"; + Effect._uniqueIdSeed = 0; + Effect._baseCache = {}; + /** + * Store of each shader (The can be looked up using effect.key) + */ + Effect.ShadersStore = {}; + /** + * Store of each included file for a shader (The can be looked up using effect.key) + */ + Effect.IncludesShadersStore = {}; + return Effect; +}()); + + + +/***/ }), + +/***/ "./Materials/fresnelParameters.ts": +/*!****************************************!*\ + !*** ./Materials/fresnelParameters.ts ***! + \****************************************/ +/*! exports provided: FresnelParameters */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FresnelParameters", function() { return FresnelParameters; }); +/* harmony import */ var _Misc_deepCopier__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/deepCopier */ "./Misc/deepCopier.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Engines/engine */ "./Engines/engine.ts"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts"); + + + + + +/** + * This represents all the required information to add a fresnel effect on a material: + * @see http://doc.babylonjs.com/how_to/how_to_use_fresnelparameters + */ +var FresnelParameters = /** @class */ (function () { + function FresnelParameters() { + this._isEnabled = true; + /** + * Define the color used on edges (grazing angle) + */ + this.leftColor = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Color3"].White(); + /** + * Define the color used on center + */ + this.rightColor = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Color3"].Black(); + /** + * Define bias applied to computed fresnel term + */ + this.bias = 0; + /** + * Defined the power exponent applied to fresnel term + */ + this.power = 1; + } + Object.defineProperty(FresnelParameters.prototype, "isEnabled", { + /** + * Define if the fresnel effect is enable or not. + */ + get: function () { + return this._isEnabled; + }, + set: function (value) { + if (this._isEnabled === value) { + return; + } + this._isEnabled = value; + _Engines_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].MarkAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_4__["Constants"].MATERIAL_FresnelDirtyFlag | _Engines_constants__WEBPACK_IMPORTED_MODULE_4__["Constants"].MATERIAL_MiscDirtyFlag); + }, + enumerable: true, + configurable: true + }); + /** + * Clones the current fresnel and its valuues + * @returns a clone fresnel configuration + */ + FresnelParameters.prototype.clone = function () { + var newFresnelParameters = new FresnelParameters(); + _Misc_deepCopier__WEBPACK_IMPORTED_MODULE_0__["DeepCopier"].DeepCopy(this, newFresnelParameters); + return newFresnelParameters; + }; + /** + * Serializes the current fresnel parameters to a JSON representation. + * @return the JSON serialization + */ + FresnelParameters.prototype.serialize = function () { + var serializationObject = {}; + serializationObject.isEnabled = this.isEnabled; + serializationObject.leftColor = this.leftColor.asArray(); + serializationObject.rightColor = this.rightColor.asArray(); + serializationObject.bias = this.bias; + serializationObject.power = this.power; + return serializationObject; + }; + /** + * Parse a JSON object and deserialize it to a new Fresnel parameter object. + * @param parsedFresnelParameters Define the JSON representation + * @returns the parsed parameters + */ + FresnelParameters.Parse = function (parsedFresnelParameters) { + var fresnelParameters = new FresnelParameters(); + fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled; + fresnelParameters.leftColor = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Color3"].FromArray(parsedFresnelParameters.leftColor); + fresnelParameters.rightColor = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Color3"].FromArray(parsedFresnelParameters.rightColor); + fresnelParameters.bias = parsedFresnelParameters.bias; + fresnelParameters.power = parsedFresnelParameters.power || 1.0; + return fresnelParameters; + }; + return FresnelParameters; +}()); + +// References the dependencies. +_Misc_decorators__WEBPACK_IMPORTED_MODULE_3__["SerializationHelper"]._FresnelParametersParser = FresnelParameters.Parse; + + +/***/ }), + +/***/ "./Materials/imageProcessingConfiguration.ts": +/*!***************************************************!*\ + !*** ./Materials/imageProcessingConfiguration.ts ***! + \***************************************************/ +/*! exports provided: ImageProcessingConfigurationDefines, ImageProcessingConfiguration */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ImageProcessingConfigurationDefines", function() { return ImageProcessingConfigurationDefines; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ImageProcessingConfiguration", function() { return ImageProcessingConfiguration; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Misc/tools */ "./Misc/tools.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Materials_materialDefines__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Materials/materialDefines */ "./Materials/materialDefines.ts"); +/* harmony import */ var _Materials_colorCurves__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Materials/colorCurves */ "./Materials/colorCurves.ts"); + + + + + + + +/** + * @hidden + */ +var ImageProcessingConfigurationDefines = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ImageProcessingConfigurationDefines, _super); + function ImageProcessingConfigurationDefines() { + var _this = _super.call(this) || this; + _this.IMAGEPROCESSING = false; + _this.VIGNETTE = false; + _this.VIGNETTEBLENDMODEMULTIPLY = false; + _this.VIGNETTEBLENDMODEOPAQUE = false; + _this.TONEMAPPING = false; + _this.TONEMAPPING_ACES = false; + _this.CONTRAST = false; + _this.COLORCURVES = false; + _this.COLORGRADING = false; + _this.COLORGRADING3D = false; + _this.SAMPLER3DGREENDEPTH = false; + _this.SAMPLER3DBGRMAP = false; + _this.IMAGEPROCESSINGPOSTPROCESS = false; + _this.EXPOSURE = false; + _this.rebuild(); + return _this; + } + return ImageProcessingConfigurationDefines; +}(_Materials_materialDefines__WEBPACK_IMPORTED_MODULE_5__["MaterialDefines"])); + +/** + * This groups together the common properties used for image processing either in direct forward pass + * or through post processing effect depending on the use of the image processing pipeline in your scene + * or not. + */ +var ImageProcessingConfiguration = /** @class */ (function () { + function ImageProcessingConfiguration() { + /** + * Color curves setup used in the effect if colorCurvesEnabled is set to true + */ + this.colorCurves = new _Materials_colorCurves__WEBPACK_IMPORTED_MODULE_6__["ColorCurves"](); + this._colorCurvesEnabled = false; + this._colorGradingEnabled = false; + this._colorGradingWithGreenDepth = true; + this._colorGradingBGR = true; + /** @hidden */ + this._exposure = 1.0; + this._toneMappingEnabled = false; + this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD; + this._contrast = 1.0; + /** + * Vignette stretch size. + */ + this.vignetteStretch = 0; + /** + * Vignette centre X Offset. + */ + this.vignetteCentreX = 0; + /** + * Vignette centre Y Offset. + */ + this.vignetteCentreY = 0; + /** + * Vignette weight or intensity of the vignette effect. + */ + this.vignetteWeight = 1.5; + /** + * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode) + * if vignetteEnabled is set to true. + */ + this.vignetteColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Color4"](0, 0, 0, 0); + /** + * Camera field of view used by the Vignette effect. + */ + this.vignetteCameraFov = 0.5; + this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY; + this._vignetteEnabled = false; + this._applyByPostProcess = false; + this._isEnabled = true; + /** + * An event triggered when the configuration changes and requires Shader to Update some parameters. + */ + this.onUpdateParameters = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); + } + Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", { + /** + * Gets wether the color curves effect is enabled. + */ + get: function () { + return this._colorCurvesEnabled; + }, + /** + * Sets wether the color curves effect is enabled. + */ + set: function (value) { + if (this._colorCurvesEnabled === value) { + return; + } + this._colorCurvesEnabled = value; + this._updateParameters(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingTexture", { + /** + * Color grading LUT texture used in the effect if colorGradingEnabled is set to true + */ + get: function () { + return this._colorGradingTexture; + }, + /** + * Color grading LUT texture used in the effect if colorGradingEnabled is set to true + */ + set: function (value) { + if (this._colorGradingTexture === value) { + return; + } + this._colorGradingTexture = value; + this._updateParameters(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", { + /** + * Gets wether the color grading effect is enabled. + */ + get: function () { + return this._colorGradingEnabled; + }, + /** + * Sets wether the color grading effect is enabled. + */ + set: function (value) { + if (this._colorGradingEnabled === value) { + return; + } + this._colorGradingEnabled = value; + this._updateParameters(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", { + /** + * Gets wether the color grading effect is using a green depth for the 3d Texture. + */ + get: function () { + return this._colorGradingWithGreenDepth; + }, + /** + * Sets wether the color grading effect is using a green depth for the 3d Texture. + */ + set: function (value) { + if (this._colorGradingWithGreenDepth === value) { + return; + } + this._colorGradingWithGreenDepth = value; + this._updateParameters(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", { + /** + * Gets wether the color grading texture contains BGR values. + */ + get: function () { + return this._colorGradingBGR; + }, + /** + * Sets wether the color grading texture contains BGR values. + */ + set: function (value) { + if (this._colorGradingBGR === value) { + return; + } + this._colorGradingBGR = value; + this._updateParameters(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", { + /** + * Gets the Exposure used in the effect. + */ + get: function () { + return this._exposure; + }, + /** + * Sets the Exposure used in the effect. + */ + set: function (value) { + if (this._exposure === value) { + return; + } + this._exposure = value; + this._updateParameters(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", { + /** + * Gets wether the tone mapping effect is enabled. + */ + get: function () { + return this._toneMappingEnabled; + }, + /** + * Sets wether the tone mapping effect is enabled. + */ + set: function (value) { + if (this._toneMappingEnabled === value) { + return; + } + this._toneMappingEnabled = value; + this._updateParameters(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", { + /** + * Gets the type of tone mapping effect. + */ + get: function () { + return this._toneMappingType; + }, + /** + * Sets the type of tone mapping effect used in BabylonJS. + */ + set: function (value) { + if (this._toneMappingType === value) { + return; + } + this._toneMappingType = value; + this._updateParameters(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", { + /** + * Gets the contrast used in the effect. + */ + get: function () { + return this._contrast; + }, + /** + * Sets the contrast used in the effect. + */ + set: function (value) { + if (this._contrast === value) { + return; + } + this._contrast = value; + this._updateParameters(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", { + /** + * Gets the vignette blend mode allowing different kind of effect. + */ + get: function () { + return this._vignetteBlendMode; + }, + /** + * Sets the vignette blend mode allowing different kind of effect. + */ + set: function (value) { + if (this._vignetteBlendMode === value) { + return; + } + this._vignetteBlendMode = value; + this._updateParameters(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", { + /** + * Gets wether the vignette effect is enabled. + */ + get: function () { + return this._vignetteEnabled; + }, + /** + * Sets wether the vignette effect is enabled. + */ + set: function (value) { + if (this._vignetteEnabled === value) { + return; + } + this._vignetteEnabled = value; + this._updateParameters(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", { + /** + * Gets wether the image processing is applied through a post process or not. + */ + get: function () { + return this._applyByPostProcess; + }, + /** + * Sets wether the image processing is applied through a post process or not. + */ + set: function (value) { + if (this._applyByPostProcess === value) { + return; + } + this._applyByPostProcess = value; + this._updateParameters(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", { + /** + * Gets wether the image processing is enabled or not. + */ + get: function () { + return this._isEnabled; + }, + /** + * Sets wether the image processing is enabled or not. + */ + set: function (value) { + if (this._isEnabled === value) { + return; + } + this._isEnabled = value; + this._updateParameters(); + }, + enumerable: true, + configurable: true + }); + /** + * Method called each time the image processing information changes requires to recompile the effect. + */ + ImageProcessingConfiguration.prototype._updateParameters = function () { + this.onUpdateParameters.notifyObservers(this); + }; + /** + * Gets the current class name. + * @return "ImageProcessingConfiguration" + */ + ImageProcessingConfiguration.prototype.getClassName = function () { + return "ImageProcessingConfiguration"; + }; + /** + * Prepare the list of uniforms associated with the Image Processing effects. + * @param uniforms The list of uniforms used in the effect + * @param defines the list of defines currently in use + */ + ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) { + if (defines.EXPOSURE) { + uniforms.push("exposureLinear"); + } + if (defines.CONTRAST) { + uniforms.push("contrast"); + } + if (defines.COLORGRADING) { + uniforms.push("colorTransformSettings"); + } + if (defines.VIGNETTE) { + uniforms.push("vInverseScreenSize"); + uniforms.push("vignetteSettings1"); + uniforms.push("vignetteSettings2"); + } + if (defines.COLORCURVES) { + _Materials_colorCurves__WEBPACK_IMPORTED_MODULE_6__["ColorCurves"].PrepareUniforms(uniforms); + } + }; + /** + * Prepare the list of samplers associated with the Image Processing effects. + * @param samplersList The list of uniforms used in the effect + * @param defines the list of defines currently in use + */ + ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) { + if (defines.COLORGRADING) { + samplersList.push("txColorTransform"); + } + }; + /** + * Prepare the list of defines associated to the shader. + * @param defines the list of defines to complete + * @param forPostProcess Define if we are currently in post process mode or not + */ + ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) { + if (forPostProcess === void 0) { forPostProcess = false; } + if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) { + defines.VIGNETTE = false; + defines.TONEMAPPING = false; + defines.TONEMAPPING_ACES = false; + defines.CONTRAST = false; + defines.EXPOSURE = false; + defines.COLORCURVES = false; + defines.COLORGRADING = false; + defines.COLORGRADING3D = false; + defines.IMAGEPROCESSING = false; + defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled; + return; + } + defines.VIGNETTE = this.vignetteEnabled; + defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY); + defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY; + defines.TONEMAPPING = this.toneMappingEnabled; + switch (this._toneMappingType) { + case ImageProcessingConfiguration.TONEMAPPING_ACES: + defines.TONEMAPPING_ACES = true; + break; + default: + defines.TONEMAPPING_ACES = false; + break; + } + defines.CONTRAST = (this.contrast !== 1.0); + defines.EXPOSURE = (this.exposure !== 1.0); + defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves); + defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture); + if (defines.COLORGRADING) { + defines.COLORGRADING3D = this.colorGradingTexture.is3D; + } + else { + defines.COLORGRADING3D = false; + } + defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth; + defines.SAMPLER3DBGRMAP = this.colorGradingBGR; + defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess; + defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING; + }; + /** + * Returns true if all the image processing information are ready. + * @returns True if ready, otherwise, false + */ + ImageProcessingConfiguration.prototype.isReady = function () { + // Color Grading texure can not be none blocking. + return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady(); + }; + /** + * Binds the image processing to the shader. + * @param effect The effect to bind to + * @param aspectRatio Define the current aspect ratio of the effect + */ + ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) { + if (aspectRatio === void 0) { aspectRatio = 1; } + // Color Curves + if (this._colorCurvesEnabled && this.colorCurves) { + _Materials_colorCurves__WEBPACK_IMPORTED_MODULE_6__["ColorCurves"].Bind(this.colorCurves, effect); + } + // Vignette + if (this._vignetteEnabled) { + var inverseWidth = 1 / effect.getEngine().getRenderWidth(); + var inverseHeight = 1 / effect.getEngine().getRenderHeight(); + effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight); + var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5); + var vignetteScaleX = vignetteScaleY * aspectRatio; + var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY); + vignetteScaleX = _Misc_tools__WEBPACK_IMPORTED_MODULE_3__["Tools"].Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch); + vignetteScaleY = _Misc_tools__WEBPACK_IMPORTED_MODULE_3__["Tools"].Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch); + effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY); + var vignettePower = -2.0 * this.vignetteWeight; + effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower); + } + // Exposure + effect.setFloat("exposureLinear", this.exposure); + // Contrast + effect.setFloat("contrast", this.contrast); + // Color transform settings + if (this.colorGradingTexture) { + effect.setTexture("txColorTransform", this.colorGradingTexture); + var textureSize = this.colorGradingTexture.getSize().height; + effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale + 0.5 / textureSize, // textureOffset + textureSize, // textureSize + this.colorGradingTexture.level // weight + ); + } + }; + /** + * Clones the current image processing instance. + * @return The cloned image processing + */ + ImageProcessingConfiguration.prototype.clone = function () { + return _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Clone(function () { return new ImageProcessingConfiguration(); }, this); + }; + /** + * Serializes the current image processing instance to a json representation. + * @return a JSON representation + */ + ImageProcessingConfiguration.prototype.serialize = function () { + return _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(this); + }; + /** + * Parses the image processing from a json representation. + * @param source the JSON source to parse + * @return The parsed image processing + */ + ImageProcessingConfiguration.Parse = function (source) { + return _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null); + }; + Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", { + /** + * Used to apply the vignette as a mix with the pixel color. + */ + get: function () { + return this._VIGNETTEMODE_MULTIPLY; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", { + /** + * Used to apply the vignette as a replacement of the pixel color. + */ + get: function () { + return this._VIGNETTEMODE_OPAQUE; + }, + enumerable: true, + configurable: true + }); + /** + * Default tone mapping applied in BabylonJS. + */ + ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0; + /** + * ACES Tone mapping (used by default in unreal and unity). This can help getting closer + * to other engines rendering to increase portability. + */ + ImageProcessingConfiguration.TONEMAPPING_ACES = 1; + // Static constants associated to the image processing. + ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0; + ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1; + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColorCurves"])() + ], ImageProcessingConfiguration.prototype, "colorCurves", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])("colorGradingTexture") + ], ImageProcessingConfiguration.prototype, "_colorGradingTexture", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ImageProcessingConfiguration.prototype, "_exposure", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ImageProcessingConfiguration.prototype, "_contrast", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor4"])() + ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0); + return ImageProcessingConfiguration; +}()); + +// References the dependencies. +_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"]._ImageProcessingConfigurationParser = ImageProcessingConfiguration.Parse; + + +/***/ }), + +/***/ "./Materials/index.ts": +/*!****************************!*\ + !*** ./Materials/index.ts ***! + \****************************/ +/*! exports provided: ColorCurves, EffectFallbacks, EffectCreationOptions, Effect, FresnelParameters, ImageProcessingConfigurationDefines, ImageProcessingConfiguration, Material, MaterialDefines, MaterialHelper, MultiMaterial, PushMaterial, ShaderMaterial, StandardMaterialDefines, StandardMaterial, BaseTexture, CubeTexture, DynamicTexture, EquiRectangularCubeTexture, HDRCubeTexture, InternalTexture, MirrorTexture, MultiRenderTarget, RawTexture, RenderTargetTexture, Texture, UniformBuffer, MaterialFlags, BackgroundMaterial, PBRMaterialDefines, PBRBaseMaterial, PBRBaseSimpleMaterial, PBRMaterial, PBRMetallicRoughnessMaterial, PBRSpecularGlossinessMaterial, ColorGradingTexture, RawCubeTexture, RawTexture3D, RefractionTexture, VideoTexture, HtmlElementTexture, NodeMaterialBlockTargets, NodeMaterialBlockConnectionPointTypes, NodeMaterialConnectionPoint, NodeMaterialBlock, NodeMaterialDefines, NodeMaterial, NodeMaterialWellKnownValues, _DDSTextureLoader, _ENVTextureLoader, _KTXTextureLoader, _TGATextureLoader, CustomProceduralTexture, NoiseProceduralTexture, ProceduralTexture, ProceduralTextureSceneComponent, MultiplyBlock, AddBlock, ClampBlock, Vector2TransformBlock, Vector3TransformBlock, Vector4TransformBlock, MatrixMultiplicationBlock, NodeMaterialOptimizer, VertexOutputBlock, BonesBlock, InstancesBlock, MorphTargetsBlock, FragmentOutputBlock, AlphaTestBlock, RGBAMergerBlock, RGBMergerBlock, RGBASplitterBlock, RGBSplitterBlock, TextureBlock, ImageProcessingBlock, FogBlock */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Background_index__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Background/index */ "./Materials/Background/index.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BackgroundMaterial", function() { return _Background_index__WEBPACK_IMPORTED_MODULE_0__["BackgroundMaterial"]; }); + +/* harmony import */ var _colorCurves__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./colorCurves */ "./Materials/colorCurves.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ColorCurves", function() { return _colorCurves__WEBPACK_IMPORTED_MODULE_1__["ColorCurves"]; }); + +/* harmony import */ var _effect__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./effect */ "./Materials/effect.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EffectFallbacks", function() { return _effect__WEBPACK_IMPORTED_MODULE_2__["EffectFallbacks"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EffectCreationOptions", function() { return _effect__WEBPACK_IMPORTED_MODULE_2__["EffectCreationOptions"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Effect", function() { return _effect__WEBPACK_IMPORTED_MODULE_2__["Effect"]; }); + +/* harmony import */ var _fresnelParameters__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./fresnelParameters */ "./Materials/fresnelParameters.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FresnelParameters", function() { return _fresnelParameters__WEBPACK_IMPORTED_MODULE_3__["FresnelParameters"]; }); + +/* harmony import */ var _imageProcessingConfiguration__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./imageProcessingConfiguration */ "./Materials/imageProcessingConfiguration.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ImageProcessingConfigurationDefines", function() { return _imageProcessingConfiguration__WEBPACK_IMPORTED_MODULE_4__["ImageProcessingConfigurationDefines"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ImageProcessingConfiguration", function() { return _imageProcessingConfiguration__WEBPACK_IMPORTED_MODULE_4__["ImageProcessingConfiguration"]; }); + +/* harmony import */ var _material__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./material */ "./Materials/material.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Material", function() { return _material__WEBPACK_IMPORTED_MODULE_5__["Material"]; }); + +/* harmony import */ var _materialDefines__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./materialDefines */ "./Materials/materialDefines.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MaterialDefines", function() { return _materialDefines__WEBPACK_IMPORTED_MODULE_6__["MaterialDefines"]; }); + +/* harmony import */ var _materialHelper__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./materialHelper */ "./Materials/materialHelper.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MaterialHelper", function() { return _materialHelper__WEBPACK_IMPORTED_MODULE_7__["MaterialHelper"]; }); + +/* harmony import */ var _multiMaterial__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./multiMaterial */ "./Materials/multiMaterial.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MultiMaterial", function() { return _multiMaterial__WEBPACK_IMPORTED_MODULE_8__["MultiMaterial"]; }); + +/* harmony import */ var _PBR_index__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./PBR/index */ "./Materials/PBR/index.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRMaterialDefines", function() { return _PBR_index__WEBPACK_IMPORTED_MODULE_9__["PBRMaterialDefines"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRBaseMaterial", function() { return _PBR_index__WEBPACK_IMPORTED_MODULE_9__["PBRBaseMaterial"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRBaseSimpleMaterial", function() { return _PBR_index__WEBPACK_IMPORTED_MODULE_9__["PBRBaseSimpleMaterial"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRMaterial", function() { return _PBR_index__WEBPACK_IMPORTED_MODULE_9__["PBRMaterial"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRMetallicRoughnessMaterial", function() { return _PBR_index__WEBPACK_IMPORTED_MODULE_9__["PBRMetallicRoughnessMaterial"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRSpecularGlossinessMaterial", function() { return _PBR_index__WEBPACK_IMPORTED_MODULE_9__["PBRSpecularGlossinessMaterial"]; }); + +/* harmony import */ var _pushMaterial__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./pushMaterial */ "./Materials/pushMaterial.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PushMaterial", function() { return _pushMaterial__WEBPACK_IMPORTED_MODULE_10__["PushMaterial"]; }); + +/* harmony import */ var _shaderMaterial__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./shaderMaterial */ "./Materials/shaderMaterial.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ShaderMaterial", function() { return _shaderMaterial__WEBPACK_IMPORTED_MODULE_11__["ShaderMaterial"]; }); + +/* harmony import */ var _standardMaterial__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./standardMaterial */ "./Materials/standardMaterial.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StandardMaterialDefines", function() { return _standardMaterial__WEBPACK_IMPORTED_MODULE_12__["StandardMaterialDefines"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StandardMaterial", function() { return _standardMaterial__WEBPACK_IMPORTED_MODULE_12__["StandardMaterial"]; }); + +/* harmony import */ var _Textures_index__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./Textures/index */ "./Materials/Textures/index.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BaseTexture", function() { return _Textures_index__WEBPACK_IMPORTED_MODULE_13__["BaseTexture"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CubeTexture", function() { return _Textures_index__WEBPACK_IMPORTED_MODULE_13__["CubeTexture"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DynamicTexture", function() { return _Textures_index__WEBPACK_IMPORTED_MODULE_13__["DynamicTexture"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EquiRectangularCubeTexture", function() { return _Textures_index__WEBPACK_IMPORTED_MODULE_13__["EquiRectangularCubeTexture"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HDRCubeTexture", function() { return _Textures_index__WEBPACK_IMPORTED_MODULE_13__["HDRCubeTexture"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InternalTexture", function() { return _Textures_index__WEBPACK_IMPORTED_MODULE_13__["InternalTexture"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MirrorTexture", function() { return _Textures_index__WEBPACK_IMPORTED_MODULE_13__["MirrorTexture"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MultiRenderTarget", function() { return _Textures_index__WEBPACK_IMPORTED_MODULE_13__["MultiRenderTarget"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RawTexture", function() { return _Textures_index__WEBPACK_IMPORTED_MODULE_13__["RawTexture"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RenderTargetTexture", function() { return _Textures_index__WEBPACK_IMPORTED_MODULE_13__["RenderTargetTexture"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Texture", function() { return _Textures_index__WEBPACK_IMPORTED_MODULE_13__["Texture"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ColorGradingTexture", function() { return _Textures_index__WEBPACK_IMPORTED_MODULE_13__["ColorGradingTexture"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RawCubeTexture", function() { return _Textures_index__WEBPACK_IMPORTED_MODULE_13__["RawCubeTexture"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RawTexture3D", function() { return _Textures_index__WEBPACK_IMPORTED_MODULE_13__["RawTexture3D"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RefractionTexture", function() { return _Textures_index__WEBPACK_IMPORTED_MODULE_13__["RefractionTexture"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VideoTexture", function() { return _Textures_index__WEBPACK_IMPORTED_MODULE_13__["VideoTexture"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HtmlElementTexture", function() { return _Textures_index__WEBPACK_IMPORTED_MODULE_13__["HtmlElementTexture"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_DDSTextureLoader", function() { return _Textures_index__WEBPACK_IMPORTED_MODULE_13__["_DDSTextureLoader"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_ENVTextureLoader", function() { return _Textures_index__WEBPACK_IMPORTED_MODULE_13__["_ENVTextureLoader"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_KTXTextureLoader", function() { return _Textures_index__WEBPACK_IMPORTED_MODULE_13__["_KTXTextureLoader"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_TGATextureLoader", function() { return _Textures_index__WEBPACK_IMPORTED_MODULE_13__["_TGATextureLoader"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CustomProceduralTexture", function() { return _Textures_index__WEBPACK_IMPORTED_MODULE_13__["CustomProceduralTexture"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NoiseProceduralTexture", function() { return _Textures_index__WEBPACK_IMPORTED_MODULE_13__["NoiseProceduralTexture"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ProceduralTexture", function() { return _Textures_index__WEBPACK_IMPORTED_MODULE_13__["ProceduralTexture"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ProceduralTextureSceneComponent", function() { return _Textures_index__WEBPACK_IMPORTED_MODULE_13__["ProceduralTextureSceneComponent"]; }); + +/* harmony import */ var _uniformBuffer__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./uniformBuffer */ "./Materials/uniformBuffer.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UniformBuffer", function() { return _uniformBuffer__WEBPACK_IMPORTED_MODULE_14__["UniformBuffer"]; }); + +/* harmony import */ var _materialFlags__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./materialFlags */ "./Materials/materialFlags.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MaterialFlags", function() { return _materialFlags__WEBPACK_IMPORTED_MODULE_15__["MaterialFlags"]; }); + +/* harmony import */ var _Node_index__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./Node/index */ "./Materials/Node/index.ts"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialBlockTargets", function() { return _Node_index__WEBPACK_IMPORTED_MODULE_16__["NodeMaterialBlockTargets"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialBlockConnectionPointTypes", function() { return _Node_index__WEBPACK_IMPORTED_MODULE_16__["NodeMaterialBlockConnectionPointTypes"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialConnectionPoint", function() { return _Node_index__WEBPACK_IMPORTED_MODULE_16__["NodeMaterialConnectionPoint"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialBlock", function() { return _Node_index__WEBPACK_IMPORTED_MODULE_16__["NodeMaterialBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialDefines", function() { return _Node_index__WEBPACK_IMPORTED_MODULE_16__["NodeMaterialDefines"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterial", function() { return _Node_index__WEBPACK_IMPORTED_MODULE_16__["NodeMaterial"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialWellKnownValues", function() { return _Node_index__WEBPACK_IMPORTED_MODULE_16__["NodeMaterialWellKnownValues"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MultiplyBlock", function() { return _Node_index__WEBPACK_IMPORTED_MODULE_16__["MultiplyBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AddBlock", function() { return _Node_index__WEBPACK_IMPORTED_MODULE_16__["AddBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ClampBlock", function() { return _Node_index__WEBPACK_IMPORTED_MODULE_16__["ClampBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Vector2TransformBlock", function() { return _Node_index__WEBPACK_IMPORTED_MODULE_16__["Vector2TransformBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Vector3TransformBlock", function() { return _Node_index__WEBPACK_IMPORTED_MODULE_16__["Vector3TransformBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Vector4TransformBlock", function() { return _Node_index__WEBPACK_IMPORTED_MODULE_16__["Vector4TransformBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MatrixMultiplicationBlock", function() { return _Node_index__WEBPACK_IMPORTED_MODULE_16__["MatrixMultiplicationBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialOptimizer", function() { return _Node_index__WEBPACK_IMPORTED_MODULE_16__["NodeMaterialOptimizer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VertexOutputBlock", function() { return _Node_index__WEBPACK_IMPORTED_MODULE_16__["VertexOutputBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BonesBlock", function() { return _Node_index__WEBPACK_IMPORTED_MODULE_16__["BonesBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InstancesBlock", function() { return _Node_index__WEBPACK_IMPORTED_MODULE_16__["InstancesBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MorphTargetsBlock", function() { return _Node_index__WEBPACK_IMPORTED_MODULE_16__["MorphTargetsBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FragmentOutputBlock", function() { return _Node_index__WEBPACK_IMPORTED_MODULE_16__["FragmentOutputBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AlphaTestBlock", function() { return _Node_index__WEBPACK_IMPORTED_MODULE_16__["AlphaTestBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RGBAMergerBlock", function() { return _Node_index__WEBPACK_IMPORTED_MODULE_16__["RGBAMergerBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RGBMergerBlock", function() { return _Node_index__WEBPACK_IMPORTED_MODULE_16__["RGBMergerBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RGBASplitterBlock", function() { return _Node_index__WEBPACK_IMPORTED_MODULE_16__["RGBASplitterBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RGBSplitterBlock", function() { return _Node_index__WEBPACK_IMPORTED_MODULE_16__["RGBSplitterBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TextureBlock", function() { return _Node_index__WEBPACK_IMPORTED_MODULE_16__["TextureBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ImageProcessingBlock", function() { return _Node_index__WEBPACK_IMPORTED_MODULE_16__["ImageProcessingBlock"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FogBlock", function() { return _Node_index__WEBPACK_IMPORTED_MODULE_16__["FogBlock"]; }); + + + + + + + + + + + + + + + + + + + + +/***/ }), + +/***/ "./Materials/material.ts": +/*!*******************************!*\ + !*** ./Materials/material.ts ***! + \*******************************/ +/*! exports provided: Material */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Material", function() { return Material; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/tools */ "./Misc/tools.ts"); +/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Engines_engineStore__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Engines/engineStore */ "./Engines/engineStore.ts"); +/* harmony import */ var _Meshes_subMesh__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Meshes/subMesh */ "./Meshes/subMesh.ts"); +/* harmony import */ var _uniformBuffer__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./uniformBuffer */ "./Materials/uniformBuffer.ts"); +/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts"); +/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts"); + + + + + + + + + + +/** + * Base class for the main features of a material in Babylon.js + */ +var Material = /** @class */ (function () { + /** + * Creates a material instance + * @param name defines the name of the material + * @param scene defines the scene to reference + * @param doNotAdd specifies if the material should be added to the scene + */ + function Material(name, scene, doNotAdd) { + /** + * Gets or sets user defined metadata + */ + this.metadata = null; + /** + * For internal use only. Please do not use. + */ + this.reservedDataStore = null; + /** + * Specifies if the ready state should be checked on each call + */ + this.checkReadyOnEveryCall = false; + /** + * Specifies if the ready state should be checked once + */ + this.checkReadyOnlyOnce = false; + /** + * The state of the material + */ + this.state = ""; + /** + * The alpha value of the material + */ + this._alpha = 1.0; + /** + * Specifies if back face culling is enabled + */ + this._backFaceCulling = true; + /** + * Callback triggered when the material is compiled + */ + this.onCompiled = null; + /** + * Callback triggered when an error occurs + */ + this.onError = null; + /** + * Callback triggered to get the render target textures + */ + this.getRenderTargetTextures = null; + /** + * Specifies if the material should be serialized + */ + this.doNotSerialize = false; + /** + * @hidden + */ + this._storeEffectOnSubMeshes = false; + /** + * Stores the animations for the material + */ + this.animations = null; + /** + * An event triggered when the material is disposed + */ + this.onDisposeObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_3__["Observable"](); + /** + * An observer which watches for dispose events + */ + this._onDisposeObserver = null; + this._onUnBindObservable = null; + /** + * An observer which watches for bind events + */ + this._onBindObserver = null; + /** + * Stores the value of the alpha mode + */ + this._alphaMode = _Engines_constants__WEBPACK_IMPORTED_MODULE_8__["Constants"].ALPHA_COMBINE; + /** + * Stores the state of the need depth pre-pass value + */ + this._needDepthPrePass = false; + /** + * Specifies if depth writing should be disabled + */ + this.disableDepthWrite = false; + /** + * Specifies if depth writing should be forced + */ + this.forceDepthWrite = false; + /** + * Specifies if there should be a separate pass for culling + */ + this.separateCullingPass = false; + /** + * Stores the state specifing if fog should be enabled + */ + this._fogEnabled = true; + /** + * Stores the size of points + */ + this.pointSize = 1.0; + /** + * Stores the z offset value + */ + this.zOffset = 0; + /** + * @hidden + * Stores the effects for the material + */ + this._effect = null; + /** + * @hidden + * Specifies if the material was previously ready + */ + this._wasPreviouslyReady = false; + /** + * Specifies if uniform buffers should be used + */ + this._useUBO = false; + /** + * Stores the fill mode state + */ + this._fillMode = Material.TriangleFillMode; + /** + * Specifies if the depth write state should be cached + */ + this._cachedDepthWriteState = false; + /** @hidden */ + this._indexInSceneMaterialArray = -1; + /** @hidden */ + this.meshMap = null; + this.name = name; + this.id = name || _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].RandomId(); + this._scene = scene || _Engines_engineStore__WEBPACK_IMPORTED_MODULE_5__["EngineStore"].LastCreatedScene; + this.uniqueId = this._scene.getUniqueId(); + if (this._scene.useRightHandedSystem) { + this.sideOrientation = Material.ClockWiseSideOrientation; + } + else { + this.sideOrientation = Material.CounterClockWiseSideOrientation; + } + this._uniformBuffer = new _uniformBuffer__WEBPACK_IMPORTED_MODULE_7__["UniformBuffer"](this._scene.getEngine()); + this._useUBO = this.getScene().getEngine().supportsUniformBuffers; + if (!doNotAdd) { + this._scene.addMaterial(this); + } + if (this._scene.useMaterialMeshMap) { + this.meshMap = {}; + } + } + Object.defineProperty(Material.prototype, "alpha", { + /** + * Gets the alpha value of the material + */ + get: function () { + return this._alpha; + }, + /** + * Sets the alpha value of the material + */ + set: function (value) { + if (this._alpha === value) { + return; + } + this._alpha = value; + this.markAsDirty(Material.MiscDirtyFlag); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Material.prototype, "backFaceCulling", { + /** + * Gets the back-face culling state + */ + get: function () { + return this._backFaceCulling; + }, + /** + * Sets the back-face culling state + */ + set: function (value) { + if (this._backFaceCulling === value) { + return; + } + this._backFaceCulling = value; + this.markAsDirty(Material.TextureDirtyFlag); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Material.prototype, "hasRenderTargetTextures", { + /** + * Gets a boolean indicating that current material needs to register RTT + */ + get: function () { + return false; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Material.prototype, "onDispose", { + /** + * Called during a dispose event + */ + set: function (callback) { + if (this._onDisposeObserver) { + this.onDisposeObservable.remove(this._onDisposeObserver); + } + this._onDisposeObserver = this.onDisposeObservable.add(callback); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Material.prototype, "onBindObservable", { + /** + * An event triggered when the material is bound + */ + get: function () { + if (!this._onBindObservable) { + this._onBindObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_3__["Observable"](); + } + return this._onBindObservable; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Material.prototype, "onBind", { + /** + * Called during a bind event + */ + set: function (callback) { + if (this._onBindObserver) { + this.onBindObservable.remove(this._onBindObserver); + } + this._onBindObserver = this.onBindObservable.add(callback); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Material.prototype, "onUnBindObservable", { + /** + * An event triggered when the material is unbound + */ + get: function () { + if (!this._onUnBindObservable) { + this._onUnBindObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_3__["Observable"](); + } + return this._onUnBindObservable; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Material.prototype, "alphaMode", { + /** + * Gets the value of the alpha mode + */ + get: function () { + return this._alphaMode; + }, + /** + * Sets the value of the alpha mode. + * + * | Value | Type | Description | + * | --- | --- | --- | + * | 0 | ALPHA_DISABLE | | + * | 1 | ALPHA_ADD | | + * | 2 | ALPHA_COMBINE | | + * | 3 | ALPHA_SUBTRACT | | + * | 4 | ALPHA_MULTIPLY | | + * | 5 | ALPHA_MAXIMIZED | | + * | 6 | ALPHA_ONEONE | | + * | 7 | ALPHA_PREMULTIPLIED | | + * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | | + * | 9 | ALPHA_INTERPOLATE | | + * | 10 | ALPHA_SCREENMODE | | + * + */ + set: function (value) { + if (this._alphaMode === value) { + return; + } + this._alphaMode = value; + this.markAsDirty(Material.TextureDirtyFlag); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Material.prototype, "needDepthPrePass", { + /** + * Gets the depth pre-pass value + */ + get: function () { + return this._needDepthPrePass; + }, + /** + * Sets the need depth pre-pass value + */ + set: function (value) { + if (this._needDepthPrePass === value) { + return; + } + this._needDepthPrePass = value; + if (this._needDepthPrePass) { + this.checkReadyOnEveryCall = true; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Material.prototype, "fogEnabled", { + /** + * Gets the value of the fog enabled state + */ + get: function () { + return this._fogEnabled; + }, + /** + * Sets the state for enabling fog + */ + set: function (value) { + if (this._fogEnabled === value) { + return; + } + this._fogEnabled = value; + this.markAsDirty(Material.MiscDirtyFlag); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Material.prototype, "wireframe", { + /** + * Gets a value specifying if wireframe mode is enabled + */ + get: function () { + switch (this._fillMode) { + case Material.WireFrameFillMode: + case Material.LineListDrawMode: + case Material.LineLoopDrawMode: + case Material.LineStripDrawMode: + return true; + } + return this._scene.forceWireframe; + }, + /** + * Sets the state of wireframe mode + */ + set: function (value) { + this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Material.prototype, "pointsCloud", { + /** + * Gets the value specifying if point clouds are enabled + */ + get: function () { + switch (this._fillMode) { + case Material.PointFillMode: + case Material.PointListDrawMode: + return true; + } + return this._scene.forcePointsCloud; + }, + /** + * Sets the state of point cloud mode + */ + set: function (value) { + this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Material.prototype, "fillMode", { + /** + * Gets the material fill mode + */ + get: function () { + return this._fillMode; + }, + /** + * Sets the material fill mode + */ + set: function (value) { + if (this._fillMode === value) { + return; + } + this._fillMode = value; + this.markAsDirty(Material.MiscDirtyFlag); + }, + enumerable: true, + configurable: true + }); + /** + * Returns a string representation of the current material + * @param fullDetails defines a boolean indicating which levels of logging is desired + * @returns a string with material information + */ + Material.prototype.toString = function (fullDetails) { + var ret = "Name: " + this.name; + if (fullDetails) { + } + return ret; + }; + /** + * Gets the class name of the material + * @returns a string with the class name of the material + */ + Material.prototype.getClassName = function () { + return "Material"; + }; + Object.defineProperty(Material.prototype, "isFrozen", { + /** + * Specifies if updates for the material been locked + */ + get: function () { + return this.checkReadyOnlyOnce; + }, + enumerable: true, + configurable: true + }); + /** + * Locks updates for the material + */ + Material.prototype.freeze = function () { + this.checkReadyOnlyOnce = true; + }; + /** + * Unlocks updates for the material + */ + Material.prototype.unfreeze = function () { + this.checkReadyOnlyOnce = false; + }; + /** + * Specifies if the material is ready to be used + * @param mesh defines the mesh to check + * @param useInstances specifies if instances should be used + * @returns a boolean indicating if the material is ready to be used + */ + Material.prototype.isReady = function (mesh, useInstances) { + return true; + }; + /** + * Specifies that the submesh is ready to be used + * @param mesh defines the mesh to check + * @param subMesh defines which submesh to check + * @param useInstances specifies that instances should be used + * @returns a boolean indicating that the submesh is ready or not + */ + Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) { + return false; + }; + /** + * Returns the material effect + * @returns the effect associated with the material + */ + Material.prototype.getEffect = function () { + return this._effect; + }; + /** + * Returns the current scene + * @returns a Scene + */ + Material.prototype.getScene = function () { + return this._scene; + }; + /** + * Specifies if the material will require alpha blending + * @returns a boolean specifying if alpha blending is needed + */ + Material.prototype.needAlphaBlending = function () { + return (this.alpha < 1.0); + }; + /** + * Specifies if the mesh will require alpha blending + * @param mesh defines the mesh to check + * @returns a boolean specifying if alpha blending is needed for the mesh + */ + Material.prototype.needAlphaBlendingForMesh = function (mesh) { + return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha; + }; + /** + * Specifies if this material should be rendered in alpha test mode + * @returns a boolean specifying if an alpha test is needed. + */ + Material.prototype.needAlphaTesting = function () { + return false; + }; + /** + * Gets the texture used for the alpha test + * @returns the texture to use for alpha testing + */ + Material.prototype.getAlphaTestTexture = function () { + return null; + }; + /** + * Marks the material to indicate that it needs to be re-calculated + */ + Material.prototype.markDirty = function () { + this._wasPreviouslyReady = false; + }; + /** @hidden */ + Material.prototype._preBind = function (effect, overrideOrientation) { + if (overrideOrientation === void 0) { overrideOrientation = null; } + var engine = this._scene.getEngine(); + var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation; + var reverse = orientation === Material.ClockWiseSideOrientation; + engine.enableEffect(effect ? effect : this._effect); + engine.setState(this.backFaceCulling, this.zOffset, false, reverse); + return reverse; + }; + /** + * Binds the material to the mesh + * @param world defines the world transformation matrix + * @param mesh defines the mesh to bind the material to + */ + Material.prototype.bind = function (world, mesh) { + }; + /** + * Binds the submesh to the material + * @param world defines the world transformation matrix + * @param mesh defines the mesh containing the submesh + * @param subMesh defines the submesh to bind the material to + */ + Material.prototype.bindForSubMesh = function (world, mesh, subMesh) { + }; + /** + * Binds the world matrix to the material + * @param world defines the world transformation matrix + */ + Material.prototype.bindOnlyWorldMatrix = function (world) { + }; + /** + * Binds the scene's uniform buffer to the effect. + * @param effect defines the effect to bind to the scene uniform buffer + * @param sceneUbo defines the uniform buffer storing scene data + */ + Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) { + sceneUbo.bindToEffect(effect, "Scene"); + }; + /** + * Binds the view matrix to the effect + * @param effect defines the effect to bind the view matrix to + */ + Material.prototype.bindView = function (effect) { + if (!this._useUBO) { + effect.setMatrix("view", this.getScene().getViewMatrix()); + } + else { + this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer()); + } + }; + /** + * Binds the view projection matrix to the effect + * @param effect defines the effect to bind the view projection matrix to + */ + Material.prototype.bindViewProjection = function (effect) { + if (!this._useUBO) { + effect.setMatrix("viewProjection", this.getScene().getTransformMatrix()); + } + else { + this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer()); + } + }; + /** + * Specifies if material alpha testing should be turned on for the mesh + * @param mesh defines the mesh to check + */ + Material.prototype._shouldTurnAlphaTestOn = function (mesh) { + return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting()); + }; + /** + * Processes to execute after binding the material to a mesh + * @param mesh defines the rendered mesh + */ + Material.prototype._afterBind = function (mesh) { + this._scene._cachedMaterial = this; + if (mesh) { + this._scene._cachedVisibility = mesh.visibility; + } + else { + this._scene._cachedVisibility = 1; + } + if (this._onBindObservable && mesh) { + this._onBindObservable.notifyObservers(mesh); + } + if (this.disableDepthWrite) { + var engine = this._scene.getEngine(); + this._cachedDepthWriteState = engine.getDepthWrite(); + engine.setDepthWrite(false); + } + }; + /** + * Unbinds the material from the mesh + */ + Material.prototype.unbind = function () { + if (this._onUnBindObservable) { + this._onUnBindObservable.notifyObservers(this); + } + if (this.disableDepthWrite) { + var engine = this._scene.getEngine(); + engine.setDepthWrite(this._cachedDepthWriteState); + } + }; + /** + * Gets the active textures from the material + * @returns an array of textures + */ + Material.prototype.getActiveTextures = function () { + return []; + }; + /** + * Specifies if the material uses a texture + * @param texture defines the texture to check against the material + * @returns a boolean specifying if the material uses the texture + */ + Material.prototype.hasTexture = function (texture) { + return false; + }; + /** + * Makes a duplicate of the material, and gives it a new name + * @param name defines the new name for the duplicated material + * @returns the cloned material + */ + Material.prototype.clone = function (name) { + return null; + }; + /** + * Gets the meshes bound to the material + * @returns an array of meshes bound to the material + */ + Material.prototype.getBindedMeshes = function () { + var _this = this; + if (this.meshMap) { + var result = new Array(); + for (var meshId in this.meshMap) { + var mesh = this.meshMap[meshId]; + if (mesh) { + result.push(mesh); + } + } + return result; + } + else { + var meshes = this._scene.meshes; + return meshes.filter(function (mesh) { return mesh.material === _this; }); + } + }; + /** + * Force shader compilation + * @param mesh defines the mesh associated with this material + * @param onCompiled defines a function to execute once the material is compiled + * @param options defines the options to configure the compilation + */ + Material.prototype.forceCompilation = function (mesh, onCompiled, options) { + var _this = this; + var localOptions = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({ clipPlane: false }, options); + var subMesh = new _Meshes_subMesh__WEBPACK_IMPORTED_MODULE_6__["BaseSubMesh"](); + var scene = this.getScene(); + var checkReady = function () { + if (!_this._scene || !_this._scene.getEngine()) { + return; + } + if (subMesh._materialDefines) { + subMesh._materialDefines._renderId = -1; + } + var clipPlaneState = scene.clipPlane; + if (localOptions.clipPlane) { + scene.clipPlane = new _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Plane"](0, 0, 0, 1); + } + if (_this._storeEffectOnSubMeshes) { + if (_this.isReadyForSubMesh(mesh, subMesh)) { + if (onCompiled) { + onCompiled(_this); + } + } + else { + setTimeout(checkReady, 16); + } + } + else { + if (_this.isReady()) { + if (onCompiled) { + onCompiled(_this); + } + } + else { + setTimeout(checkReady, 16); + } + } + if (localOptions.clipPlane) { + scene.clipPlane = clipPlaneState; + } + }; + checkReady(); + }; + /** + * Force shader compilation + * @param mesh defines the mesh that will use this material + * @param options defines additional options for compiling the shaders + * @returns a promise that resolves when the compilation completes + */ + Material.prototype.forceCompilationAsync = function (mesh, options) { + var _this = this; + return new Promise(function (resolve) { + _this.forceCompilation(mesh, function () { + resolve(); + }, options); + }); + }; + /** + * Marks a define in the material to indicate that it needs to be re-computed + * @param flag defines a flag used to determine which parts of the material have to be marked as dirty + */ + Material.prototype.markAsDirty = function (flag) { + if (this.getScene().blockMaterialDirtyMechanism) { + return; + } + Material._DirtyCallbackArray.length = 0; + if (flag & Material.TextureDirtyFlag) { + Material._DirtyCallbackArray.push(Material._TextureDirtyCallBack); + } + if (flag & Material.LightDirtyFlag) { + Material._DirtyCallbackArray.push(Material._LightsDirtyCallBack); + } + if (flag & Material.FresnelDirtyFlag) { + Material._DirtyCallbackArray.push(Material._FresnelDirtyCallBack); + } + if (flag & Material.AttributesDirtyFlag) { + Material._DirtyCallbackArray.push(Material._AttributeDirtyCallBack); + } + if (flag & Material.MiscDirtyFlag) { + Material._DirtyCallbackArray.push(Material._MiscDirtyCallBack); + } + if (Material._DirtyCallbackArray.length) { + this._markAllSubMeshesAsDirty(Material._RunDirtyCallBacks); + } + this.getScene().resetCachedMaterial(); + }; + /** + * Marks all submeshes of a material to indicate that their material defines need to be re-calculated + * @param func defines a function which checks material defines against the submeshes + */ + Material.prototype._markAllSubMeshesAsDirty = function (func) { + if (this.getScene().blockMaterialDirtyMechanism) { + return; + } + var meshes = this.getScene().meshes; + for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) { + var mesh = meshes_1[_i]; + if (!mesh.subMeshes) { + continue; + } + for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) { + var subMesh = _b[_a]; + if (subMesh.getMaterial() !== this) { + continue; + } + if (!subMesh._materialDefines) { + continue; + } + func(subMesh._materialDefines); + } + } + }; + /** + * Indicates that we need to re-calculated for all submeshes + */ + Material.prototype._markAllSubMeshesAsAllDirty = function () { + this._markAllSubMeshesAsDirty(Material._AllDirtyCallBack); + }; + /** + * Indicates that image processing needs to be re-calculated for all submeshes + */ + Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () { + this._markAllSubMeshesAsDirty(Material._ImageProcessingDirtyCallBack); + }; + /** + * Indicates that textures need to be re-calculated for all submeshes + */ + Material.prototype._markAllSubMeshesAsTexturesDirty = function () { + this._markAllSubMeshesAsDirty(Material._TextureDirtyCallBack); + }; + /** + * Indicates that fresnel needs to be re-calculated for all submeshes + */ + Material.prototype._markAllSubMeshesAsFresnelDirty = function () { + this._markAllSubMeshesAsDirty(Material._FresnelDirtyCallBack); + }; + /** + * Indicates that fresnel and misc need to be re-calculated for all submeshes + */ + Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () { + this._markAllSubMeshesAsDirty(Material._FresnelAndMiscDirtyCallBack); + }; + /** + * Indicates that lights need to be re-calculated for all submeshes + */ + Material.prototype._markAllSubMeshesAsLightsDirty = function () { + this._markAllSubMeshesAsDirty(Material._LightsDirtyCallBack); + }; + /** + * Indicates that attributes need to be re-calculated for all submeshes + */ + Material.prototype._markAllSubMeshesAsAttributesDirty = function () { + this._markAllSubMeshesAsDirty(Material._AttributeDirtyCallBack); + }; + /** + * Indicates that misc needs to be re-calculated for all submeshes + */ + Material.prototype._markAllSubMeshesAsMiscDirty = function () { + this._markAllSubMeshesAsDirty(Material._MiscDirtyCallBack); + }; + /** + * Indicates that textures and misc need to be re-calculated for all submeshes + */ + Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () { + this._markAllSubMeshesAsDirty(Material._TextureAndMiscDirtyCallBack); + }; + /** + * Disposes the material + * @param forceDisposeEffect specifies if effects should be forcefully disposed + * @param forceDisposeTextures specifies if textures should be forcefully disposed + * @param notBoundToMesh specifies if the material that is being disposed is known to be not bound to any mesh + */ + Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures, notBoundToMesh) { + var scene = this.getScene(); + // Animations + scene.stopAnimation(this); + scene.freeProcessedMaterials(); + // Remove from scene + scene.removeMaterial(this); + if (notBoundToMesh !== true) { + // Remove from meshes + if (this.meshMap) { + for (var meshId in this.meshMap) { + var mesh = this.meshMap[meshId]; + if (mesh) { + mesh.material = null; // will set the entry in the map to undefined + this.releaseVertexArrayObject(mesh, forceDisposeEffect); + } + } + } + else { + var meshes = scene.meshes; + for (var _i = 0, meshes_2 = meshes; _i < meshes_2.length; _i++) { + var mesh = meshes_2[_i]; + if (mesh.material === this && !mesh.sourceMesh) { + mesh.material = null; + this.releaseVertexArrayObject(mesh, forceDisposeEffect); + } + } + } + } + this._uniformBuffer.dispose(); + // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect + if (forceDisposeEffect && this._effect) { + if (!this._storeEffectOnSubMeshes) { + this._effect.dispose(); + } + this._effect = null; + } + // Callback + this.onDisposeObservable.notifyObservers(this); + this.onDisposeObservable.clear(); + if (this._onBindObservable) { + this._onBindObservable.clear(); + } + if (this._onUnBindObservable) { + this._onUnBindObservable.clear(); + } + }; + /** @hidden */ + Material.prototype.releaseVertexArrayObject = function (mesh, forceDisposeEffect) { + if (mesh.geometry) { + var geometry = (mesh.geometry); + if (this._storeEffectOnSubMeshes) { + for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) { + var subMesh = _a[_i]; + geometry._releaseVertexArrayObject(subMesh._materialEffect); + if (forceDisposeEffect && subMesh._materialEffect) { + subMesh._materialEffect.dispose(); + } + } + } + else { + geometry._releaseVertexArrayObject(this._effect); + } + } + }; + /** + * Serializes this material + * @returns the serialized material object + */ + Material.prototype.serialize = function () { + return _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(this); + }; + /** + * Creates a material from parsed material data + * @param parsedMaterial defines parsed material data + * @param scene defines the hosting scene + * @param rootUrl defines the root URL to use to load textures + * @returns a new material + */ + Material.Parse = function (parsedMaterial, scene, rootUrl) { + if (!parsedMaterial.customType) { + parsedMaterial.customType = "BABYLON.StandardMaterial"; + } + else if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) { + parsedMaterial.customType = "BABYLON.LegacyPBRMaterial"; + if (!BABYLON.LegacyPBRMaterial) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_9__["Logger"].Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library."); + return null; + } + } + var materialType = _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].Instantiate(parsedMaterial.customType); + return materialType.Parse(parsedMaterial, scene, rootUrl); + }; + /** + * Returns the triangle fill mode + */ + Material.TriangleFillMode = _Engines_constants__WEBPACK_IMPORTED_MODULE_8__["Constants"].MATERIAL_TriangleFillMode; + /** + * Returns the wireframe mode + */ + Material.WireFrameFillMode = _Engines_constants__WEBPACK_IMPORTED_MODULE_8__["Constants"].MATERIAL_WireFrameFillMode; + /** + * Returns the point fill mode + */ + Material.PointFillMode = _Engines_constants__WEBPACK_IMPORTED_MODULE_8__["Constants"].MATERIAL_PointFillMode; + /** + * Returns the point list draw mode + */ + Material.PointListDrawMode = _Engines_constants__WEBPACK_IMPORTED_MODULE_8__["Constants"].MATERIAL_PointListDrawMode; + /** + * Returns the line list draw mode + */ + Material.LineListDrawMode = _Engines_constants__WEBPACK_IMPORTED_MODULE_8__["Constants"].MATERIAL_LineListDrawMode; + /** + * Returns the line loop draw mode + */ + Material.LineLoopDrawMode = _Engines_constants__WEBPACK_IMPORTED_MODULE_8__["Constants"].MATERIAL_LineLoopDrawMode; + /** + * Returns the line strip draw mode + */ + Material.LineStripDrawMode = _Engines_constants__WEBPACK_IMPORTED_MODULE_8__["Constants"].MATERIAL_LineStripDrawMode; + /** + * Returns the triangle strip draw mode + */ + Material.TriangleStripDrawMode = _Engines_constants__WEBPACK_IMPORTED_MODULE_8__["Constants"].MATERIAL_TriangleStripDrawMode; + /** + * Returns the triangle fan draw mode + */ + Material.TriangleFanDrawMode = _Engines_constants__WEBPACK_IMPORTED_MODULE_8__["Constants"].MATERIAL_TriangleFanDrawMode; + /** + * Stores the clock-wise side orientation + */ + Material.ClockWiseSideOrientation = _Engines_constants__WEBPACK_IMPORTED_MODULE_8__["Constants"].MATERIAL_ClockWiseSideOrientation; + /** + * Stores the counter clock-wise side orientation + */ + Material.CounterClockWiseSideOrientation = _Engines_constants__WEBPACK_IMPORTED_MODULE_8__["Constants"].MATERIAL_CounterClockWiseSideOrientation; + /** + * The dirty texture flag value + */ + Material.TextureDirtyFlag = _Engines_constants__WEBPACK_IMPORTED_MODULE_8__["Constants"].MATERIAL_TextureDirtyFlag; + /** + * The dirty light flag value + */ + Material.LightDirtyFlag = _Engines_constants__WEBPACK_IMPORTED_MODULE_8__["Constants"].MATERIAL_LightDirtyFlag; + /** + * The dirty fresnel flag value + */ + Material.FresnelDirtyFlag = _Engines_constants__WEBPACK_IMPORTED_MODULE_8__["Constants"].MATERIAL_FresnelDirtyFlag; + /** + * The dirty attribute flag value + */ + Material.AttributesDirtyFlag = _Engines_constants__WEBPACK_IMPORTED_MODULE_8__["Constants"].MATERIAL_AttributesDirtyFlag; + /** + * The dirty misc flag value + */ + Material.MiscDirtyFlag = _Engines_constants__WEBPACK_IMPORTED_MODULE_8__["Constants"].MATERIAL_MiscDirtyFlag; + /** + * The all dirty flag value + */ + Material.AllDirtyFlag = _Engines_constants__WEBPACK_IMPORTED_MODULE_8__["Constants"].MATERIAL_AllDirtyFlag; + Material._AllDirtyCallBack = function (defines) { return defines.markAllAsDirty(); }; + Material._ImageProcessingDirtyCallBack = function (defines) { return defines.markAsImageProcessingDirty(); }; + Material._TextureDirtyCallBack = function (defines) { return defines.markAsTexturesDirty(); }; + Material._FresnelDirtyCallBack = function (defines) { return defines.markAsFresnelDirty(); }; + Material._MiscDirtyCallBack = function (defines) { return defines.markAsMiscDirty(); }; + Material._LightsDirtyCallBack = function (defines) { return defines.markAsLightDirty(); }; + Material._AttributeDirtyCallBack = function (defines) { return defines.markAsAttributesDirty(); }; + Material._FresnelAndMiscDirtyCallBack = function (defines) { + Material._FresnelDirtyCallBack(defines); + Material._MiscDirtyCallBack(defines); + }; + Material._TextureAndMiscDirtyCallBack = function (defines) { + Material._TextureDirtyCallBack(defines); + Material._MiscDirtyCallBack(defines); + }; + Material._DirtyCallbackArray = []; + Material._RunDirtyCallBacks = function (defines) { + for (var _i = 0, _a = Material._DirtyCallbackArray; _i < _a.length; _i++) { + var cb = _a[_i]; + cb(defines); + } + }; + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], Material.prototype, "id", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], Material.prototype, "uniqueId", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], Material.prototype, "name", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], Material.prototype, "checkReadyOnEveryCall", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], Material.prototype, "checkReadyOnlyOnce", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], Material.prototype, "state", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])("alpha") + ], Material.prototype, "_alpha", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])("backFaceCulling") + ], Material.prototype, "_backFaceCulling", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], Material.prototype, "sideOrientation", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])("alphaMode") + ], Material.prototype, "_alphaMode", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], Material.prototype, "_needDepthPrePass", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], Material.prototype, "disableDepthWrite", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], Material.prototype, "forceDepthWrite", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], Material.prototype, "separateCullingPass", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])("fogEnabled") + ], Material.prototype, "_fogEnabled", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], Material.prototype, "pointSize", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], Material.prototype, "zOffset", void 0); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], Material.prototype, "wireframe", null); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], Material.prototype, "pointsCloud", null); + tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ + Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() + ], Material.prototype, "fillMode", null); + return Material; +}()); + + + +/***/ }), + +/***/ "./Materials/materialDefines.ts": +/*!**************************************!*\ + !*** ./Materials/materialDefines.ts ***! + \**************************************/ +/*! exports provided: MaterialDefines */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MaterialDefines", function() { return MaterialDefines; }); +/** + * Manages the defines for the Material + */ +var MaterialDefines = /** @class */ (function () { + function MaterialDefines() { + this._isDirty = true; + /** @hidden */ + this._areLightsDirty = true; + /** @hidden */ + this._areAttributesDirty = true; + /** @hidden */ + this._areTexturesDirty = true; + /** @hidden */ + this._areFresnelDirty = true; + /** @hidden */ + this._areMiscDirty = true; + /** @hidden */ + this._areImageProcessingDirty = true; + /** @hidden */ + this._normals = false; + /** @hidden */ + this._uvs = false; + /** @hidden */ + this._needNormals = false; + /** @hidden */ + this._needUVs = false; + } + Object.defineProperty(MaterialDefines.prototype, "isDirty", { + /** + * Specifies if the material needs to be re-calculated + */ + get: function () { + return this._isDirty; + }, + enumerable: true, + configurable: true + }); + /** + * Marks the material to indicate that it has been re-calculated + */ + MaterialDefines.prototype.markAsProcessed = function () { + this._isDirty = false; + this._areAttributesDirty = false; + this._areTexturesDirty = false; + this._areFresnelDirty = false; + this._areLightsDirty = false; + this._areMiscDirty = false; + this._areImageProcessingDirty = false; + }; + /** + * Marks the material to indicate that it needs to be re-calculated + */ + MaterialDefines.prototype.markAsUnprocessed = function () { + this._isDirty = true; + }; + /** + * Marks the material to indicate all of its defines need to be re-calculated + */ + MaterialDefines.prototype.markAllAsDirty = function () { + this._areTexturesDirty = true; + this._areAttributesDirty = true; + this._areLightsDirty = true; + this._areFresnelDirty = true; + this._areMiscDirty = true; + this._areImageProcessingDirty = true; + this._isDirty = true; + }; + /** + * Marks the material to indicate that image processing needs to be re-calculated + */ + MaterialDefines.prototype.markAsImageProcessingDirty = function () { + this._areImageProcessingDirty = true; + this._isDirty = true; + }; + /** + * Marks the material to indicate the lights need to be re-calculated + */ + MaterialDefines.prototype.markAsLightDirty = function () { + this._areLightsDirty = true; + this._isDirty = true; + }; + /** + * Marks the attribute state as changed + */ + MaterialDefines.prototype.markAsAttributesDirty = function () { + this._areAttributesDirty = true; + this._isDirty = true; + }; + /** + * Marks the texture state as changed + */ + MaterialDefines.prototype.markAsTexturesDirty = function () { + this._areTexturesDirty = true; + this._isDirty = true; + }; + /** + * Marks the fresnel state as changed + */ + MaterialDefines.prototype.markAsFresnelDirty = function () { + this._areFresnelDirty = true; + this._isDirty = true; + }; + /** + * Marks the misc state as changed + */ + MaterialDefines.prototype.markAsMiscDirty = function () { + this._areMiscDirty = true; + this._isDirty = true; + }; + /** + * Rebuilds the material defines + */ + MaterialDefines.prototype.rebuild = function () { + if (this._keys) { + delete this._keys; + } + this._keys = []; + for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) { + var key = _a[_i]; + if (key[0] === "_") { + continue; + } + this._keys.push(key); + } + }; + /** + * Specifies if two material defines are equal + * @param other - A material define instance to compare to + * @returns - Boolean indicating if the material defines are equal (true) or not (false) + */ + MaterialDefines.prototype.isEqual = function (other) { + if (this._keys.length !== other._keys.length) { + return false; + } + for (var index = 0; index < this._keys.length; index++) { + var prop = this._keys[index]; + if (this[prop] !== other[prop]) { + return false; + } + } + return true; + }; + /** + * Clones this instance's defines to another instance + * @param other - material defines to clone values to + */ + MaterialDefines.prototype.cloneTo = function (other) { + if (this._keys.length !== other._keys.length) { + other._keys = this._keys.slice(0); + } + for (var index = 0; index < this._keys.length; index++) { + var prop = this._keys[index]; + other[prop] = this[prop]; + } + }; + /** + * Resets the material define values + */ + MaterialDefines.prototype.reset = function () { + for (var index = 0; index < this._keys.length; index++) { + var prop = this._keys[index]; + var type = typeof this[prop]; + switch (type) { + case "number": + this[prop] = 0; + break; + case "string": + this[prop] = ""; + break; + default: + this[prop] = false; + break; + } + } + }; + /** + * Converts the material define values to a string + * @returns - String of material define information + */ + MaterialDefines.prototype.toString = function () { + var result = ""; + for (var index = 0; index < this._keys.length; index++) { + var prop = this._keys[index]; + var value = this[prop]; + var type = typeof value; + switch (type) { + case "number": + case "string": + result += "#define " + prop + " " + value + "\n"; + break; + default: + if (value) { + result += "#define " + prop + "\n"; + } + break; + } + } + return result; + }; + return MaterialDefines; +}()); + + + +/***/ }), + +/***/ "./Materials/materialFlags.ts": +/*!************************************!*\ + !*** ./Materials/materialFlags.ts ***! + \************************************/ +/*! exports provided: MaterialFlags */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MaterialFlags", function() { return MaterialFlags; }); +/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Engines/engine */ "./Engines/engine.ts"); +/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts"); + + +/** + * This groups all the flags used to control the materials channel. + */ +var MaterialFlags = /** @class */ (function () { + function MaterialFlags() { + } + Object.defineProperty(MaterialFlags, "DiffuseTextureEnabled", { + /** + * Are diffuse textures enabled in the application. + */ + get: function () { + return this._DiffuseTextureEnabled; + }, + set: function (value) { + if (this._DiffuseTextureEnabled === value) { + return; + } + this._DiffuseTextureEnabled = value; + _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].MarkAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].MATERIAL_TextureDirtyFlag); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(MaterialFlags, "AmbientTextureEnabled", { + /** + * Are ambient textures enabled in the application. + */ + get: function () { + return this._AmbientTextureEnabled; + }, + set: function (value) { + if (this._AmbientTextureEnabled === value) { + return; + } + this._AmbientTextureEnabled = value; + _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].MarkAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].MATERIAL_TextureDirtyFlag); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(MaterialFlags, "OpacityTextureEnabled", { + /** + * Are opacity textures enabled in the application. + */ + get: function () { + return this._OpacityTextureEnabled; + }, + set: function (value) { + if (this._OpacityTextureEnabled === value) { + return; + } + this._OpacityTextureEnabled = value; + _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].MarkAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].MATERIAL_TextureDirtyFlag); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(MaterialFlags, "ReflectionTextureEnabled", { + /** + * Are reflection textures enabled in the application. + */ + get: function () { + return this._ReflectionTextureEnabled; + }, + set: function (value) { + if (this._ReflectionTextureEnabled === value) { + return; + } + this._ReflectionTextureEnabled = value; + _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].MarkAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].MATERIAL_TextureDirtyFlag); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(MaterialFlags, "EmissiveTextureEnabled", { + /** + * Are emissive textures enabled in the application. + */ + get: function () { + return this._EmissiveTextureEnabled; + }, + set: function (value) { + if (this._EmissiveTextureEnabled === value) { + return; + } + this._EmissiveTextureEnabled = value; + _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].MarkAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].MATERIAL_TextureDirtyFlag); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(MaterialFlags, "SpecularTextureEnabled", { + /** + * Are specular textures enabled in the application. + */ + get: function () { + return this._SpecularTextureEnabled; + }, + set: function (value) { + if (this._SpecularTextureEnabled === value) { + return; + } + this._SpecularTextureEnabled = value; + _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].MarkAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].MATERIAL_TextureDirtyFlag); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(MaterialFlags, "BumpTextureEnabled", { + /** + * Are bump textures enabled in the application. + */ + get: function () { + return this._BumpTextureEnabled; + }, + set: function (value) { + if (this._BumpTextureEnabled === value) { + return; + } + this._BumpTextureEnabled = value; + _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].MarkAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].MATERIAL_TextureDirtyFlag); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(MaterialFlags, "LightmapTextureEnabled", { + /** + * Are lightmap textures enabled in the application. + */ + get: function () { + return this._LightmapTextureEnabled; + }, + set: function (value) { + if (this._LightmapTextureEnabled === value) { + return; + } + this._LightmapTextureEnabled = value; + _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].MarkAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].MATERIAL_TextureDirtyFlag); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(MaterialFlags, "RefractionTextureEnabled", { + /** + * Are refraction textures enabled in the application. + */ + get: function () { + return this._RefractionTextureEnabled; + }, + set: function (value) { + if (this._RefractionTextureEnabled === value) { + return; + } + this._RefractionTextureEnabled = value; + _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].MarkAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].MATERIAL_TextureDirtyFlag); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(MaterialFlags, "ColorGradingTextureEnabled", { + /** + * Are color grading textures enabled in the application. + */ + get: function () { + return this._ColorGradingTextureEnabled; + }, + set: function (value) { + if (this._ColorGradingTextureEnabled === value) { + return; + } + this._ColorGradingTextureEnabled = value; + _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].MarkAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].MATERIAL_TextureDirtyFlag); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(MaterialFlags, "FresnelEnabled", { + /** + * Are fresnels enabled in the application. + */ + get: function () { + return this._FresnelEnabled; + }, + set: function (value) { + if (this._FresnelEnabled === value) { + return; + } + this._FresnelEnabled = value; + _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].MarkAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].MATERIAL_FresnelDirtyFlag); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(MaterialFlags, "ClearCoatTextureEnabled", { + /** + * Are clear coat textures enabled in the application. + */ + get: function () { + return this._ClearCoatTextureEnabled; + }, + set: function (value) { + if (this._ClearCoatTextureEnabled === value) { + return; + } + this._ClearCoatTextureEnabled = value; + _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].MarkAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].MATERIAL_TextureDirtyFlag); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(MaterialFlags, "ClearCoatBumpTextureEnabled", { + /** + * Are clear coat bump textures enabled in the application. + */ + get: function () { + return this._ClearCoatBumpTextureEnabled; + }, + set: function (value) { + if (this._ClearCoatBumpTextureEnabled === value) { + return; + } + this._ClearCoatBumpTextureEnabled = value; + _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].MarkAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].MATERIAL_TextureDirtyFlag); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(MaterialFlags, "ClearCoatTintTextureEnabled", { + /** + * Are clear coat tint textures enabled in the application. + */ + get: function () { + return this._ClearCoatTintTextureEnabled; + }, + set: function (value) { + if (this._ClearCoatTintTextureEnabled === value) { + return; + } + this._ClearCoatTintTextureEnabled = value; + _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].MarkAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].MATERIAL_TextureDirtyFlag); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(MaterialFlags, "SheenTextureEnabled", { + /** + * Are sheen textures enabled in the application. + */ + get: function () { + return this._SheenTextureEnabled; + }, + set: function (value) { + if (this._SheenTextureEnabled === value) { + return; + } + this._SheenTextureEnabled = value; + _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].MarkAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].MATERIAL_TextureDirtyFlag); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(MaterialFlags, "AnisotropicTextureEnabled", { + /** + * Are anisotropic textures enabled in the application. + */ + get: function () { + return this._AnisotropicTextureEnabled; + }, + set: function (value) { + if (this._AnisotropicTextureEnabled === value) { + return; + } + this._AnisotropicTextureEnabled = value; + _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].MarkAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].MATERIAL_TextureDirtyFlag); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(MaterialFlags, "ThicknessTextureEnabled", { + /** + * Are thickness textures enabled in the application. + */ + get: function () { + return this._ThicknessTextureEnabled; + }, + set: function (value) { + if (this._ThicknessTextureEnabled === value) { + return; + } + this._ThicknessTextureEnabled = value; + _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].MarkAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].MATERIAL_TextureDirtyFlag); + }, + enumerable: true, + configurable: true + }); + // Flags used to enable or disable a type of texture for all Standard Materials + MaterialFlags._DiffuseTextureEnabled = true; + MaterialFlags._AmbientTextureEnabled = true; + MaterialFlags._OpacityTextureEnabled = true; + MaterialFlags._ReflectionTextureEnabled = true; + MaterialFlags._EmissiveTextureEnabled = true; + MaterialFlags._SpecularTextureEnabled = true; + MaterialFlags._BumpTextureEnabled = true; + MaterialFlags._LightmapTextureEnabled = true; + MaterialFlags._RefractionTextureEnabled = true; + MaterialFlags._ColorGradingTextureEnabled = true; + MaterialFlags._FresnelEnabled = true; + MaterialFlags._ClearCoatTextureEnabled = true; + MaterialFlags._ClearCoatBumpTextureEnabled = true; + MaterialFlags._ClearCoatTintTextureEnabled = true; + MaterialFlags._SheenTextureEnabled = true; + MaterialFlags._AnisotropicTextureEnabled = true; + MaterialFlags._ThicknessTextureEnabled = true; + return MaterialFlags; +}()); + + + +/***/ }), + +/***/ "./Materials/materialHelper.ts": +/*!*************************************!*\ + !*** ./Materials/materialHelper.ts ***! + \*************************************/ +/*! exports provided: MaterialHelper */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MaterialHelper", function() { return MaterialHelper; }); +/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts"); +/* harmony import */ var _scene__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../scene */ "./scene.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Engines_engineStore__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Engines/engineStore */ "./Engines/engineStore.ts"); +/* harmony import */ var _Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Meshes/buffer */ "./Meshes/buffer.ts"); +/* harmony import */ var _Lights_light__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Lights/light */ "./Lights/light.ts"); + + + + + + +/** + * "Static Class" containing the most commonly used helper while dealing with material for + * rendering purpose. + * + * It contains the basic tools to help defining defines, binding uniform for the common part of the materials. + * + * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions. + */ +var MaterialHelper = /** @class */ (function () { + function MaterialHelper() { + } + /** + * Bind the current view position to an effect. + * @param effect The effect to be bound + * @param scene The scene the eyes position is used from + */ + MaterialHelper.BindEyePosition = function (effect, scene) { + if (scene._forcedViewPosition) { + effect.setVector3("vEyePosition", scene._forcedViewPosition); + return; + } + var globalPosition = scene.activeCamera.globalPosition; + if (!globalPosition) { + // Use WebVRFreecamera's device position as global position is not it's actual position in babylon space + globalPosition = scene.activeCamera.devicePosition; + } + effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : globalPosition); + }; + /** + * Helps preparing the defines values about the UVs in used in the effect. + * UVs are shared as much as we can accross channels in the shaders. + * @param texture The texture we are preparing the UVs for + * @param defines The defines to update + * @param key The channel key "diffuse", "specular"... used in the shader + */ + MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) { + defines._needUVs = true; + defines[key] = true; + if (texture.getTextureMatrix().isIdentityAs3x2()) { + defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1; + if (texture.coordinatesIndex === 0) { + defines["MAINUV1"] = true; + } + else { + defines["MAINUV2"] = true; + } + } + else { + defines[key + "DIRECTUV"] = 0; + } + }; + /** + * Binds a texture matrix value to its corrsponding uniform + * @param texture The texture to bind the matrix for + * @param uniformBuffer The uniform buffer receivin the data + * @param key The channel key "diffuse", "specular"... used in the shader + */ + MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) { + var matrix = texture.getTextureMatrix(); + if (!matrix.isIdentityAs3x2()) { + uniformBuffer.updateMatrix(key + "Matrix", matrix); + } + }; + /** + * Gets the current status of the fog (should it be enabled?) + * @param mesh defines the mesh to evaluate for fog support + * @param scene defines the hosting scene + * @returns true if fog must be enabled + */ + MaterialHelper.GetFogState = function (mesh, scene) { + return (scene.fogEnabled && mesh.applyFog && scene.fogMode !== _scene__WEBPACK_IMPORTED_MODULE_1__["Scene"].FOGMODE_NONE); + }; + /** + * Helper used to prepare the list of defines associated with misc. values for shader compilation + * @param mesh defines the current mesh + * @param scene defines the current scene + * @param useLogarithmicDepth defines if logarithmic depth has to be turned on + * @param pointsCloud defines if point cloud rendering has to be turned on + * @param fogEnabled defines if fog has to be turned on + * @param alphaTest defines if alpha testing has to be turned on + * @param defines defines the current list of defines + */ + MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) { + if (defines._areMiscDirty) { + defines["LOGARITHMICDEPTH"] = useLogarithmicDepth; + defines["POINTSIZE"] = pointsCloud; + defines["FOG"] = fogEnabled && this.GetFogState(mesh, scene); + defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling; + defines["ALPHATEST"] = alphaTest; + } + }; + /** + * Helper used to prepare the list of defines associated with frame values for shader compilation + * @param scene defines the current scene + * @param engine defines the current engine + * @param defines specifies the list of active defines + * @param useInstances defines if instances have to be turned on + * @param useClipPlane defines if clip plane have to be turned on + */ + MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) { + if (useClipPlane === void 0) { useClipPlane = null; } + var changed = false; + var useClipPlane1 = false; + var useClipPlane2 = false; + var useClipPlane3 = false; + var useClipPlane4 = false; + useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane; + useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane; + useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane; + useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane; + if (defines["CLIPPLANE"] !== useClipPlane1) { + defines["CLIPPLANE"] = useClipPlane1; + changed = true; + } + if (defines["CLIPPLANE2"] !== useClipPlane2) { + defines["CLIPPLANE2"] = useClipPlane2; + changed = true; + } + if (defines["CLIPPLANE3"] !== useClipPlane3) { + defines["CLIPPLANE3"] = useClipPlane3; + changed = true; + } + if (defines["CLIPPLANE4"] !== useClipPlane4) { + defines["CLIPPLANE4"] = useClipPlane4; + changed = true; + } + if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) { + defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"]; + changed = true; + } + if (defines["INSTANCES"] !== useInstances) { + defines["INSTANCES"] = useInstances; + changed = true; + } + if (changed) { + defines.markAsUnprocessed(); + } + }; + /** + * Prepares the defines for bones + * @param mesh The mesh containing the geometry data we will draw + * @param defines The defines to update + */ + MaterialHelper.PrepareDefinesForBones = function (mesh, defines) { + if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) { + defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers; + var materialSupportsBoneTexture = defines["BONETEXTURE"] !== undefined; + if (mesh.skeleton.isUsingTextureForMatrices && materialSupportsBoneTexture) { + defines["BONETEXTURE"] = true; + } + else { + defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1); + defines["BONETEXTURE"] = materialSupportsBoneTexture ? false : undefined; + } + } + else { + defines["NUM_BONE_INFLUENCERS"] = 0; + defines["BonesPerMesh"] = 0; + } + }; + /** + * Prepares the defines for morph targets + * @param mesh The mesh containing the geometry data we will draw + * @param defines The defines to update + */ + MaterialHelper.PrepareDefinesForMorphTargets = function (mesh, defines) { + var manager = mesh.morphTargetManager; + if (manager) { + defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"]; + defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"]; + defines["MORPHTARGETS"] = (manager.numInfluencers > 0); + defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers; + } + else { + defines["MORPHTARGETS_TANGENT"] = false; + defines["MORPHTARGETS_NORMAL"] = false; + defines["MORPHTARGETS"] = false; + defines["NUM_MORPH_INFLUENCERS"] = 0; + } + }; + /** + * Prepares the defines used in the shader depending on the attributes data available in the mesh + * @param mesh The mesh containing the geometry data we will draw + * @param defines The defines to update + * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info) + * @param useBones Precise whether bones should be used or not (override mesh info) + * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info) + * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info) + * @returns false if defines are considered not dirty and have not been checked + */ + MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) { + if (useMorphTargets === void 0) { useMorphTargets = false; } + if (useVertexAlpha === void 0) { useVertexAlpha = true; } + if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) { + return false; + } + defines._normals = defines._needNormals; + defines._uvs = defines._needUVs; + defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"].NormalKind)); + if (defines._needNormals && mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"].TangentKind)) { + defines["TANGENT"] = true; + } + if (defines._needUVs) { + defines["UV1"] = mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"].UVKind); + defines["UV2"] = mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"].UV2Kind); + } + else { + defines["UV1"] = false; + defines["UV2"] = false; + } + if (useVertexColor) { + var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"].ColorKind); + defines["VERTEXCOLOR"] = hasVertexColors; + defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha; + } + if (useBones) { + this.PrepareDefinesForBones(mesh, defines); + } + if (useMorphTargets) { + this.PrepareDefinesForMorphTargets(mesh, defines); + } + return true; + }; + /** + * Prepares the defines related to multiview + * @param scene The scene we are intending to draw + * @param defines The defines to update + */ + MaterialHelper.PrepareDefinesForMultiview = function (scene, defines) { + if (scene.activeCamera) { + var previousMultiview = defines.MULTIVIEW; + defines.MULTIVIEW = (scene.activeCamera.outputRenderTarget !== null && scene.activeCamera.outputRenderTarget.getViewCount() > 1); + if (defines.MULTIVIEW != previousMultiview) { + defines.markAsUnprocessed(); + } + } + }; + /** + * Prepares the defines related to the light information passed in parameter + * @param scene The scene we are intending to draw + * @param mesh The mesh the effect is compiling for + * @param defines The defines to update + * @param specularSupported Specifies whether specular is supported or not (override lights data) + * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max + * @param disableLighting Specifies whether the lighting is disabled (override scene and light) + * @returns true if normals will be required for the rest of the effect + */ + MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) { + if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; } + if (disableLighting === void 0) { disableLighting = false; } + if (!defines._areLightsDirty) { + return defines._needNormals; + } + var lightIndex = 0; + var needNormals = false; + var needRebuild = false; + var lightmapMode = false; + var shadowEnabled = false; + var specularEnabled = false; + if (scene.lightsEnabled && !disableLighting) { + for (var _i = 0, _a = mesh.lightSources; _i < _a.length; _i++) { + var light = _a[_i]; + needNormals = true; + if (defines["LIGHT" + lightIndex] === undefined) { + needRebuild = true; + } + defines["LIGHT" + lightIndex] = true; + defines["SPOTLIGHT" + lightIndex] = false; + defines["HEMILIGHT" + lightIndex] = false; + defines["POINTLIGHT" + lightIndex] = false; + defines["DIRLIGHT" + lightIndex] = false; + light.prepareLightSpecificDefines(defines, lightIndex); + // FallOff. + defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false; + defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false; + defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false; + switch (light.falloffType) { + case _Lights_light__WEBPACK_IMPORTED_MODULE_5__["Light"].FALLOFF_GLTF: + defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true; + break; + case _Lights_light__WEBPACK_IMPORTED_MODULE_5__["Light"].FALLOFF_PHYSICAL: + defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true; + break; + case _Lights_light__WEBPACK_IMPORTED_MODULE_5__["Light"].FALLOFF_STANDARD: + defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true; + break; + } + // Specular + if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) { + specularEnabled = true; + } + // Shadows + defines["SHADOW" + lightIndex] = false; + defines["SHADOWPCF" + lightIndex] = false; + defines["SHADOWPCSS" + lightIndex] = false; + defines["SHADOWPOISSON" + lightIndex] = false; + defines["SHADOWESM" + lightIndex] = false; + defines["SHADOWCUBE" + lightIndex] = false; + defines["SHADOWLOWQUALITY" + lightIndex] = false; + defines["SHADOWMEDIUMQUALITY" + lightIndex] = false; + if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) { + var shadowGenerator = light.getShadowGenerator(); + if (shadowGenerator) { + var shadowMap = shadowGenerator.getShadowMap(); + if (shadowMap) { + if (shadowMap.renderList && shadowMap.renderList.length > 0) { + shadowEnabled = true; + shadowGenerator.prepareDefines(defines, lightIndex); + } + } + } + } + if (light.lightmapMode != _Lights_light__WEBPACK_IMPORTED_MODULE_5__["Light"].LIGHTMAP_DEFAULT) { + lightmapMode = true; + defines["LIGHTMAPEXCLUDED" + lightIndex] = true; + defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == _Lights_light__WEBPACK_IMPORTED_MODULE_5__["Light"].LIGHTMAP_SHADOWSONLY); + } + else { + defines["LIGHTMAPEXCLUDED" + lightIndex] = false; + defines["LIGHTMAPNOSPECULAR" + lightIndex] = false; + } + lightIndex++; + if (lightIndex === maxSimultaneousLights) { + break; + } + } + } + defines["SPECULARTERM"] = specularEnabled; + defines["SHADOWS"] = shadowEnabled; + // Resetting all other lights if any + for (var index = lightIndex; index < maxSimultaneousLights; index++) { + if (defines["LIGHT" + index] !== undefined) { + defines["LIGHT" + index] = false; + defines["HEMILIGHT" + index] = false; + defines["POINTLIGHT" + index] = false; + defines["DIRLIGHT" + index] = false; + defines["SPOTLIGHT" + index] = false; + defines["SHADOW" + index] = false; + defines["SHADOWPCF" + index] = false; + defines["SHADOWPCSS" + index] = false; + defines["SHADOWPOISSON" + index] = false; + defines["SHADOWESM" + index] = false; + defines["SHADOWCUBE" + index] = false; + defines["SHADOWLOWQUALITY" + index] = false; + defines["SHADOWMEDIUMQUALITY" + index] = false; + } + } + var caps = scene.getEngine().getCaps(); + if (defines["SHADOWFLOAT"] === undefined) { + needRebuild = true; + } + defines["SHADOWFLOAT"] = shadowEnabled && + ((caps.textureFloatRender && caps.textureFloatLinearFiltering) || + (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering)); + defines["LIGHTMAPEXCLUDED"] = lightmapMode; + if (needRebuild) { + defines.rebuild(); + } + return needNormals; + }; + /** + * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms + * that won t be acctive due to defines being turned off. + * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information + * @param samplersList The samplers list + * @param defines The defines helping in the list generation + * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect + */ + MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) { + if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; } + var uniformsList; + var uniformBuffersList = null; + if (uniformsListOrOptions.uniformsNames) { + var options = uniformsListOrOptions; + uniformsList = options.uniformsNames; + uniformBuffersList = options.uniformBuffersNames; + samplersList = options.samplers; + defines = options.defines; + maxSimultaneousLights = options.maxSimultaneousLights; + } + else { + uniformsList = uniformsListOrOptions; + if (!samplersList) { + samplersList = []; + } + } + for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) { + if (!defines["LIGHT" + lightIndex]) { + break; + } + uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex); + if (uniformBuffersList) { + uniformBuffersList.push("Light" + lightIndex); + } + samplersList.push("shadowSampler" + lightIndex); + samplersList.push("depthSampler" + lightIndex); + if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) { + samplersList.push("projectionLightSampler" + lightIndex); + uniformsList.push("textureProjectionMatrix" + lightIndex); + } + } + if (defines["NUM_MORPH_INFLUENCERS"]) { + uniformsList.push("morphTargetInfluences"); + } + }; + /** + * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality) + * @param defines The defines to update while falling back + * @param fallbacks The authorized effect fallbacks + * @param maxSimultaneousLights The maximum number of lights allowed + * @param rank the current rank of the Effect + * @returns The newly affected rank + */ + MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) { + if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; } + if (rank === void 0) { rank = 0; } + var lightFallbackRank = 0; + for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) { + if (!defines["LIGHT" + lightIndex]) { + break; + } + if (lightIndex > 0) { + lightFallbackRank = rank + lightIndex; + fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex); + } + if (!defines["SHADOWS"]) { + if (defines["SHADOW" + lightIndex]) { + fallbacks.addFallback(rank, "SHADOW" + lightIndex); + } + if (defines["SHADOWPCF" + lightIndex]) { + fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex); + } + if (defines["SHADOWPCSS" + lightIndex]) { + fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex); + } + if (defines["SHADOWPOISSON" + lightIndex]) { + fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex); + } + if (defines["SHADOWESM" + lightIndex]) { + fallbacks.addFallback(rank, "SHADOWESM" + lightIndex); + } + } + } + return lightFallbackRank++; + }; + /** + * Prepares the list of attributes required for morph targets according to the effect defines. + * @param attribs The current list of supported attribs + * @param mesh The mesh to prepare the morph targets attributes for + * @param defines The current Defines of the effect + */ + MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) { + var influencers = defines["NUM_MORPH_INFLUENCERS"]; + if (influencers > 0 && _Engines_engineStore__WEBPACK_IMPORTED_MODULE_3__["EngineStore"].LastCreatedEngine) { + var maxAttributesCount = _Engines_engineStore__WEBPACK_IMPORTED_MODULE_3__["EngineStore"].LastCreatedEngine.getCaps().maxVertexAttribs; + var manager = mesh.morphTargetManager; + var normal = manager && manager.supportsNormals && defines["NORMAL"]; + var tangent = manager && manager.supportsTangents && defines["TANGENT"]; + for (var index = 0; index < influencers; index++) { + attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"].PositionKind + index); + if (normal) { + attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"].NormalKind + index); + } + if (tangent) { + attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"].TangentKind + index); + } + if (attribs.length > maxAttributesCount) { + _Misc_logger__WEBPACK_IMPORTED_MODULE_0__["Logger"].Error("Cannot add more vertex attributes for mesh " + mesh.name); + } + } + } + }; + /** + * Prepares the list of attributes required for bones according to the effect defines. + * @param attribs The current list of supported attribs + * @param mesh The mesh to prepare the bones attributes for + * @param defines The current Defines of the effect + * @param fallbacks The current efffect fallback strategy + */ + MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) { + if (defines["NUM_BONE_INFLUENCERS"] > 0) { + fallbacks.addCPUSkinningFallback(0, mesh); + attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"].MatricesIndicesKind); + attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"].MatricesWeightsKind); + if (defines["NUM_BONE_INFLUENCERS"] > 4) { + attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"].MatricesIndicesExtraKind); + attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"].MatricesWeightsExtraKind); + } + } + }; + /** + * Check and prepare the list of attributes required for instances according to the effect defines. + * @param attribs The current list of supported attribs + * @param defines The current MaterialDefines of the effect + */ + MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) { + if (defines["INSTANCES"]) { + this.PushAttributesForInstances(attribs); + } + }; + /** + * Add the list of attributes required for instances to the attribs array. + * @param attribs The current list of supported attribs + */ + MaterialHelper.PushAttributesForInstances = function (attribs) { + attribs.push("world0"); + attribs.push("world1"); + attribs.push("world2"); + attribs.push("world3"); + }; + /** + * Binds the light shadow information to the effect for the given mesh. + * @param light The light containing the generator + * @param scene The scene the lights belongs to + * @param mesh The mesh we are binding the information to render + * @param lightIndex The light index in the effect used to render the mesh + * @param effect The effect we are binding the data to + */ + MaterialHelper.BindLightShadow = function (light, mesh, lightIndex, effect) { + if (light.shadowEnabled && mesh.receiveShadows) { + var shadowGenerator = light.getShadowGenerator(); + if (shadowGenerator) { + shadowGenerator.bindShadowLight(lightIndex, effect); + } + } + }; + /** + * Binds the light information to the effect. + * @param light The light containing the generator + * @param effect The effect we are binding the data to + * @param lightIndex The light index in the effect used to render + */ + MaterialHelper.BindLightProperties = function (light, effect, lightIndex) { + light.transferToEffect(effect, lightIndex + ""); + }; + /** + * Binds the lights information from the scene to the effect for the given mesh. + * @param scene The scene the lights belongs to + * @param mesh The mesh we are binding the information to render + * @param effect The effect we are binding the data to + * @param defines The generated defines for the effect + * @param maxSimultaneousLights The maximum number of light that can be bound to the effect + * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not + */ + MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) { + if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; } + if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; } + var len = Math.min(mesh.lightSources.length, maxSimultaneousLights); + for (var i = 0; i < len; i++) { + var light = mesh.lightSources[i]; + var iAsString = i.toString(); + var scaledIntensity = light.getScaledIntensity(); + light._uniformBuffer.bindToEffect(effect, "Light" + i); + MaterialHelper.BindLightProperties(light, effect, i); + light.diffuse.scaleToRef(scaledIntensity, _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Tmp"].Color3[0]); + light._uniformBuffer.updateColor4("vLightDiffuse", _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Tmp"].Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString); + if (defines["SPECULARTERM"]) { + light.specular.scaleToRef(scaledIntensity, _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Tmp"].Color3[1]); + light._uniformBuffer.updateColor3("vLightSpecular", _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Tmp"].Color3[1], iAsString); + } + // Shadows + if (scene.shadowsEnabled) { + this.BindLightShadow(light, mesh, iAsString, effect); + } + light._uniformBuffer.update(); + } + }; + /** + * Binds the fog information from the scene to the effect for the given mesh. + * @param scene The scene the lights belongs to + * @param mesh The mesh we are binding the information to render + * @param effect The effect we are binding the data to + * @param linearSpace Defines if the fog effect is applied in linear space + */ + MaterialHelper.BindFogParameters = function (scene, mesh, effect, linearSpace) { + if (linearSpace === void 0) { linearSpace = false; } + if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== _scene__WEBPACK_IMPORTED_MODULE_1__["Scene"].FOGMODE_NONE) { + effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity); + // Convert fog color to linear space if used in a linear space computed shader. + if (linearSpace) { + scene.fogColor.toLinearSpaceToRef(this._tempFogColor); + effect.setColor3("vFogColor", this._tempFogColor); + } + else { + effect.setColor3("vFogColor", scene.fogColor); + } + } + }; + /** + * Binds the bones information from the mesh to the effect. + * @param mesh The mesh we are binding the information to render + * @param effect The effect we are binding the data to + */ + MaterialHelper.BindBonesParameters = function (mesh, effect) { + if (!effect || !mesh) { + return; + } + if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) { + mesh.computeBonesUsingShaders = false; + } + if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) { + var skeleton = mesh.skeleton; + if (skeleton.isUsingTextureForMatrices && effect.getUniformIndex("boneTextureWidth") > -1) { + var boneTexture = skeleton.getTransformMatrixTexture(); + effect.setTexture("boneSampler", boneTexture); + effect.setFloat("boneTextureWidth", 4.0 * (skeleton.bones.length + 1)); + } + else { + var matrices = skeleton.getTransformMatrices(mesh); + if (matrices) { + effect.setMatrices("mBones", matrices); + } + } + } + }; + /** + * Binds the morph targets information from the mesh to the effect. + * @param abstractMesh The mesh we are binding the information to render + * @param effect The effect we are binding the data to + */ + MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) { + var manager = abstractMesh.morphTargetManager; + if (!abstractMesh || !manager) { + return; + } + effect.setFloatArray("morphTargetInfluences", manager.influences); + }; + /** + * Binds the logarithmic depth information from the scene to the effect for the given defines. + * @param defines The generated defines used in the effect + * @param effect The effect we are binding the data to + * @param scene The scene we are willing to render with logarithmic scale for + */ + MaterialHelper.BindLogDepth = function (defines, effect, scene) { + if (defines["LOGARITHMICDEPTH"]) { + effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2)); + } + }; + /** + * Binds the clip plane information from the scene to the effect. + * @param scene The scene the clip plane information are extracted from + * @param effect The effect we are binding the data to + */ + MaterialHelper.BindClipPlane = function (effect, scene) { + if (scene.clipPlane) { + var clipPlane = scene.clipPlane; + effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d); + } + if (scene.clipPlane2) { + var clipPlane = scene.clipPlane2; + effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d); + } + if (scene.clipPlane3) { + var clipPlane = scene.clipPlane3; + effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d); + } + if (scene.clipPlane4) { + var clipPlane = scene.clipPlane4; + effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d); + } + }; + MaterialHelper._tempFogColor = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color3"].Black(); + return MaterialHelper; +}()); + + + +/***/ }), + +/***/ "./Materials/multiMaterial.ts": +/*!************************************!*\ + !*** ./Materials/multiMaterial.ts ***! + \************************************/ +/*! exports provided: MultiMaterial */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MultiMaterial", function() { return MultiMaterial; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Materials_material__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Materials/material */ "./Materials/material.ts"); +/* harmony import */ var _Misc_tags__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/tags */ "./Misc/tags.ts"); +/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Misc/typeStore */ "./Misc/typeStore.ts"); + + + + +/** + * A multi-material is used to apply different materials to different parts of the same object without the need of + * separate meshes. This can be use to improve performances. + * @see http://doc.babylonjs.com/how_to/multi_materials + */ +var MultiMaterial = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](MultiMaterial, _super); + /** + * Instantiates a new Multi Material + * A multi-material is used to apply different materials to different parts of the same object without the need of + * separate meshes. This can be use to improve performances. + * @see http://doc.babylonjs.com/how_to/multi_materials + * @param name Define the name in the scene + * @param scene Define the scene the material belongs to + */ + function MultiMaterial(name, scene) { + var _this = _super.call(this, name, scene, true) || this; + scene.multiMaterials.push(_this); + _this.subMaterials = new Array(); + _this._storeEffectOnSubMeshes = true; // multimaterial is considered like a push material + return _this; + } + Object.defineProperty(MultiMaterial.prototype, "subMaterials", { + /** + * Gets or Sets the list of Materials used within the multi material. + * They need to be ordered according to the submeshes order in the associated mesh + */ + get: function () { + return this._subMaterials; + }, + set: function (value) { + this._subMaterials = value; + this._hookArray(value); + }, + enumerable: true, + configurable: true + }); + /** + * Function used to align with Node.getChildren() + * @returns the list of Materials used within the multi material + */ + MultiMaterial.prototype.getChildren = function () { + return this.subMaterials; + }; + MultiMaterial.prototype._hookArray = function (array) { + var _this = this; + var oldPush = array.push; + array.push = function () { + var items = []; + for (var _i = 0; _i < arguments.length; _i++) { + items[_i] = arguments[_i]; + } + var result = oldPush.apply(array, items); + _this._markAllSubMeshesAsTexturesDirty(); + return result; + }; + var oldSplice = array.splice; + array.splice = function (index, deleteCount) { + var deleted = oldSplice.apply(array, [index, deleteCount]); + _this._markAllSubMeshesAsTexturesDirty(); + return deleted; + }; + }; + /** + * Get one of the submaterial by its index in the submaterials array + * @param index The index to look the sub material at + * @returns The Material if the index has been defined + */ + MultiMaterial.prototype.getSubMaterial = function (index) { + if (index < 0 || index >= this.subMaterials.length) { + return this.getScene().defaultMaterial; + } + return this.subMaterials[index]; + }; + /** + * Get the list of active textures for the whole sub materials list. + * @returns All the textures that will be used during the rendering + */ + MultiMaterial.prototype.getActiveTextures = function () { + var _a; + return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) { + if (subMaterial) { + return subMaterial.getActiveTextures(); + } + else { + return []; + } + })); + }; + /** + * Gets the current class name of the material e.g. "MultiMaterial" + * Mainly use in serialization. + * @returns the class name + */ + MultiMaterial.prototype.getClassName = function () { + return "MultiMaterial"; + }; + /** + * Checks if the material is ready to render the requested sub mesh + * @param mesh Define the mesh the submesh belongs to + * @param subMesh Define the sub mesh to look readyness for + * @param useInstances Define whether or not the material is used with instances + * @returns true if ready, otherwise false + */ + MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) { + for (var index = 0; index < this.subMaterials.length; index++) { + var subMaterial = this.subMaterials[index]; + if (subMaterial) { + if (subMaterial._storeEffectOnSubMeshes) { + if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) { + return false; + } + continue; + } + if (!subMaterial.isReady(mesh)) { + return false; + } + } + } + return true; + }; + /** + * Clones the current material and its related sub materials + * @param name Define the name of the newly cloned material + * @param cloneChildren Define if submaterial will be cloned or shared with the parent instance + * @returns the cloned material + */ + MultiMaterial.prototype.clone = function (name, cloneChildren) { + var newMultiMaterial = new MultiMaterial(name, this.getScene()); + for (var index = 0; index < this.subMaterials.length; index++) { + var subMaterial = null; + var current = this.subMaterials[index]; + if (cloneChildren && current) { + subMaterial = current.clone(name + "-" + current.name); + } + else { + subMaterial = this.subMaterials[index]; + } + newMultiMaterial.subMaterials.push(subMaterial); + } + return newMultiMaterial; + }; + /** + * Serializes the materials into a JSON representation. + * @returns the JSON representation + */ + MultiMaterial.prototype.serialize = function () { + var serializationObject = {}; + serializationObject.name = this.name; + serializationObject.id = this.id; + if (_Misc_tags__WEBPACK_IMPORTED_MODULE_2__["Tags"]) { + serializationObject.tags = _Misc_tags__WEBPACK_IMPORTED_MODULE_2__["Tags"].GetTags(this); + } + serializationObject.materials = []; + for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) { + var subMat = this.subMaterials[matIndex]; + if (subMat) { + serializationObject.materials.push(subMat.id); + } + else { + serializationObject.materials.push(null); + } + } + return serializationObject; + }; + /** + * Dispose the material and release its associated resources + * @param forceDisposeEffect Define if we want to force disposing the associated effect (if false the shader is not released and could be reuse later on) + * @param forceDisposeTextures Define if we want to force disposing the associated textures (if false, they will not be disposed and can still be use elsewhere in the app) + * @param forceDisposeChildren Define if we want to force disposing the associated submaterials (if false, they will not be disposed and can still be use elsewhere in the app) + */ + MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures, forceDisposeChildren) { + var scene = this.getScene(); + if (!scene) { + return; + } + if (forceDisposeChildren) { + for (var index = 0; index < this.subMaterials.length; index++) { + var subMaterial = this.subMaterials[index]; + if (subMaterial) { + subMaterial.dispose(forceDisposeEffect, forceDisposeTextures); + } + } + } + var index = scene.multiMaterials.indexOf(this); + if (index >= 0) { + scene.multiMaterials.splice(index, 1); + } + _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures); + }; + /** + * Creates a MultiMaterial from parsed MultiMaterial data. + * @param parsedMultiMaterial defines parsed MultiMaterial data. + * @param scene defines the hosting scene + * @returns a new MultiMaterial + */ + MultiMaterial.ParseMultiMaterial = function (parsedMultiMaterial, scene) { + var multiMaterial = new MultiMaterial(parsedMultiMaterial.name, scene); + multiMaterial.id = parsedMultiMaterial.id; + if (_Misc_tags__WEBPACK_IMPORTED_MODULE_2__["Tags"]) { + _Misc_tags__WEBPACK_IMPORTED_MODULE_2__["Tags"].AddTagsTo(multiMaterial, parsedMultiMaterial.tags); + } + for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) { + var subMatId = parsedMultiMaterial.materials[matIndex]; + if (subMatId) { + multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId)); + } + else { + multiMaterial.subMaterials.push(null); + } + } + return multiMaterial; + }; + return MultiMaterial; +}(_Materials_material__WEBPACK_IMPORTED_MODULE_1__["Material"])); + +_Misc_typeStore__WEBPACK_IMPORTED_MODULE_3__["_TypeStore"].RegisteredTypes["BABYLON.MultiMaterial"] = MultiMaterial; + + +/***/ }), + +/***/ "./Materials/pushMaterial.ts": +/*!***********************************!*\ + !*** ./Materials/pushMaterial.ts ***! + \***********************************/ +/*! exports provided: PushMaterial */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PushMaterial", function() { return PushMaterial; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Materials_material__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Materials/material */ "./Materials/material.ts"); + + + +/** + * Base class of materials working in push mode in babylon JS + * @hidden + */ +var PushMaterial = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PushMaterial, _super); + function PushMaterial(name, scene) { + var _this = _super.call(this, name, scene) || this; + _this._normalMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"](); + /** + * Gets or sets a boolean indicating that the material is allowed to do shader hot swapping. + * This means that the material can keep using a previous shader while a new one is being compiled. + * This is mostly used when shader parallel compilation is supported (true by default) + */ + _this.allowShaderHotSwapping = true; + _this._storeEffectOnSubMeshes = true; + return _this; + } + PushMaterial.prototype.getEffect = function () { + return this._activeEffect; + }; + PushMaterial.prototype.isReady = function (mesh, useInstances) { + if (!mesh) { + return false; + } + if (!mesh.subMeshes || mesh.subMeshes.length === 0) { + return true; + } + return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances); + }; + /** + * Binds the given world matrix to the active effect + * + * @param world the matrix to bind + */ + PushMaterial.prototype.bindOnlyWorldMatrix = function (world) { + this._activeEffect.setMatrix("world", world); + }; + /** + * Binds the given normal matrix to the active effect + * + * @param normalMatrix the matrix to bind + */ + PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) { + this._activeEffect.setMatrix("normalMatrix", normalMatrix); + }; + PushMaterial.prototype.bind = function (world, mesh) { + if (!mesh) { + return; + } + this.bindForSubMesh(world, mesh, mesh.subMeshes[0]); + }; + PushMaterial.prototype._afterBind = function (mesh, effect) { + if (effect === void 0) { effect = null; } + _super.prototype._afterBind.call(this, mesh); + this.getScene()._cachedEffect = effect; + }; + PushMaterial.prototype._mustRebind = function (scene, effect, visibility) { + if (visibility === void 0) { visibility = 1; } + return scene.isCachedMaterialInvalid(this, effect, visibility); + }; + return PushMaterial; +}(_Materials_material__WEBPACK_IMPORTED_MODULE_2__["Material"])); + + + +/***/ }), + +/***/ "./Materials/shaderMaterial.ts": +/*!*************************************!*\ + !*** ./Materials/shaderMaterial.ts ***! + \*************************************/ +/*! exports provided: ShaderMaterial */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ShaderMaterial", function() { return ShaderMaterial; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); +/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts"); +/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); +/* harmony import */ var _Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Meshes/buffer */ "./Meshes/buffer.ts"); +/* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Materials/Textures/texture */ "./Materials/Textures/texture.ts"); +/* harmony import */ var _materialHelper__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./materialHelper */ "./Materials/materialHelper.ts"); +/* harmony import */ var _effect__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./effect */ "./Materials/effect.ts"); +/* harmony import */ var _material__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./material */ "./Materials/material.ts"); +/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Misc/typeStore */ "./Misc/typeStore.ts"); + + + + + + + + + +/** + * The ShaderMaterial object has the necessary methods to pass data from your scene to the Vertex and Fragment Shaders and returns a material that can be applied to any mesh. + * + * This returned material effects how the mesh will look based on the code in the shaders. + * + * @see http://doc.babylonjs.com/how_to/shader_material + */ +var ShaderMaterial = /** @class */ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ShaderMaterial, _super); + /** + * Instantiate a new shader material. + * The ShaderMaterial object has the necessary methods to pass data from your scene to the Vertex and Fragment Shaders and returns a material that can be applied to any mesh. + * This returned material effects how the mesh will look based on the code in the shaders. + * @see http://doc.babylonjs.com/how_to/shader_material + * @param name Define the name of the material in the scene + * @param scene Define the scene the material belongs to + * @param shaderPath Defines the route to the shader code in one of three ways: + * - object - { vertex: "custom", fragment: "custom" }, used with Effect.ShadersStore["customVertexShader"] and Effect.ShadersStore["customFragmentShader"] + * - object - { vertexElement: "vertexShaderCode", fragmentElement: "fragmentShaderCode" }, used with shader code in